@seip/bluebird-js 0.0.0-stage → 0.0.1

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 (73) hide show
  1. package/.env_example +54 -0
  2. package/AGENTS.md +403 -0
  3. package/LICENSE +21 -0
  4. package/README.md +284 -2
  5. package/app/routes/api.js +50 -0
  6. package/app/routes/web.js +53 -0
  7. package/app/views/about.html +161 -0
  8. package/app/views/dashboard.html +140 -0
  9. package/app/views/index.html +150 -0
  10. package/app/views/login.html +144 -0
  11. package/core/app.d.ts +18 -0
  12. package/core/app.js +644 -0
  13. package/core/auth.d.ts +13 -0
  14. package/core/auth.js +326 -0
  15. package/core/cache.d.ts +17 -0
  16. package/core/cache.js +475 -0
  17. package/core/cli/doctor.js +287 -0
  18. package/core/cli/ecosystem.js +162 -0
  19. package/core/cli/init.js +779 -0
  20. package/core/cli/migrate.js +541 -0
  21. package/core/cli/model.js +66 -0
  22. package/core/cli/nginx.js +199 -0
  23. package/core/cli/route.js +121 -0
  24. package/core/cli/swagger.js +45 -0
  25. package/core/cli/view.js +77 -0
  26. package/core/config.d.ts +3 -0
  27. package/core/config.js +111 -0
  28. package/core/csrf.d.ts +3 -0
  29. package/core/csrf.js +114 -0
  30. package/core/database.d.ts +15 -0
  31. package/core/database.js +636 -0
  32. package/core/debug.d.ts +3 -0
  33. package/core/debug.js +250 -0
  34. package/core/hash.d.ts +3 -0
  35. package/core/hash.js +194 -0
  36. package/core/index.d.ts +1071 -0
  37. package/core/logger.d.ts +3 -0
  38. package/core/logger.js +124 -0
  39. package/core/middleware.d.ts +3 -0
  40. package/core/middleware.js +28 -0
  41. package/core/model.d.ts +19 -0
  42. package/core/model.js +600 -0
  43. package/core/queue.d.ts +13 -0
  44. package/core/queue.js +172 -0
  45. package/core/ratelimit.d.ts +3 -0
  46. package/core/ratelimit.js +145 -0
  47. package/core/redis.d.ts +21 -0
  48. package/core/redis.js +230 -0
  49. package/core/render.d.ts +3 -0
  50. package/core/render.js +676 -0
  51. package/core/router.d.ts +3 -0
  52. package/core/router.js +171 -0
  53. package/core/seo.d.ts +3 -0
  54. package/core/seo.js +106 -0
  55. package/core/swagger.d.ts +3 -0
  56. package/core/swagger.js +60 -0
  57. package/core/upload.d.ts +13 -0
  58. package/core/upload.js +102 -0
  59. package/core/util/colors.js +82 -0
  60. package/core/validate.d.ts +15 -0
  61. package/core/validate.js +364 -0
  62. package/core/vite.d.ts +3 -0
  63. package/core/vite.js +145 -0
  64. package/core/ws.d.ts +13 -0
  65. package/core/ws.js +245 -0
  66. package/index.js +18 -0
  67. package/jsconfig.json +15 -0
  68. package/package.json +84 -3
  69. package/production.md +273 -0
  70. package/public/css/bluebird.min.css +2 -0
  71. package/public/images/favicon.ico +0 -0
  72. package/public/js/bluebird-client.js +1663 -0
  73. package/public/js/bluebird.min.js +1073 -0
