@ztimson/utils 0.25.7 → 0.25.9

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.
@@ -1,27 +1,38 @@
1
1
  export type TableOptions = {
2
2
  name: string;
3
3
  key?: string;
4
+ autoIncrement?: boolean;
4
5
  };
5
6
  export declare class Database {
6
7
  readonly database: string;
7
8
  version?: number | undefined;
8
9
  connection: Promise<IDBDatabase>;
10
+ ready: boolean;
9
11
  tables: TableOptions[];
10
- constructor(database: string, tables: (string | TableOptions)[], version?: number | undefined);
12
+ constructor(database: string, tables?: (string | TableOptions)[], version?: number | undefined);
13
+ createTable<K extends IDBValidKey = any, T = any>(table: string | TableOptions): Promise<Table<K, T>>;
14
+ deleteTable(table: string | TableOptions): Promise<void>;
11
15
  includes(name: any): boolean;
12
16
  table<K extends IDBValidKey = any, T = any>(name: any): Table<K, T>;
13
17
  }
14
18
  export declare class Table<K extends IDBValidKey = any, T = any> {
15
19
  private readonly database;
16
20
  readonly name: string;
17
- constructor(database: Database, name: string);
21
+ readonly key: keyof T | string;
22
+ constructor(database: Database, name: string, key?: keyof T | string);
18
23
  tx<R>(table: string, fn: (store: IDBObjectStore) => IDBRequest, readonly?: boolean): Promise<R>;
19
24
  add(value: T, key?: K): Promise<void>;
25
+ all: () => Promise<T[]>;
26
+ clear(): Promise<void>;
20
27
  count(): Promise<number>;
21
- put(key: K, value: T): Promise<void>;
28
+ create: (value: T, key?: K) => Promise<void>;
29
+ delete(key: K): Promise<void>;
30
+ get(key: K): Promise<T>;
22
31
  getAll(): Promise<T[]>;
23
32
  getAllKeys(): Promise<K[]>;
24
- get(key: K): Promise<T>;
25
- delete(key: K): Promise<void>;
26
- clear(): Promise<void>;
33
+ put(key: K, value: T): Promise<void>;
34
+ read(): Promise<T[]>;
35
+ read(key: K): Promise<T>;
36
+ set(value: T, key?: K): Promise<void>;
37
+ update: (value: T, key?: K) => Promise<void>;
27
38
  }
