@seip/bluebird-js 0.1.1 → 0.1.4

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 (49) hide show
  1. package/.vscode/extensions.json +7 -0
  2. package/.vscode/settings.json +10 -0
  3. package/AGENTS.md +124 -64
  4. package/README.md +236 -103
  5. package/app/routes/web.js +47 -55
  6. package/app/views/about.jsx +98 -0
  7. package/app/views/components/Header.jsx +42 -0
  8. package/app/views/components/LiveCounter.jsx +67 -0
  9. package/app/views/dashboard.jsx +300 -0
  10. package/app/views/index.jsx +123 -0
  11. package/app/views/layouts/main/view.jsx +201 -0
  12. package/app/views/legal/terms.html +29 -19
  13. package/app/views/login.jsx +141 -0
  14. package/core/actions.d.ts +4 -0
  15. package/core/actions.js +329 -0
  16. package/core/app.js +129 -22
  17. package/core/auth.js +1 -1
  18. package/core/cli/doctor.js +3 -4
  19. package/core/cli/init.js +153 -6
  20. package/core/cli/migrate.js +418 -145
  21. package/core/cli/view.js +76 -11
  22. package/core/config.js +35 -5
  23. package/core/csrf.js +1 -1
  24. package/core/database.js +52 -17
  25. package/core/debug.js +1 -1
  26. package/core/html.d.ts +54 -42
  27. package/core/html.js +473 -217
  28. package/core/index.d.ts +187 -85
  29. package/core/jsx.d.ts +38 -0
  30. package/core/jsx.js +1180 -0
  31. package/core/model.js +282 -61
  32. package/core/queue.js +7 -4
  33. package/core/render-cache.js +212 -212
  34. package/core/render.d.ts +20 -2
  35. package/core/render.js +320 -43
  36. package/core/upload.js +7 -1
  37. package/core/validate.js +1 -1
  38. package/core/view-loader.js +341 -19
  39. package/core/vite.js +1 -1
  40. package/package.json +9 -3
  41. package/public/js/bluebird-client.js +2313 -1049
  42. package/public/js/tailwind.js +8 -0
  43. package/app/views/about.js +0 -63
  44. package/app/views/dashboard.js +0 -147
  45. package/app/views/index.js +0 -80
  46. package/app/views/layouts/main/view.js +0 -81
  47. package/app/views/login.js +0 -80
  48. package/public/css/bluebird.min.css +0 -2
  49. package/public/js/bluebird.min.js +0 -1073