package/core/queue.js ADDED
@@ -0,0 +1,172 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { getRedisClient } from "./cache.js";
4
+
5
+ /**
6
+ * Lightweight background queue worker module with Redis and in-memory fallback.
7
+ */
8
+ class QueueManager {
9
+ constructor() {
10
+ this.handlers = new Map();
11
+ this.memoryQueue = [];
12
+ this.isProcessing = false;
13
+ this.isWorkerRunning = false;
14
+ this.shouldStop = false;
15
+ this.redisPrefix = "bluebird:queue:";
16
+ }
17
+
18
+ /**
19
+ * Registers a job handler function.
20
+ * @param {string} jobName - Name of the job.
21
+ * @param {Function} handler - Async function(payload).
22
+ */
23
+ process(jobName, handler) {
24
+ if (typeof handler !== "function") {
25
+ throw new Error(`Handler for job '${jobName}' must be a function.`);
26
+ }
27
+ this.handlers.set(jobName, handler);
28
+ }
29
+
30
+ /**
31
+ * Dispatches a new job to the queue.
32
+ * @param {string} jobName - Name of the job.
33
+ * @param {any} [payload={}] - Data payload to pass to the handler.
34
+ * @param {Object} [options={}] - Options (e.g. delayMs).
35
+ * @returns {Promise<boolean>}
36
+ */
37
+ async dispatch(jobName, payload = {}, options = {}) {
38
+ const jobItem = {
39
+ id: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
40
+ name: jobName,
41
+ payload,
42
+ createdAt: new Date().toISOString(),
43
+ };
44
+
45
+ const redis = getRedisClient();
46
+ if (redis && redis.isReady) {
47
+ try {
48
+ await redis.lPush(`${this.redisPrefix}jobs`, JSON.stringify(jobItem));
49
+ return true;
50
+ } catch (err) {
51
+ console.error("[QUEUE ERROR] Failed to dispatch job to Redis:", err.message);
52
+ }
53
+ }
54
+
55
+ if (options.delayMs && options.delayMs > 0) {
56
+ setTimeout(() => {
57
+ this.memoryQueue.push(jobItem);
58
+ this.runMemoryWorker();
59
+ }, options.delayMs);
60
+ } else {
61
+ this.memoryQueue.push(jobItem);
62
+ setImmediate(() => this.runMemoryWorker());
63
+ }
64
+
65
+ return true;
66
+ }
67
+
68
+ /**
69
+ * Starts the worker processing loop for Redis and in-memory jobs.
70
+ * @returns {Promise<void>}
71
+ */
72
+ async work() {
73
+ this.isWorkerRunning = true;
74
+ this.shouldStop = false;
75
+
76
+ const redis = getRedisClient();
77
+ if (redis && redis.isReady) {
78
+ while (!this.shouldStop) {
79
+ try {
80
+ const result = await redis.brPop(`${this.redisPrefix}jobs`, 2);
81
+ if (result && result.element) {
82
+ const job = JSON.parse(result.element);
83
+ const handler = this.handlers.get(job.name);
84
+ if (handler) {
85
+ await handler(job.payload);
86
+ } else {
87
+ console.warn(`[QUEUE WARN] No handler registered for job '${job.name}'.`);
88
+ }
89
+ }
90
+ } catch (err) {
91
+ if (!this.shouldStop) {
92
+ await new Promise((resolve) => setTimeout(resolve, 1000));
93
+ }
94
+ }
95
+ }
96
+ this.isWorkerRunning = false;
97
+ return;
98
+ }
99
+
100
+ await this.runMemoryWorker();
101
+ this.isWorkerRunning = false;
102
+ }
103
+
104
+ /**
105
+ * Stops the background worker loop.
106
+ */
107
+ stop() {
108
+ this.shouldStop = true;
109
+ }
110
+
111
+ /**
112
+ * Executes in-memory queue jobs sequentially.
113
+ * @private
114
+ */
115
+ async runMemoryWorker() {
116
+ if (this.isProcessing || this.memoryQueue.length === 0) return;
117
+ this.isProcessing = true;
118
+
119
+ while (this.memoryQueue.length > 0) {
120
+ const job = this.memoryQueue.shift();
121
+ if (!job) continue;
122
+
123
+ const handler = this.handlers.get(job.name);
124
+ if (!handler) {
125
+ console.warn(`[QUEUE WARN] No handler registered for job '${job.name}'.`);
126
+ continue;
127
+ }
128
+
129
+ try {
130
+ await handler(job.payload);
131
+ } catch (err) {
132
+ console.error(`[QUEUE ERROR] Error processing job '${job.name}' (${job.id}):`, err);
133
+ }
134
+ }
135
+
136
+ this.isProcessing = false;
137
+ }
138
+
139
+ /**
140
+ * Auto-loads all job definition files from app/jobs/ (or legacy backend/jobs/).
141
+ * @param {string} [jobsDir]
142
+ */
143
+ async loadJobs(jobsDir) {
144
+ const targetDir =
145
+ jobsDir ||
146
+ (fs.existsSync(path.resolve(process.cwd(), "app/jobs"))
147
+ ? path.resolve(process.cwd(), "app/jobs")
148
+ : path.resolve(process.cwd(), "backend/jobs"));
149
+
150
+ if (!fs.existsSync(targetDir)) return;
151
+
152
+ const files = fs
153
+ .readdirSync(targetDir)
154
+ .filter((f) => f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".ts"));
155
+
156
+ for (const file of files) {
157
+ const fullPath = path.join(targetDir, file);
158
+ try {
159
+ const module = await import(`file://${fullPath}`);
160
+ if (typeof module.default === "function") {
161
+ const jobName = path.basename(file, path.extname(file));
162
+ this.process(jobName, module.default);
163
+ }
164
+ } catch (err) {
165
+ console.error(`[QUEUE ERROR] Failed to load job file '${file}':`, err.message);
166
+ }
167
+ }
168
+ }
169
+ }
170
+
171
+ export const Queue = new QueueManager();
172
+ export default Queue;
@@ -0,0 +1,3 @@
1
+ import { RateLimit, RateLimitOptions } from "./index.js";
2
+ export default RateLimit;
3
+ export { RateLimit, RateLimitOptions };
@@ -0,0 +1,145 @@
1
+ import { getRedisClient } from "./cache.js";
2
+
3
+ /**
4
+ * In-memory store for rate limiting buckets.
5
+ * Maps client key to { count: number, resetTime: number }.
6
+ * @type {Map<string, {count: number, resetTime: number}>}
7
+ */
8
+ const memoryBuckets = new Map();
9
+
10
+ setInterval(() => {
11
+ if (memoryBuckets.size === 0) return;
12
+ const now = Date.now();
13
+ for (const [key, bucket] of memoryBuckets) {
14
+ if (bucket.resetTime <= now) {
15
+ memoryBuckets.delete(key);
16
+ }
17
+ }
18
+ }, 60000).unref();
19
+
20
+ /**
21
+ * Native zero-dependency Rate Limiter supporting in-memory and Redis backends.
22
+ */
23
+ class RateLimit {
24
+ /**
25
+ * Creates an Express rate-limiting middleware.
26
+ * @param {Object} [options={}] - Rate limit configuration options.
27
+ * @param {number} [options.windowMs=60000] - Time window in milliseconds (default: 60s).
28
+ * @param {number} [options.max=100] - Maximum requests allowed per window (default: 100).
29
+ * @param {string} [options.message="Too many requests, please try again later."] - Error message when rate limited.
30
+ * @param {number} [options.statusCode=429] - HTTP status code when rate limited.
31
+ * @param {boolean} [options.headers=true] - Whether to send X-RateLimit-* and Retry-After headers.
32
+ * @param {"memory"|"redis"} [options.driver="memory"] - Storage backend.
33
+ * @param {Function} [options.keyGenerator] - Custom key generator: (req) => string.
34
+ * @param {Function} [options.skip] - Predicate to bypass rate limiting: (req) => boolean.
35
+ * @returns {Function} Express middleware function.
36
+ */
37
+ static middleware(options = {}) {
38
+ const windowMs = options.windowMs ?? 60000;
39
+ const max = options.max ?? 100;
40
+ const message = options.message ?? "Too many requests, please try again later.";
41
+ const statusCode = options.statusCode ?? 429;
42
+ const sendHeaders = options.headers ?? true;
43
+ const driver = options.driver || "memory";
44
+ const keyGenerator =
45
+ typeof options.keyGenerator === "function"
46
+ ? options.keyGenerator
47
+ : (req) => req.ip || req.socket?.remoteAddress || "unknown";
48
+ const skip = typeof options.skip === "function" ? options.skip : null;
49
+
50
+ return async (req, res, next) => {
51
+ if (skip && skip(req)) {
52
+ return next();
53
+ }
54
+
55
+ const clientKey = `rl:${keyGenerator(req)}`;
56
+ const now = Date.now();
57
+ let count = 0;
58
+ let resetTime = now + windowMs;
59
+
60
+ const redis = driver === "redis" ? getRedisClient() : null;
61
+ if (redis) {
62
+ try {
63
+ const ttlSeconds = Math.ceil(windowMs / 1000);
64
+ count = await redis.incr(clientKey);
65
+ if (count === 1) {
66
+ await redis.expire(clientKey, ttlSeconds);
67
+ } else {
68
+ const pttl = await redis.pTTL(clientKey);
69
+ if (pttl > 0) {
70
+ resetTime = now + pttl;
71
+ }
72
+ }
73
+ } catch {
74
+ const bucket = RateLimit._incrementMemory(clientKey, now, windowMs);
75
+ count = bucket.count;
76
+ resetTime = bucket.resetTime;
77
+ }
78
+ } else {
79
+ const bucket = RateLimit._incrementMemory(clientKey, now, windowMs);
80
+ count = bucket.count;
81
+ resetTime = bucket.resetTime;
82
+ }
83
+
84
+ const remaining = Math.max(0, max - count);
85
+ const resetSeconds = Math.ceil((resetTime - now) / 1000);
86
+
87
+ if (sendHeaders) {
88
+ res.setHeader("X-RateLimit-Limit", String(max));
89
+ res.setHeader("X-RateLimit-Remaining", String(remaining));
90
+ res.setHeader("X-RateLimit-Reset", String(Math.ceil(resetTime / 1000)));
91
+ }
92
+
93
+ if (count > max) {
94
+ if (sendHeaders) {
95
+ res.setHeader("Retry-After", String(Math.max(1, resetSeconds)));
96
+ }
97
+ const expectsHtml =
98
+ req.headers.accept?.includes("text/html") && !req.path.startsWith("/api");
99
+ if (expectsHtml) {
100
+ return res.status(statusCode).send(`<h1>${statusCode} Too Many Requests</h1><p>${message}</p>`);
101
+ }
102
+ return res.status(statusCode).json({
103
+ status: "error",
104
+ message,
105
+ retryAfter: Math.max(1, resetSeconds),
106
+ });
107
+ }
108
+
109
+ next();
110
+ };
111
+ }
112
+
113
+ /**
114
+ * Increments the counter for a client key in memory.
115
+ * @private
116
+ * @param {string} key
117
+ * @param {number} now
118
+ * @param {number} windowMs
119
+ * @returns {{count: number, resetTime: number}}
120
+ */
121
+ static _incrementMemory(key, now, windowMs) {
122
+ let bucket = memoryBuckets.get(key);
123
+ if (!bucket || bucket.resetTime <= now) {
124
+ bucket = { count: 1, resetTime: now + windowMs };
125
+ if (memoryBuckets.size >= 50000) {
126
+ const oldestKey = memoryBuckets.keys().next().value;
127
+ if (oldestKey !== undefined) memoryBuckets.delete(oldestKey);
128
+ }
129
+ memoryBuckets.set(key, bucket);
130
+ } else {
131
+ bucket.count += 1;
132
+ }
133
+ return bucket;
134
+ }
135
+
136
+ /**
137
+ * Clears all rate limit buckets in memory.
138
+ */
139
+ static reset() {
140
+ memoryBuckets.clear();
141
+ }
142
+ }
143
+
144
+ export { RateLimit };
145
+ export default RateLimit;
@@ -0,0 +1,21 @@
1
+ export function initRedis(): Promise<any>;
2
+ export function getRedisClient(): any;
3
+ export function isRedisConnectedStatus(): boolean;
4
+ export function redisGet(key: string): Promise<any>;
5
+ export function redisSet(key: string, value: any, seconds?: number): Promise<boolean>;
6
+ export function redisDel(keys: string | string[]): Promise<boolean>;
7
+ export function redisClearPrefix(prefix: string): Promise<boolean>;
8
+ export function disconnectRedis(): Promise<void>;
9
+
10
+ declare const redisHandler: {
11
+ initRedis: typeof initRedis;
12
+ getRedisClient: typeof getRedisClient;
13
+ isRedisConnectedStatus: typeof isRedisConnectedStatus;
14
+ redisGet: typeof redisGet;
15
+ redisSet: typeof redisSet;
16
+ redisDel: typeof redisDel;
17
+ redisClearPrefix: typeof redisClearPrefix;
18
+ disconnectRedis: typeof disconnectRedis;
19
+ };
20
+
21
+ export default redisHandler;
package/core/redis.js ADDED
@@ -0,0 +1,230 @@
1
+ import fs from "node:fs";
2
+
3
+ /** @type {import('redis').RedisClientType|null} */
4
+ let redisClient = null;
5
+ let isRedisConnected = false;
6
+ let isRedisModuleChecked = false;
7
+ let redisModule = null;
8
+
9
+ const redisHost = process.env.REDIS_HOST || "localhost";
10
+ const redisPort = parseInt(process.env.REDIS_PORT || "6379", 10);
11
+ const redisPassword = process.env.REDIS_PASSWORD || "";
12
+
13
+ /**
14
+ * Checks whether the redis package is installed.
15
+ * @returns {Promise<any|null>}
16
+ */
17
+ async function loadRedisModule() {
18
+ if (isRedisModuleChecked) return redisModule;
19
+ isRedisModuleChecked = true;
20
+
21
+ try {
22
+ redisModule = await import("redis");
23
+ return redisModule;
24
+ } catch {
25
+ console.error(
26
+ "[REDIS ERROR] The 'redis' package is not installed. To use Redis, install it via 'npm install redis' or 'npx bluebird-js add redis'."
27
+ );
28
+ redisModule = null;
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Initializes and connects to the Redis server if available.
35
+ * @returns {Promise<import('redis').RedisClientType|null>}
36
+ */
37
+ export async function initRedis() {
38
+ if (redisClient && isRedisConnected) {
39
+ return redisClient;
40
+ }
41
+
42
+ const mod = await loadRedisModule();
43
+ if (!mod) {
44
+ return null;
45
+ }
46
+
47
+ const { createClient } = mod;
48
+ const url = redisPassword
49
+ ? `redis://:${encodeURIComponent(redisPassword)}@${redisHost}:${redisPort}`
50
+ : `redis://${redisHost}:${redisPort}`;
51
+
52
+ try {
53
+ redisClient = createClient({
54
+ url,
55
+ socket: {
56
+ connectTimeout: 1500,
57
+ reconnectStrategy: false,
58
+ },
59
+ });
60
+
61
+ redisClient.on("error", () => {
62
+ isRedisConnected = false;
63
+ });
64
+
65
+ redisClient.on("ready", () => {
66
+ isRedisConnected = true;
67
+ });
68
+
69
+ redisClient.on("connect", () => {
70
+ isRedisConnected = true;
71
+ });
72
+
73
+ redisClient.on("end", () => {
74
+ isRedisConnected = false;
75
+ });
76
+
77
+ await redisClient.connect();
78
+ isRedisConnected = true;
79
+ return redisClient;
80
+ } catch (err) {
81
+ try {
82
+ redisClient?.destroy?.();
83
+ } catch {}
84
+ redisClient = null;
85
+ isRedisConnected = false;
86
+ return null;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Returns the active Redis client instance or null if not connected.
92
+ * @returns {import('redis').RedisClientType|null}
93
+ */
94
+ export function getRedisClient() {
95
+ return isRedisConnected ? redisClient : null;
96
+ }
97
+
98
+ /**
99
+ * Checks whether Redis is connected and ready for commands.
100
+ * @returns {boolean}
101
+ */
102
+ export function isRedisConnectedStatus() {
103
+ return Boolean(isRedisConnected && redisClient);
104
+ }
105
+
106
+ /**
107
+ * Retrieves a value from Redis by key.
108
+ * @param {string} key
109
+ * @returns {Promise<any|null>}
110
+ */
111
+ export async function redisGet(key) {
112
+ const client = await initRedis();
113
+ if (!client || !isRedisConnected) return null;
114
+
115
+ try {
116
+ const raw = await client.get(key);
117
+ if (!raw) return null;
118
+ try {
119
+ return JSON.parse(raw);
120
+ } catch {
121
+ return raw;
122
+ }
123
+ } catch {
124
+ isRedisConnected = false;
125
+ return null;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Stores a value in Redis with an optional TTL in seconds.
131
+ * @param {string} key
132
+ * @param {any} value
133
+ * @param {number} [seconds=60]
134
+ * @returns {Promise<boolean>}
135
+ */
136
+ export async function redisSet(key, value, seconds = 60) {
137
+ const client = await initRedis();
138
+ if (!client || !isRedisConnected) return false;
139
+
140
+ try {
141
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
142
+ if (seconds > 0) {
143
+ await client.set(key, serialized, { EX: seconds });
144
+ } else {
145
+ await client.set(key, serialized);
146
+ }
147
+ return true;
148
+ } catch {
149
+ isRedisConnected = false;
150
+ return false;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Deletes one or more keys from Redis.
156
+ * @param {string|string[]} keys
157
+ * @returns {Promise<boolean>}
158
+ */
159
+ export async function redisDel(keys) {
160
+ const client = await initRedis();
161
+ if (!client || !isRedisConnected) return false;
162
+
163
+ try {
164
+ const keyList = Array.isArray(keys) ? keys : [keys];
165
+ if (keyList.length > 0) {
166
+ await client.del(keyList);
167
+ }
168
+ return true;
169
+ } catch {
170
+ isRedisConnected = false;
171
+ return false;
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Removes all keys matching a specific prefix from Redis.
177
+ * @param {string} prefix
178
+ * @returns {Promise<boolean>}
179
+ */
180
+ export async function redisClearPrefix(prefix) {
181
+ const client = await initRedis();
182
+ if (!client || !isRedisConnected) return false;
183
+
184
+ try {
185
+ let cursor = "0";
186
+ do {
187
+ const reply = await client.scan(cursor, {
188
+ MATCH: `${prefix}*`,
189
+ COUNT: 100,
190
+ });
191
+ cursor = String(reply.cursor);
192
+ if (reply.keys.length > 0) {
193
+ await client.del(reply.keys);
194
+ }
195
+ } while (cursor !== "0");
196
+ return true;
197
+ } catch {
198
+ isRedisConnected = false;
199
+ return false;
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Gracefully disconnects the Redis client.
205
+ * @returns {Promise<void>}
206
+ */
207
+ export async function disconnectRedis() {
208
+ if (redisClient) {
209
+ try {
210
+ await redisClient.quit();
211
+ } catch {
212
+ try {
213
+ redisClient.disconnect();
214
+ } catch {}
215
+ }
216
+ redisClient = null;
217
+ isRedisConnected = false;
218
+ }
219
+ }
220
+
221
+ export default {
222
+ initRedis,
223
+ getRedisClient,
224
+ isRedisConnected: isRedisConnectedStatus,
225
+ get: redisGet,
226
+ set: redisSet,
227
+ del: redisDel,
228
+ clearPrefix: redisClearPrefix,
229
+ disconnect: disconnectRedis,
230
+ };
@@ -0,0 +1,3 @@
1
+ import { Render } from "./index.js";
2
+ export default Render;
3
+ export { Render };