package/dist/index.cjs CHANGED
@@ -399,46 +399,88 @@ ${opts.message || this.desc}`;
399
399
  class Database {
400
400
  constructor(database, tables, version) {
401
401
  __publicField(this, "connection");
402
+ __publicField(this, "ready", false);
402
403
  __publicField(this, "tables");
403
404
  this.database = database;
404
405
  this.version = version;
405
406
  this.connection = new Promise((resolve, reject) => {
406
407
  const req = indexedDB.open(this.database, this.version);
407
- this.tables = tables.map((t) => {
408
+ this.tables = !tables ? [] : tables.map((t) => {
408
409
  t = typeof t == "object" ? t : { name: t };
409
410
  return { ...t, name: t.name.toString() };
410
411
  });
411
- const tableNames = new ASet(this.tables.map((t) => t.name));
412
412
  req.onerror = () => reject(req.error);
413
413
  req.onsuccess = () => {
414
414
  const db = req.result;
415
- if (tableNames.symmetricDifference(new ASet(Array.from(db.objectStoreNames))).length) {
415
+ const existing = Array.from(db.objectStoreNames);
416
+ if (!tables) this.tables = existing.map((t) => {
417
+ const tx = db.transaction(t, "readonly");
418
+ const store = tx.objectStore(t);
419
+ return { name: t, key: store.keyPath };
420
+ });
421
+ const desired = new ASet((tables || []).map((t) => typeof t == "string" ? t : t.name));
422
+ if (tables && desired.symmetricDifference(new ASet(existing)).length) {
416
423
  db.close();
417
424
  Object.assign(this, new Database(this.database, this.tables, db.version + 1));
425
+ this.connection.then(resolve);
418
426
  } else {
419
427
  this.version = db.version;
420
428
  resolve(db);
421
429
  }
430
+ this.ready = true;
422
431
  };
423
432
  req.onupgradeneeded = () => {
424
433
  const db = req.result;
425
434
  const existingTables = new ASet(Array.from(db.objectStoreNames));
426
- existingTables.difference(tableNames).forEach((name) => db.deleteObjectStore(name));
427
- tableNames.difference(existingTables).forEach((name) => db.createObjectStore(name));
435
+ if (tables) {
436
+ const desired = new ASet((tables || []).map((t) => typeof t == "string" ? t : t.name));
437
+ existingTables.difference(desired).forEach((name) => db.deleteObjectStore(name));
438
+ desired.difference(existingTables).forEach((name) => {
439
+ const t = this.tables.find(findByProp("name", name));
440
+ db.createObjectStore(name, {
441
+ keyPath: t == null ? void 0 : t.key,
442
+ autoIncrement: (t == null ? void 0 : t.autoIncrement) || !(t == null ? void 0 : t.key)
443
+ });
444
+ });
445
+ }
428
446
  };
429
447
  });
430
448
  }
449
+ async createTable(table) {
450
+ if (typeof table == "string") table = { name: table };
451
+ const conn = await this.connection;
452
+ if (!this.includes(table.name)) {
453
+ conn.close();
454
+ Object.assign(this, new Database(this.database, [...this.tables, table], (this.version ?? 0) + 1));
455
+ }
456
+ return this.table(table.name);
457
+ }
458
+ async deleteTable(table) {
459
+ if (typeof table == "string") table = { name: table };
460
+ if (!this.includes(table.name)) return;
461
+ const conn = await this.connection;
462
+ conn.close();
463
+ Object.assign(this, new Database(this.database, this.tables.filter((t) => t.name != table.name), (this.version ?? 0) + 1));
464
+ }
431
465
  includes(name) {
432
- return !!this.tables.find((t) => t.name == name.toString());
466
+ return !!this.tables.find((t) => t.name == (typeof name == "object" ? name.name : name.toString()));
433
467
  }
434
468
  table(name) {
435
469
  return new Table(this, name.toString());
436
470
  }
437
471
  }
438
472
  class Table {
439
- constructor(database, name) {
473
+ constructor(database, name, key = "id") {
474
+ __publicField(this, "all", this.getAll);
475
+ __publicField(this, "create", this.add);
476
+ __publicField(this, "update", this.set);
440
477
  this.database = database;
441
478
  this.name = name;
479
+ this.key = key;
480
+ this.database.connection.then(() => {
481
+ const exists = !!this.database.tables.find(findByProp("name", this.name));
482
+ if (!exists) this.database.createTable(this.name);
483
+ });
442
484
  }
443
485
  async tx(table, fn2, readonly = false) {
444
486
  const db = await this.database.connection;
@@ -453,11 +495,17 @@ ${opts.message || this.desc}`;
453
495
  add(value, key) {
454
496
  return this.tx(this.name, (store) => store.add(value, key));
455
497
  }
498
+ clear() {
499
+ return this.tx(this.name, (store) => store.clear());
500
+ }
456
501
  count() {
457
502
  return this.tx(this.name, (store) => store.count(), true);
458
503
  }