package/core/model.js CHANGED
@@ -11,13 +11,57 @@ import Hash from "./hash.js";
11
11
  function buildWhere(where) {
12
12
  const whereClauses = [];
13
13
  const params = [];
14
+ const opMap = {
15
+ $gt: ">",
16
+ $gte: ">=",
17
+ $lt: "<",
18
+ $lte: "<=",
19
+ $ne: "!=",
20
+ $like: "LIKE",
21
+ };
14
22
 
15
23
  for (const [col, val] of Object.entries(where)) {
16
24
  if (!/^[a-zA-Z0-9_]+$/.test(col)) {
17
25
  throw new Error(`[MODEL ERROR] Invalid column identifier '${col}'`);
18
26
  }
19
- if (val === null) {
27
+
28
+ if (Array.isArray(val)) {
29
+ if (val.length === 0) {
30
+ whereClauses.push("1 = 0");
31
+ } else {
32
+ whereClauses.push(`${col} IN (${val.map(() => "?").join(", ")})`);
33
+ params.push(...val);
34
+ }
35
+ } else if (val === null) {
20
36
  whereClauses.push(`${col} IS NULL`);
37
+ } else if (typeof val === "object" && val !== null) {
38
+ for (const [op, opVal] of Object.entries(val)) {
39
+ if (op === "$in") {
40
+ if (Array.isArray(opVal) && opVal.length > 0) {
41
+ whereClauses.push(`${col} IN (${opVal.map(() => "?").join(", ")})`);
42
+ params.push(...opVal);
43
+ } else {
44
+ whereClauses.push("1 = 0");
45
+ }
46
+ } else if (op === "$nin") {
47
+ if (Array.isArray(opVal) && opVal.length > 0) {
48
+ whereClauses.push(`${col} NOT IN (${opVal.map(() => "?").join(", ")})`);
49
+ params.push(...opVal);
50
+ } else {
51
+ whereClauses.push("1 = 1");
52
+ }
53
+ } else if (op === "$notNull" && opVal) {
54
+ whereClauses.push(`${col} IS NOT NULL`);
55
+ } else if (op === "$null" && opVal) {
56
+ whereClauses.push(`${col} IS NULL`);
57
+ } else if (opMap[op]) {
58
+ whereClauses.push(`${col} ${opMap[op]} ?`);
59
+ params.push(opVal);
60
+ } else {
61
+ whereClauses.push(`${col} = ?`);
62
+ params.push(opVal);
63
+ }
64
+ }
21
65
  } else {
22
66
  whereClauses.push(`${col} = ?`);
23
67
  params.push(val);
@@ -73,6 +117,19 @@ class Model {
73
117
  /** @type {Object<string, Object>} */
74
118
  static schema = {};
75
119
 
120
+ /**
121
+ * Optional list of columns allowed in create() and update() mass assignment.
122
+ * If empty, all non-guarded schema columns are permitted.
123
+ * @type {string[]}
124
+ */
125
+ static fillable = [];
126
+
127
+ /**
128
+ * Columns protected against mass assignment when `guard: true` is passed or `guarded` is configured.
129
+ * @type {string[]}
130
+ */
131
+ static guarded = [];
132
+
76
133
  /** @type {Database|null} */
77
134
  static _dbInstance = null;
78
135
 
@@ -95,6 +152,17 @@ class Model {
95
152
  this._dbInstance = db;
96
153
  }
97
154
 
155
+ /**
156
+ * Closes the shared Model database connection.
157
+ * @returns {Promise<void>}
158
+ */
159
+ static async close() {
160
+ if (this._dbInstance) {
161
+ await this._dbInstance.close();
162
+ this._dbInstance = null;
163
+ }
164
+ }
165
+
98
166
  /**
99
167
  * Executes a direct SQL query through the model's database connection.
100
168
  * @param {string} sql - SQL query string.
@@ -284,31 +352,57 @@ class Model {
284
352
 
285
353
  const results = rows.map((r) => this.filterHidden(r, options.withHidden));
286
354
 
287
- if (options.oneMany || options.belongsTo) {
288
- for (const item of results) {
289
- if (options.oneMany) {
290
- const targets = Array.isArray(options.oneMany) ? options.oneMany : [options.oneMany];
291
- for (const target of targets) {
292
- const fk = this.resolveForeignKey(target);
293
- item[target.table] = await target.all({
294
- where: { [fk]: item[this.primaryKey] },
295
- withDeleted: options.withDeleted,
296
- withHidden: options.withHidden,
297
- });
355
+ if (results.length > 0) {
356
+ if (options.oneMany) {
357
+ const targets = Array.isArray(options.oneMany) ? options.oneMany : [options.oneMany];
358
+ const primaryKeys = results.map((r) => r[this.primaryKey]).filter((id) => id !== undefined && id !== null);
359
+
360
+ for (const target of targets) {
361
+ const fk = this.resolveForeignKey(target);
362
+ const relatedList = primaryKeys.length > 0
363
+ ? await target.all({
364
+ where: { [fk]: primaryKeys },
365
+ withDeleted: options.withDeleted,
366
+ withHidden: options.withHidden,
367
+ })
368
+ : [];
369
+
370
+ const grouped = new Map();
371
+ for (const rel of relatedList) {
372
+ const parentId = rel[fk];
373
+ if (!grouped.has(parentId)) grouped.set(parentId, []);
374
+ grouped.get(parentId).push(rel);
375
+ }
376
+
377
+ for (const item of results) {
378
+ item[target.table] = grouped.get(item[this.primaryKey]) || [];
298
379
  }
299
380
  }
300
- if (options.belongsTo) {
301
- const parents = Array.isArray(options.belongsTo) ? options.belongsTo : [options.belongsTo];
302
- for (const parent of parents) {
303
- const fk = parent.resolveForeignKey(this);
304
- const parentId = item[fk];
305
- if (parentId !== undefined && parentId !== null) {
306
- const singularParent = parent.table.endsWith("s") ? parent.table.slice(0, -1) : parent.table;
307
- item[singularParent] = await parent.find(parentId, {
381
+ }
382
+
383
+ if (options.belongsTo) {
384
+ const parents = Array.isArray(options.belongsTo) ? options.belongsTo : [options.belongsTo];
385
+
386
+ for (const parent of parents) {
387
+ const fk = parent.resolveForeignKey(this);
388
+ const parentIds = [...new Set(results.map((r) => r[fk]).filter((id) => id !== undefined && id !== null))];
389
+
390
+ const parentList = parentIds.length > 0
391
+ ? await parent.all({
392
+ where: { [parent.primaryKey]: parentIds },
308
393
  withDeleted: options.withDeleted,
309
394
  withHidden: options.withHidden,
310
- });
311
- }
395
+ })
396
+ : [];
397
+
398
+ const parentMap = new Map();
399
+ for (const p of parentList) {
400
+ parentMap.set(p[parent.primaryKey], p);
401
+ }
402
+
403
+ const singularParent = parent.table.endsWith("s") ? parent.table.slice(0, -1) : parent.table;
404
+ for (const item of results) {
405
+ item[singularParent] = parentMap.get(item[fk]) || null;
312
406
  }
313
407
  }
314
408
  }
@@ -349,21 +443,36 @@ class Model {
349
443
  /**
350
444
  * Inserts a new record, ignoring undeclared fields to prevent mass-assignment.
351
445
  * @param {Object} data
446
+ * @param {Object} [options={}]
447
+ * @param {string[]} [options.only] - Explicit whitelist of columns allowed for this operation.
448
+ * @param {string[]} [options.except] - Explicit blacklist of columns excluded from this operation.
352
449
  * @returns {Promise<number|string>} Inserted record identifier.
353
450
  */
354
- static async create(data = {}) {
451
+ static async create(data = {}, options = {}) {
355
452
  const payload = {};
356
453
  const cols = [];
357
454
  const placeholders = [];
358
455
  const params = [];
456
+ const safeData = data && typeof data === "object" ? data : {};
457
+ const onlySet = Array.isArray(options.only) ? new Set(options.only) : null;
458
+ const exceptSet = Array.isArray(options.except) ? new Set(options.except) : null;
459
+ const fillableSet = Array.isArray(this.fillable) && this.fillable.length > 0 ? new Set(this.fillable) : null;
460
+ const guardedSet = Array.isArray(this.guarded) && this.guarded.length > 0 ? new Set(this.guarded) : null;
359
461
 
360
462
  const now = new Date().toISOString();
361
463
 
362
464
  for (const [col, def] of Object.entries(this.schema)) {
363
465
  if (col === this.primaryKey && def.auto) continue;
364
466
 
365
- if (col in data) {
366
- let val = data[col];
467
+ const isAllowedByFilter =
468
+ (!onlySet || onlySet.has(col)) &&
469
+ (!exceptSet || !exceptSet.has(col)) &&
470
+ (!fillableSet || fillableSet.has(col)) &&
471
+ (!guardedSet || !guardedSet.has(col)) &&
472
+ !def.guarded;
473
+
474
+ if (isAllowedByFilter && Object.prototype.hasOwnProperty.call(safeData, col)) {
475
+ let val = safeData[col];
367
476
  if (def.hash && typeof val === "string" && val.length > 0) {
368
477
  const isAlreadyHashed = val.startsWith("$scrypt$") || /^\$2[aby]\$\d{2}\$/.test(val);
369
478
  if (!isAlreadyHashed) {
@@ -404,20 +513,36 @@ class Model {
404
513
  * Updates an existing record by identifier or conditions.
405
514
  * @param {number|string|Object} idOrConditions
406
515
  * @param {Object} data
516
+ * @param {Object} [options={}]
517
+ * @param {string[]} [options.only] - Explicit whitelist of columns allowed for this update.
518
+ * @param {string[]} [options.except] - Explicit blacklist of columns excluded from this update.
407
519
  * @returns {Promise<number>} Affected rows count.
408
520
  */
409
- static async update(idOrConditions, data = {}) {
521
+ static async update(idOrConditions, data = {}, options = {}) {
410
522
  const where = typeof idOrConditions === "object" && idOrConditions !== null
411
523
  ? { ...idOrConditions }
412
524
  : { [this.primaryKey]: idOrConditions };
413
525
 
414
526
  const sets = [];
415
527
  const params = [];
528
+ const safeData = data && typeof data === "object" ? data : {};
529
+ const onlySet = Array.isArray(options.only) ? new Set(options.only) : null;
530
+ const exceptSet = Array.isArray(options.except) ? new Set(options.except) : null;
531
+ const fillableSet = Array.isArray(this.fillable) && this.fillable.length > 0 ? new Set(this.fillable) : null;
532
+ const guardedSet = Array.isArray(this.guarded) && this.guarded.length > 0 ? new Set(this.guarded) : null;
416
533
 
417
534
  for (const [col, def] of Object.entries(this.schema)) {
418
535
  if (col === this.primaryKey) continue;
419
- if (col in data) {
420
- let val = data[col];
536
+
537
+ const isAllowedByFilter =
538
+ (!onlySet || onlySet.has(col)) &&
539
+ (!exceptSet || !exceptSet.has(col)) &&
540
+ (!fillableSet || fillableSet.has(col)) &&
541
+ (!guardedSet || !guardedSet.has(col)) &&
542
+ !def.guarded;
543
+
544
+ if (isAllowedByFilter && Object.prototype.hasOwnProperty.call(safeData, col)) {
545
+ let val = safeData[col];
421
546
  if (def.hash && typeof val === "string" && val.length > 0) {
422
547
  const isAlreadyHashed = val.startsWith("$scrypt$") || /^\$2[aby]\$\d{2}\$/.test(val);
423
548
  if (!isAlreadyHashed) {
@@ -532,6 +657,117 @@ class Model {
532
657
  return new Validator(rules, lang);
533
658
  }
534
659
 
660
+ /**
661
+ * Retrieves the first record matching the given criteria.
662
+ * Semantic alias for Model.find(where, options).
663
+ * @param {Object|number|string} [where={}]
664
+ * @param {Object} [options={}]
665
+ * @returns {Promise<Object|null>}
666
+ */
667
+ static async first(where = {}, options = {}) {
668
+ return this.find(where, options);
669
+ }
670
+
671
+ /**
672
+ * Returns the count of records matching the given criteria.
673
+ * @param {Object} [where={}]
674
+ * @returns {Promise<number>}
675
+ */
676
+ static async count(where = {}) {
677
+ const conds = { ...where };
678
+ if (this.softDelete && !("deleted_at" in conds)) {
679
+ conds.deleted_at = null;
680
+ }
681
+ const { params, whereSql } = buildWhere(conds);
682
+ const sql = `SELECT COUNT(*) as total FROM ${this.table} ${whereSql}`.trim();
683
+ const row = await this.getDatabase().query(sql, params, { return_row: true });
684
+ return Number(row?.total || row?.count || 0);
685
+ }
686
+
687
+ /**
688
+ * Checks whether at least one record exists matching the given criteria.
689
+ * @param {Object} [where={}]
690
+ * @returns {Promise<boolean>}
691
+ */
692
+ static async exists(where = {}) {
693
+ const total = await this.count(where);
694
+ return total > 0;
695
+ }
696
+
697
+ /**
698
+ * Finds the first record matching criteria or creates it if not found.
699
+ * @param {Object} where - Search conditions.
700
+ * @param {Object} [defaults={}] - Additional default values for creation.
701
+ * @returns {Promise<Object>}
702
+ */
703
+ static async firstOrCreate(where, defaults = {}) {
704
+ const existing = await this.find(where);
705
+ if (existing) return existing;
706
+ const newId = await this.create({ ...where, ...defaults });
707
+ return this.find(newId);
708
+ }
709
+
710
+ /**
711
+ * Updates an existing record matching criteria or creates it if not found.
712
+ * @param {Object} where - Search conditions.
713
+ * @param {Object} [values={}] - Attributes to update or create.
714
+ * @returns {Promise<Object>}
715
+ */
716
+ static async updateOrCreate(where, values = {}) {
717
+ const existing = await this.find(where);
718
+ if (existing) {
719
+ const pk = existing[this.primaryKey];
720
+ await this.update(pk, values);
721
+ return this.find(pk);
722
+ }
723
+ const newId = await this.create({ ...where, ...values });
724
+ return this.find(newId);
725
+ }
726
+
727
+ /**
728
+ * Converts a schema column definition to its SQL column specification string.
729
+ * @param {string} col - Column name.
730
+ * @param {Object} def - Column definition.
731
+ * @param {"sqlite"|"mysql"|"postgres"} [dialect="sqlite"]
732
+ * @returns {string}
733
+ */
734
+ static columnToSQL(col, def, dialect = "sqlite") {
735
+ const type = (def.type || "string").toLowerCase();
736
+
737
+ if (def.primary) {
738
+ if (dialect === "postgres") {
739
+ return `${col} SERIAL PRIMARY KEY`;
740
+ }
741
+ if (dialect === "mysql") {
742
+ return `${col} INT AUTO_INCREMENT PRIMARY KEY`;
743
+ }
744
+ return `${col} INTEGER PRIMARY KEY AUTOINCREMENT`;
745
+ }
746
+
747
+ let typeStr = "VARCHAR(255)";
748
+ if (type === "int" || type === "integer") typeStr = dialect === "postgres" ? "INTEGER" : "INT";
749
+ if (type === "bigint") typeStr = "BIGINT";
750
+ if (type === "float" || type === "double" || type === "decimal") typeStr = "DECIMAL(10,2)";
751
+ if (type === "text") typeStr = "TEXT";
752
+ if (type === "boolean" || type === "bool") typeStr = dialect === "sqlite" ? "INTEGER" : "BOOLEAN";
753
+ if (type === "date" || type === "datetime" || type === "timestamp") {
754
+ typeStr = dialect === "mysql" ? "DATETIME" : "TIMESTAMP";
755
+ }
756
+ if (type === "json") typeStr = dialect === "postgres" ? "JSONB" : (dialect === "sqlite" ? "TEXT" : "JSON");
757
+ if (type === "string") {
758
+ typeStr = `VARCHAR(${def.length || 255})`;
759
+ }
760
+
761
+ let sqlCol = `${col} ${typeStr}`;
762
+ if (def.required && !def.nullable) sqlCol += " NOT NULL";
763
+ if (def.unique) sqlCol += " UNIQUE";
764
+ if (def.default !== undefined) {
765
+ const defVal = typeof def.default === "string" ? `'${def.default}'` : def.default;
766
+ sqlCol += ` DEFAULT ${defVal}`;
767
+ }
768
+ return sqlCol;
769
+ }
770
+
535
771
  /**
536
772
  * Generates a SQL CREATE TABLE DDL string tailored to the target dialect.
537
773
  * @param {"sqlite"|"mysql"|"postgres"} [dialect="sqlite"]
@@ -539,44 +775,28 @@ class Model {
539
775
  */
540
776
  static toDDL(dialect = "sqlite") {
541
777
  const columns = [];
778
+ const foreignKeys = [];
542
779
 
543
780
  for (const [col, def] of Object.entries(this.schema)) {
544
- const type = (def.type || "string").toLowerCase();
545
- let sqlCol = "";
546
-
547
- if (def.primary) {
548
- if (dialect === "postgres") {
549
- sqlCol = `${col} SERIAL PRIMARY KEY`;
550
- } else if (dialect === "mysql") {
551
- sqlCol = `${col} INT AUTO_INCREMENT PRIMARY KEY`;
552
- } else {
553
- sqlCol = `${col} INTEGER PRIMARY KEY AUTOINCREMENT`;
554
- }
555
- } else {
556
- let typeStr = "VARCHAR(255)";
557
- if (type === "int" || type === "integer") typeStr = dialect === "postgres" ? "INTEGER" : "INT";
558
- if (type === "bigint") typeStr = "BIGINT";
559
- if (type === "float" || type === "double" || type === "decimal") typeStr = "DECIMAL(10,2)";
560
- if (type === "text") typeStr = "TEXT";
561
- if (type === "boolean" || type === "bool") typeStr = dialect === "sqlite" ? "INTEGER" : "BOOLEAN";
562
- if (type === "date" || type === "datetime" || type === "timestamp") {
563
- typeStr = dialect === "mysql" ? "DATETIME" : "TIMESTAMP";
564
- }
565
- if (type === "json") typeStr = dialect === "postgres" ? "JSONB" : (dialect === "sqlite" ? "TEXT" : "JSON");
566
- if (type === "string") {
567
- typeStr = `VARCHAR(${def.length || 255})`;
781
+ columns.push(` ${this.columnToSQL(col, def, dialect)}`);
782
+
783
+ if (def.references) {
784
+ let refTable = "";
785
+ let refCol = "id";
786
+ if (typeof def.references === "string") {
787
+ const parts = def.references.split(".");
788
+ refTable = parts[0];
789
+ if (parts[1]) refCol = parts[1];
790
+ } else if (def.references && def.references.table) {
791
+ refTable = def.references.table;
792
+ if (def.references.column) refCol = def.references.column;
568
793
  }
569
794
 
570
- sqlCol = `${col} ${typeStr}`;
571
- if (def.required && !def.nullable) sqlCol += " NOT NULL";
572
- if (def.unique) sqlCol += " UNIQUE";
573
- if (def.default !== undefined) {
574
- const defVal = typeof def.default === "string" ? `'${def.default}'` : def.default;
575
- sqlCol += ` DEFAULT ${defVal}`;
795
+ if (refTable) {
796
+ const onAction = def.onDelete ? def.onDelete.toUpperCase() : (def.nullable ? "SET NULL" : "CASCADE");
797
+ foreignKeys.push(` FOREIGN KEY (${col}) REFERENCES ${refTable}(${refCol}) ON DELETE ${onAction}`);
576
798
  }
577
799
  }
578
-
579
- columns.push(` ${sqlCol}`);
580
800
  }
581
801
 
582
802
  if (this.timestamps) {
@@ -592,7 +812,8 @@ class Model {
592
812
  columns.push(dialect === "mysql" ? " deleted_at DATETIME NULL" : " deleted_at TIMESTAMP NULL");
593
813
  }
594
814
 
595
- return `CREATE TABLE IF NOT EXISTS ${this.table} (\n${columns.join(",\n")}\n);`;
815
+ const allLines = columns.concat(foreignKeys);
816
+ return `CREATE TABLE IF NOT EXISTS ${this.table} (\n${allLines.join(",\n")}\n);`;
596
817
  }
597
818
  }
598
819
 
package/core/queue.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import Config from "./config.js";
3
5
  import { getRedisClient } from "./cache.js";
4
6
 
5
7
  /**
@@ -143,9 +145,9 @@ class QueueManager {
143
145
  async loadJobs(jobsDir) {
144
146
  const targetDir =
145
147
  jobsDir ||
146
- (fs.existsSync(path.resolve(process.cwd(), "app/jobs"))
147
- ? path.resolve(process.cwd(), "app/jobs")
148
- : path.resolve(process.cwd(), "backend/jobs"));
148
+ (fs.existsSync(path.resolve(Config.appDir(), "app/jobs"))
149
+ ? path.resolve(Config.appDir(), "app/jobs")
150
+ : path.resolve(Config.appDir(), "backend/jobs"));
149
151
 
150
152
  if (!fs.existsSync(targetDir)) return;
151
153
 
@@ -156,7 +158,8 @@ class QueueManager {
156
158
  for (const file of files) {
157
159
  const fullPath = path.join(targetDir, file);
158
160
  try {
159
- const module = await import(`file://${fullPath}`);
161
+ const fileUrl = pathToFileURL(fullPath).href;
162
+ const module = await import(fileUrl);
160
163
  if (typeof module.default === "function") {
161
164
  const jobName = path.basename(file, path.extname(file));
162
165
  this.process(jobName, module.default);