459
- put(key, value) {
460
- return this.tx(this.name, (store) => store.put(value, key));
504
+ delete(key) {
505
+ return this.tx(this.name, (store) => store.delete(key));
506
+ }
507
+ get(key) {
508
+ return this.tx(this.name, (store) => store.get(key), true);
461
509
  }
462
510
  getAll() {
463
511
  return this.tx(this.name, (store) => store.getAll(), true);
@@ -465,14 +513,15 @@ ${opts.message || this.desc}`;
465
513
  getAllKeys() {
466
514
  return this.tx(this.name, (store) => store.getAllKeys(), true);
467
515
  }
468
- get(key) {
469
- return this.tx(this.name, (store) => store.get(key), true);
516
+ put(key, value) {
517
+ return this.tx(this.name, (store) => store.put(value, key));
470
518
  }
471
- delete(key) {
472
- return this.tx(this.name, (store) => store.delete(key));
519
+ read(key) {
520
+ return key ? this.get(key) : this.getAll();
473
521
  }
474
- clear() {
475
- return this.tx(this.name, (store) => store.clear());
522
+ set(value, key) {
523
+ if (!key && !value[this.key]) return this.add(value);
524
+ return this.put(key || value[this.key], value);
476
525
  }
477
526
  }
478
527
  class Cache {
@@ -661,8 +710,9 @@ ${opts.message || this.desc}`;
661
710
  const SYMBOL_LIST = "~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
662
711
  const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST;
663
712
  function camelCase(str) {
664
- const text = pascalCase(str);
665
- return !text ? "" : text[0].toLowerCase() + text.slice(1);
713
+ if (!str) return "";
714
+ const pascal = pascalCase(str);
715
+ return pascal.charAt(0).toLowerCase() + pascal.slice(1);
666
716
  }
667
717
  function formatBytes(bytes, decimals = 2) {
668
718
  if (bytes === 0) return "0 Bytes";
@@ -681,16 +731,15 @@ ${opts.message || this.desc}`;
681
731
  }
682
732
  function kebabCase(str) {
683
733
  if (!str) return "";
684
- return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, "").replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `-${args[0].toLowerCase()}`).replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}-${args[2]}`).replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `-${args[1] ?? ""}`).toLowerCase();
734
+ return wordSegments(str).map((w) => w.toLowerCase()).join("-");
685
735
  }
686
736
  function pad(text, length, char = " ", start = true) {
687
737
  if (start) return text.toString().padStart(length, char);
688
738
  return text.toString().padEnd(length, char);
689
739
  }
690
740
  function pascalCase(str) {
691
- var _a;
692
741
  if (!str) return "";
693
- return ((_a = str.match(/[a-zA-Z0-9]+/g)) == null ? void 0 : _a.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("")) ?? "";
742
+ return wordSegments(str).map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join("");
694
743
  }
695
744
  function randomHex(length) {
696
745
  return Array(length).fill(null).map(() => Math.round(Math.random() * 15).toString(16)).join("");
@@ -720,7 +769,7 @@ ${opts.message || this.desc}`;
720
769
  }
721
770
  function snakeCase(str) {
722
771
  if (!str) return "";
723
- return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, "").replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `_${args[0].toLowerCase()}`).replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}_${args[2]}`).replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `_${args[1] ?? ""}`).toLowerCase();
772
+ return wordSegments(str).map((w) => w.toLowerCase()).join("_");
724
773
  }
725
774
  function strSplice(str, start, deleteCount, insert = "") {
726
775
  const before = str.slice(0, start);
@@ -810,6 +859,10 @@ ${opts.message || this.desc}`;
810
859
  function bit_rol(d, _) {
811
860
  return d << _ | d >>> 32 - _;
812
861
  }
862
+ function wordSegments(str) {
863
+ if (!str) return [];
864
+ return str.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/([0-9]+)([a-zA-Z])/g, "$1 $2").replace(/([a-zA-Z])([0-9]+)/g, "$1 $2").replace(/[_\-\s]+/g, " ").trim().split(/\s+/).filter(Boolean);
865
+ }
813
866
  function validateEmail(email) {
814
867
  return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email);
815
868
  }
@@ -2121,6 +2174,7 @@ ${opts.message || this.desc}`;
2121
2174
  exports2.toCsv = toCsv;
2122
2175
  exports2.uploadWithProgress = uploadWithProgress;
2123
2176
  exports2.validateEmail = validateEmail;
2177
+ exports2.wordSegments = wordSegments;
2124
2178
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
2125
2179
  });
2126
2180
  //# sourceMappingURL=index.cjs.map