@choksheak/ts-utils 0.1.5 → 0.1.6
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/dateTimeStr.d.ts +14 -0
- package/dateTimeStr.js +71 -0
- package/dateTimeStr.js.map +1 -0
- package/isEmpty.d.ts +4 -0
- package/isEmpty.js +48 -0
- package/isEmpty.js.map +1 -0
- package/kvStore.d.ts +63 -0
- package/kvStore.js +315 -0
- package/kvStore.js.map +1 -0
- package/localStorageCache.d.ts +9 -0
- package/localStorageCache.js +26 -8
- package/localStorageCache.js.map +1 -1
- package/nonEmpty.d.ts +5 -0
- package/nonEmpty.js +58 -0
- package/nonEmpty.js.map +1 -0
- package/nonNil.js +2 -2
- package/nonNil.js.map +1 -1
- package/package.json +6 -5
- package/src/dateTimeStr.ts +83 -0
- package/src/isEmpty.ts +32 -0
- package/src/kvStore.ts +382 -0
- package/src/localStorageCache.ts +31 -7
- package/src/nonEmpty.ts +15 -0
- package/src/nonNil.ts +2 -2
package/nonEmpty.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/nonEmpty.ts
|
|
21
|
+
var nonEmpty_exports = {};
|
|
22
|
+
__export(nonEmpty_exports, {
|
|
23
|
+
nonEmpty: () => nonEmpty
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(nonEmpty_exports);
|
|
26
|
+
|
|
27
|
+
// src/isEmpty.ts
|
|
28
|
+
function isEmpty(t) {
|
|
29
|
+
if (!t) {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
if (typeof t !== "object") {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
if ("length" in t) {
|
|
36
|
+
return t.length === 0;
|
|
37
|
+
}
|
|
38
|
+
if ("size" in t) {
|
|
39
|
+
return t.size === 0;
|
|
40
|
+
}
|
|
41
|
+
for (const k in t) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/nonEmpty.ts
|
|
48
|
+
function nonEmpty(t, varName = "value") {
|
|
49
|
+
if (isEmpty(t)) {
|
|
50
|
+
throw new Error(`Empty ${varName}: ${t}`);
|
|
51
|
+
}
|
|
52
|
+
return t;
|
|
53
|
+
}
|
|
54
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
55
|
+
0 && (module.exports = {
|
|
56
|
+
nonEmpty
|
|
57
|
+
});
|
|
58
|
+
//# sourceMappingURL=nonEmpty.js.map
|
package/nonEmpty.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/nonEmpty.ts","../src/isEmpty.ts"],"sourcesContent":["import { isEmpty } from \"./isEmpty\";\n\n/**\n * Type asserts that `t` is truthy.\n * Throws an error if `t` is null or undefined.\n */\nexport function nonEmpty<T>(\n t: T | null | undefined | \"\" | 0 | -0 | 0n | false | typeof NaN,\n varName = \"value\",\n): T {\n if (isEmpty(t)) {\n throw new Error(`Empty ${varName}: ${t}`);\n }\n return t as T;\n}\n","/**\n * Returns true if `t` is empty.\n */\nexport function isEmpty(t: unknown): boolean {\n // Anything falsy is considered empty.\n if (!t) {\n return true;\n }\n\n // Arrays are also of type `object`.\n if (typeof t !== \"object\") {\n return false;\n }\n\n // `length` includes arrays as well.\n if (\"length\" in t) {\n return t.length === 0;\n }\n\n // `size` is for Set, Map, Blob etc.\n if (\"size\" in t) {\n return t.size === 0;\n }\n\n // Super fast check for object emptiness.\n // https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object\n for (const k in t) {\n return false;\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,SAAS,QAAQ,GAAqB;AAE3C,MAAI,CAAC,GAAG;AACN,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,MAAM,UAAU;AACzB,WAAO;AAAA,EACT;AAGA,MAAI,YAAY,GAAG;AACjB,WAAO,EAAE,WAAW;AAAA,EACtB;AAGA,MAAI,UAAU,GAAG;AACf,WAAO,EAAE,SAAS;AAAA,EACpB;AAIA,aAAW,KAAK,GAAG;AACjB,WAAO;AAAA,EACT;AAEA,SAAO;AACT;;;ADzBO,SAAS,SACd,GACA,UAAU,SACP;AACH,MAAI,QAAQ,CAAC,GAAG;AACd,UAAM,IAAI,MAAM,SAAS,OAAO,KAAK,CAAC,EAAE;AAAA,EAC1C;AACA,SAAO;AACT;","names":[]}
|
package/nonNil.js
CHANGED
|
@@ -23,9 +23,9 @@ __export(nonNil_exports, {
|
|
|
23
23
|
nonNil: () => nonNil
|
|
24
24
|
});
|
|
25
25
|
module.exports = __toCommonJS(nonNil_exports);
|
|
26
|
-
function nonNil(t, varName = "
|
|
26
|
+
function nonNil(t, varName = "value") {
|
|
27
27
|
if (t === null || t === void 0) {
|
|
28
|
-
throw new Error(`Missing ${varName}`);
|
|
28
|
+
throw new Error(`Missing ${varName}: ${t}`);
|
|
29
29
|
}
|
|
30
30
|
return t;
|
|
31
31
|
}
|
package/nonNil.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nonNil.ts"],"sourcesContent":["/**\n * Type asserts that `t` is neither null nor undefined.\n * Throws an error if `t` is null or undefined.\n */\nexport function nonNil<T>(t: T | null | undefined, varName = \"
|
|
1
|
+
{"version":3,"sources":["../src/nonNil.ts"],"sourcesContent":["/**\n * Type asserts that `t` is neither null nor undefined.\n * Throws an error if `t` is null or undefined.\n */\nexport function nonNil<T>(t: T | null | undefined, varName = \"value\"): T {\n if (t === null || t === undefined) {\n throw new Error(`Missing ${varName}: ${t}`);\n }\n return t;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,SAAS,OAAU,GAAyB,UAAU,SAAY;AACvE,MAAI,MAAM,QAAQ,MAAM,QAAW;AACjC,UAAM,IAAI,MAAM,WAAW,OAAO,KAAK,CAAC,EAAE;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@choksheak/ts-utils",
|
|
3
3
|
"license": "The Unlicense",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.6",
|
|
5
5
|
"description": "Random Typescript utilities with support for full tree-shaking",
|
|
6
6
|
"private": false,
|
|
7
7
|
"scripts": {
|
|
8
8
|
"lint": "eslint src/**",
|
|
9
|
-
"format": "prettier --write \"**/*.{
|
|
10
|
-
"test": "jest",
|
|
11
|
-
"test:watch": "jest --watch",
|
|
9
|
+
"format": "prettier --write \"**/*.{ts}\"",
|
|
10
|
+
"test": "npm run clean && jest",
|
|
11
|
+
"test:watch": "npm run clean && jest --watch",
|
|
12
12
|
"clean": "rm -rf dist",
|
|
13
|
-
"ci": "npm run
|
|
13
|
+
"ci": "npm run lint && npm run format && npm run test",
|
|
14
14
|
"build": "tsup src/*",
|
|
15
15
|
"gen-types": "tsc --emitDeclarationOnly --declaration",
|
|
16
16
|
"pub": "scripts/publish.sh"
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"@types/jest": "^27.5.2",
|
|
22
22
|
"@types/node": "^16.18.97",
|
|
23
23
|
"eslint": "^9.14.0",
|
|
24
|
+
"fake-indexeddb": "^6.0.0",
|
|
24
25
|
"globals": "^15.12.0",
|
|
25
26
|
"jest": "^29.7.0",
|
|
26
27
|
"jest-environment-jsdom": "^29.7.0",
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export class DateTimeStr {
|
|
2
|
+
public static yyyyMmDd(dt = new Date(), separator = "-"): string {
|
|
3
|
+
const yr = dt.getFullYear();
|
|
4
|
+
const mth = dt.getMonth() + 1;
|
|
5
|
+
const day = dt.getDate();
|
|
6
|
+
|
|
7
|
+
return (
|
|
8
|
+
yr +
|
|
9
|
+
separator +
|
|
10
|
+
(mth < 10 ? "0" + mth : mth) +
|
|
11
|
+
separator +
|
|
12
|
+
(day < 10 ? "0" + day : day)
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
public static hhMmSs(dt = new Date(), separator = ":"): string {
|
|
17
|
+
const hr = dt.getHours();
|
|
18
|
+
const min = dt.getMinutes();
|
|
19
|
+
const sec = dt.getSeconds();
|
|
20
|
+
|
|
21
|
+
return (
|
|
22
|
+
(hr < 10 ? "0" + hr : hr) +
|
|
23
|
+
separator +
|
|
24
|
+
(min < 10 ? "0" + min : min) +
|
|
25
|
+
separator +
|
|
26
|
+
(sec < 10 ? "0" + sec : sec)
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public static hhMmSsMs(
|
|
31
|
+
dt = new Date(),
|
|
32
|
+
timeSeparator = ":",
|
|
33
|
+
msSeparator = ".",
|
|
34
|
+
): string {
|
|
35
|
+
const ms = dt.getMilliseconds();
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
DateTimeStr.hhMmSs(dt, timeSeparator) +
|
|
39
|
+
msSeparator +
|
|
40
|
+
(ms < 10 ? "00" + ms : ms < 100 ? "0" + ms : ms)
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
public static tz(dt = new Date()): string {
|
|
45
|
+
if (dt.getTimezoneOffset() === 0) {
|
|
46
|
+
return "Z";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const tzHours = dt.getTimezoneOffset() / 60;
|
|
50
|
+
return tzHours >= 0 ? "+" + tzHours : String(tzHours);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Full local date/time string. */
|
|
54
|
+
public static local(
|
|
55
|
+
dt = new Date(),
|
|
56
|
+
dateSeparator = "-",
|
|
57
|
+
dtSeparator = " ",
|
|
58
|
+
timeSeparator = ":",
|
|
59
|
+
msSeparator = ".",
|
|
60
|
+
): string {
|
|
61
|
+
return (
|
|
62
|
+
DateTimeStr.yyyyMmDd(dt, dateSeparator) +
|
|
63
|
+
dtSeparator +
|
|
64
|
+
DateTimeStr.hhMmSsMs(dt, timeSeparator, msSeparator) +
|
|
65
|
+
DateTimeStr.tz(dt)
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Use the default ISO string function to keep things simple here. */
|
|
70
|
+
public static utc(dt = new Date()) {
|
|
71
|
+
return dt.toISOString();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Default full local date+time string with full & concise info. */
|
|
75
|
+
public static get now() {
|
|
76
|
+
return DateTimeStr.local();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Default full UTC date+time string with full & concise info. */
|
|
80
|
+
public static get utcNow() {
|
|
81
|
+
return DateTimeStr.utc();
|
|
82
|
+
}
|
|
83
|
+
}
|
package/src/isEmpty.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns true if `t` is empty.
|
|
3
|
+
*/
|
|
4
|
+
export function isEmpty(t: unknown): boolean {
|
|
5
|
+
// Anything falsy is considered empty.
|
|
6
|
+
if (!t) {
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Arrays are also of type `object`.
|
|
11
|
+
if (typeof t !== "object") {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// `length` includes arrays as well.
|
|
16
|
+
if ("length" in t) {
|
|
17
|
+
return t.length === 0;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// `size` is for Set, Map, Blob etc.
|
|
21
|
+
if ("size" in t) {
|
|
22
|
+
return t.size === 0;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Super fast check for object emptiness.
|
|
26
|
+
// https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
|
|
27
|
+
for (const k in t) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return true;
|
|
32
|
+
}
|
package/src/kvStore.ts
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Indexed DB key-value store with support for auto-expirations.
|
|
3
|
+
*
|
|
4
|
+
* Why use this?
|
|
5
|
+
* 1. No need to worry about running out of storage.
|
|
6
|
+
* 2. Extremely simple interface to use indexed DBs.
|
|
7
|
+
* 3. Auto-expirations frees you from worrying about data clean-up.
|
|
8
|
+
* 4. Any serializable data type can be stored (except undefined).
|
|
9
|
+
*
|
|
10
|
+
* How to use?
|
|
11
|
+
* Just use the `kvStore` global constant like the local storage.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
// Updating the DB name will cause all old entries to be gone.
|
|
15
|
+
const DEFAULT_DB_NAME = "KVStore";
|
|
16
|
+
|
|
17
|
+
// Updating the version will cause all old entries to be gone.
|
|
18
|
+
const DEFAULT_DB_VERSION = 1;
|
|
19
|
+
|
|
20
|
+
// Use a constant store name to keep things simple.
|
|
21
|
+
const STORE_NAME = "kvStore";
|
|
22
|
+
|
|
23
|
+
/** One day in milliseconds. */
|
|
24
|
+
export const MILLIS_PER_DAY = 86_400_000;
|
|
25
|
+
|
|
26
|
+
/** 30 days in ms. */
|
|
27
|
+
export const DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;
|
|
28
|
+
|
|
29
|
+
/** Do GC once per day. */
|
|
30
|
+
export const GC_INTERVAL_MS = MILLIS_PER_DAY;
|
|
31
|
+
|
|
32
|
+
type StoredObject<T> = {
|
|
33
|
+
key: string;
|
|
34
|
+
value: T;
|
|
35
|
+
expireMs: number;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Parse a stored value string. Returns undefined if invalid or expired.
|
|
40
|
+
* Throws an error if the string cannot be parsed as JSON.
|
|
41
|
+
*/
|
|
42
|
+
function validateStoredObject<T>(
|
|
43
|
+
obj: StoredObject<T>,
|
|
44
|
+
): StoredObject<T> | undefined {
|
|
45
|
+
if (
|
|
46
|
+
!obj ||
|
|
47
|
+
typeof obj !== "object" ||
|
|
48
|
+
!("key" in obj) ||
|
|
49
|
+
typeof obj.key !== "string" ||
|
|
50
|
+
!("value" in obj) ||
|
|
51
|
+
obj.value === undefined ||
|
|
52
|
+
!("expireMs" in obj) ||
|
|
53
|
+
typeof obj.expireMs !== "number" ||
|
|
54
|
+
Date.now() >= obj.expireMs
|
|
55
|
+
) {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return obj;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Add an `onerror` handler to the request. */
|
|
63
|
+
function withOnError<T extends IDBRequest | IDBTransaction>(
|
|
64
|
+
request: T,
|
|
65
|
+
reject: (reason?: unknown) => void,
|
|
66
|
+
): T {
|
|
67
|
+
request.onerror = (event) => {
|
|
68
|
+
reject(event);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
return request;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export class KVStoreField<T> {
|
|
75
|
+
public constructor(
|
|
76
|
+
public readonly store: KVStore,
|
|
77
|
+
public readonly key: string,
|
|
78
|
+
) {}
|
|
79
|
+
|
|
80
|
+
public get(): Promise<T | undefined> {
|
|
81
|
+
return this.store.get(this.key);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
public set(t: T): Promise<T> {
|
|
85
|
+
return this.store.set(this.key, t);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
public delete(): Promise<void> {
|
|
89
|
+
return this.store.delete(this.key);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* You can create multiple KVStores if you want, but most likely you will only
|
|
95
|
+
* need to use the default `kvStore` instance.
|
|
96
|
+
*/
|
|
97
|
+
export class KVStore {
|
|
98
|
+
// We'll init the DB only on first use.
|
|
99
|
+
private db: IDBDatabase | undefined;
|
|
100
|
+
|
|
101
|
+
// Local storage key name for the last GC completed timestamp.
|
|
102
|
+
public readonly gcMsStorageKey: string;
|
|
103
|
+
|
|
104
|
+
public constructor(
|
|
105
|
+
public readonly dbName: string,
|
|
106
|
+
public readonly dbVersion: number,
|
|
107
|
+
public readonly defaultExpiryDeltaMs: number,
|
|
108
|
+
) {
|
|
109
|
+
this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${dbVersion}:${STORE_NAME}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private async getOrCreateDb() {
|
|
113
|
+
if (!this.db) {
|
|
114
|
+
this.db = await new Promise<IDBDatabase>((resolve, reject) => {
|
|
115
|
+
const request = withOnError(
|
|
116
|
+
globalThis.indexedDB.open(this.dbName, this.dbVersion),
|
|
117
|
+
reject,
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
request.onupgradeneeded = (event) => {
|
|
121
|
+
const db = (event.target as unknown as { result: IDBDatabase })
|
|
122
|
+
.result;
|
|
123
|
+
|
|
124
|
+
// Create the store on DB init.
|
|
125
|
+
const objectStore = db.createObjectStore(STORE_NAME, {
|
|
126
|
+
keyPath: "key",
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
objectStore.createIndex("key", "key", {
|
|
130
|
+
unique: true,
|
|
131
|
+
});
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
request.onsuccess = (event) => {
|
|
135
|
+
const db = (event.target as unknown as { result: IDBDatabase })
|
|
136
|
+
.result;
|
|
137
|
+
resolve(db);
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return this.db;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private async transact<T>(
|
|
146
|
+
mode: IDBTransactionMode,
|
|
147
|
+
callback: (
|
|
148
|
+
objectStore: IDBObjectStore,
|
|
149
|
+
resolve: (t: T) => void,
|
|
150
|
+
reject: (reason?: unknown) => void,
|
|
151
|
+
) => void,
|
|
152
|
+
): Promise<T> {
|
|
153
|
+
const db = await this.getOrCreateDb();
|
|
154
|
+
|
|
155
|
+
return await new Promise<T>((resolve, reject) => {
|
|
156
|
+
const transaction = withOnError(db.transaction(STORE_NAME, mode), reject);
|
|
157
|
+
|
|
158
|
+
transaction.onabort = (event) => {
|
|
159
|
+
reject(event);
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const objectStore = transaction.objectStore(STORE_NAME);
|
|
163
|
+
|
|
164
|
+
callback(objectStore, resolve, reject);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
public async set<T>(
|
|
169
|
+
key: string,
|
|
170
|
+
value: T,
|
|
171
|
+
expireDeltaMs: number = this.defaultExpiryDeltaMs,
|
|
172
|
+
): Promise<T> {
|
|
173
|
+
const obj = {
|
|
174
|
+
key,
|
|
175
|
+
value,
|
|
176
|
+
expireMs: Date.now() + expireDeltaMs,
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
return await this.transact<T>(
|
|
180
|
+
"readwrite",
|
|
181
|
+
(objectStore, resolve, reject) => {
|
|
182
|
+
const request = withOnError(objectStore.put(obj), reject);
|
|
183
|
+
|
|
184
|
+
request.onsuccess = () => {
|
|
185
|
+
resolve(value);
|
|
186
|
+
|
|
187
|
+
this.gc(); // check GC on every write
|
|
188
|
+
};
|
|
189
|
+
},
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Delete one or multiple keys. */
|
|
194
|
+
public async delete(key: string | string[]): Promise<void> {
|
|
195
|
+
return await this.transact<void>(
|
|
196
|
+
"readwrite",
|
|
197
|
+
(objectStore, resolve, reject) => {
|
|
198
|
+
objectStore.transaction.oncomplete = () => {
|
|
199
|
+
resolve();
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
if (typeof key === "string") {
|
|
203
|
+
withOnError(objectStore.delete(key), reject);
|
|
204
|
+
} else {
|
|
205
|
+
for (const k of key) {
|
|
206
|
+
withOnError(objectStore.delete(k), reject);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
public async get<T>(key: string): Promise<T | undefined> {
|
|
214
|
+
const stored = await this.transact<StoredObject<T> | undefined>(
|
|
215
|
+
"readonly",
|
|
216
|
+
(objectStore, resolve, reject) => {
|
|
217
|
+
const request = withOnError(objectStore.get(key), reject);
|
|
218
|
+
|
|
219
|
+
request.onsuccess = () => {
|
|
220
|
+
resolve(request.result);
|
|
221
|
+
};
|
|
222
|
+
},
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
if (!stored) {
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
const obj = validateStoredObject(stored);
|
|
231
|
+
if (!obj) {
|
|
232
|
+
await this.delete(key);
|
|
233
|
+
|
|
234
|
+
this.gc(); // check GC on every read of an expired key
|
|
235
|
+
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return obj.value;
|
|
240
|
+
} catch (e) {
|
|
241
|
+
console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);
|
|
242
|
+
await this.delete(key);
|
|
243
|
+
|
|
244
|
+
this.gc(); // check GC on every read of an invalid key
|
|
245
|
+
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
public async forEach(
|
|
251
|
+
callback: (
|
|
252
|
+
key: string,
|
|
253
|
+
value: unknown,
|
|
254
|
+
expireMs: number,
|
|
255
|
+
) => void | Promise<void>,
|
|
256
|
+
): Promise<void> {
|
|
257
|
+
await this.transact<void>("readonly", (objectStore, resolve, reject) => {
|
|
258
|
+
const request = withOnError(objectStore.openCursor(), reject);
|
|
259
|
+
|
|
260
|
+
request.onsuccess = async (event) => {
|
|
261
|
+
const cursor = (
|
|
262
|
+
event.target as unknown as { result: IDBCursorWithValue }
|
|
263
|
+
).result;
|
|
264
|
+
|
|
265
|
+
if (cursor) {
|
|
266
|
+
if (cursor.key) {
|
|
267
|
+
const obj = validateStoredObject(cursor.value);
|
|
268
|
+
if (obj) {
|
|
269
|
+
await callback(String(cursor.key), obj.value, obj.expireMs);
|
|
270
|
+
} else {
|
|
271
|
+
await callback(String(cursor.key), undefined, 0);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
cursor.continue();
|
|
275
|
+
} else {
|
|
276
|
+
resolve();
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Cannot be a getter because this needs to be async. */
|
|
283
|
+
public async size() {
|
|
284
|
+
let count = 0;
|
|
285
|
+
await this.forEach(() => {
|
|
286
|
+
count++;
|
|
287
|
+
});
|
|
288
|
+
return count;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
public async clear() {
|
|
292
|
+
const keys: string[] = [];
|
|
293
|
+
await this.forEach((key) => {
|
|
294
|
+
keys.push(key);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
await this.delete(keys);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Mainly for debugging dumps. */
|
|
301
|
+
public async asMap(): Promise<Map<string, unknown>> {
|
|
302
|
+
const map = new Map<string, unknown>();
|
|
303
|
+
await this.forEach((key, value, expireMs) => {
|
|
304
|
+
map.set(key, { value, expireMs });
|
|
305
|
+
});
|
|
306
|
+
return map;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
public get lastGcMs(): number {
|
|
310
|
+
const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);
|
|
311
|
+
if (!lastGcMsStr) return 0;
|
|
312
|
+
|
|
313
|
+
const ms = Number(lastGcMsStr);
|
|
314
|
+
return isNaN(ms) ? 0 : ms;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
public set lastGcMs(ms: number) {
|
|
318
|
+
globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Perform garbage-collection if due. */
|
|
322
|
+
public async gc() {
|
|
323
|
+
const lastGcMs = this.lastGcMs;
|
|
324
|
+
|
|
325
|
+
// Set initial timestamp - no need GC now.
|
|
326
|
+
if (!lastGcMs) {
|
|
327
|
+
this.lastGcMs = Date.now();
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (Date.now() < lastGcMs + GC_INTERVAL_MS) {
|
|
332
|
+
return; // not due for next GC yet
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// GC is due now, so run it.
|
|
336
|
+
await this.gcNow();
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Perform garbage-collection immediately without checking. */
|
|
340
|
+
public async gcNow() {
|
|
341
|
+
console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);
|
|
342
|
+
|
|
343
|
+
// Prevent concurrent GC runs.
|
|
344
|
+
this.lastGcMs = Date.now();
|
|
345
|
+
|
|
346
|
+
const keysToDelete: string[] = [];
|
|
347
|
+
await this.forEach(
|
|
348
|
+
async (key: string, value: unknown, expireMs: number) => {
|
|
349
|
+
if (value === undefined || Date.now() >= expireMs) {
|
|
350
|
+
keysToDelete.push(key);
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
);
|
|
354
|
+
|
|
355
|
+
if (keysToDelete.length) {
|
|
356
|
+
await this.delete(keysToDelete);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
console.log(
|
|
360
|
+
`Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +
|
|
361
|
+
`- deleted ${keysToDelete.length} keys`,
|
|
362
|
+
);
|
|
363
|
+
|
|
364
|
+
// Mark the end time as last GC time.
|
|
365
|
+
this.lastGcMs = Date.now();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Get an independent store item with a locked key and value type. */
|
|
369
|
+
public field<T>(key: string) {
|
|
370
|
+
return new KVStoreField<T>(this, key);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Default KV store ready for immediate use. You can create new instances if
|
|
376
|
+
* you want, but most likely you will only need one store instance.
|
|
377
|
+
*/
|
|
378
|
+
export const kvStore = new KVStore(
|
|
379
|
+
DEFAULT_DB_NAME,
|
|
380
|
+
DEFAULT_DB_VERSION,
|
|
381
|
+
DEFAULT_EXPIRY_DELTA_MS,
|
|
382
|
+
);
|
package/src/localStorageCache.ts
CHANGED
|
@@ -13,7 +13,10 @@ export class LocalStorageCache {
|
|
|
13
13
|
|
|
14
14
|
public static getValue<T>(key: string, logError = true): T | undefined {
|
|
15
15
|
const jsonStr = globalThis.localStorage.getItem(key);
|
|
16
|
-
|
|
16
|
+
|
|
17
|
+
if (!jsonStr || typeof jsonStr !== "string") {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
17
20
|
|
|
18
21
|
try {
|
|
19
22
|
const obj: { value: T; expireMs: number } | undefined =
|
|
@@ -22,17 +25,14 @@ export class LocalStorageCache {
|
|
|
22
25
|
!obj ||
|
|
23
26
|
typeof obj !== "object" ||
|
|
24
27
|
!("value" in obj) ||
|
|
25
|
-
!("expireMs" in obj)
|
|
28
|
+
!("expireMs" in obj) ||
|
|
29
|
+
typeof obj.expireMs !== "number" ||
|
|
30
|
+
Date.now() >= obj.expireMs
|
|
26
31
|
) {
|
|
27
32
|
globalThis.localStorage.removeItem(key);
|
|
28
33
|
return undefined;
|
|
29
34
|
}
|
|
30
35
|
|
|
31
|
-
if (Date.now() >= obj.expireMs) {
|
|
32
|
-
globalThis.localStorage.removeItem(key);
|
|
33
|
-
return undefined;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
36
|
return obj.value;
|
|
37
37
|
} catch (e) {
|
|
38
38
|
if (logError) {
|
|
@@ -43,3 +43,27 @@ export class LocalStorageCache {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
+
|
|
47
|
+
/** Same as above, but saves some config for reuse. */
|
|
48
|
+
export class LocalStorageCacheItem<T> {
|
|
49
|
+
public constructor(
|
|
50
|
+
public readonly key: string,
|
|
51
|
+
public readonly expireDeltaMs: number,
|
|
52
|
+
public readonly logError = true,
|
|
53
|
+
defaultValue?: T,
|
|
54
|
+
) {
|
|
55
|
+
if (defaultValue !== undefined) {
|
|
56
|
+
if (this.get() === undefined) {
|
|
57
|
+
this.set(defaultValue);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
public set(value: T) {
|
|
63
|
+
LocalStorageCache.setValue(this.key, value, this.expireDeltaMs);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
public get(): T | undefined {
|
|
67
|
+
return LocalStorageCache.getValue(this.key, this.logError);
|
|
68
|
+
}
|
|
69
|
+
}
|
package/src/nonEmpty.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { isEmpty } from "./isEmpty";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Type asserts that `t` is truthy.
|
|
5
|
+
* Throws an error if `t` is null or undefined.
|
|
6
|
+
*/
|
|
7
|
+
export function nonEmpty<T>(
|
|
8
|
+
t: T | null | undefined | "" | 0 | -0 | 0n | false | typeof NaN,
|
|
9
|
+
varName = "value",
|
|
10
|
+
): T {
|
|
11
|
+
if (isEmpty(t)) {
|
|
12
|
+
throw new Error(`Empty ${varName}: ${t}`);
|
|
13
|
+
}
|
|
14
|
+
return t as T;
|
|
15
|
+
}
|
package/src/nonNil.ts
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* Type asserts that `t` is neither null nor undefined.
|
|
3
3
|
* Throws an error if `t` is null or undefined.
|
|
4
4
|
*/
|
|
5
|
-
export function nonNil<T>(t: T | null | undefined, varName = "
|
|
5
|
+
export function nonNil<T>(t: T | null | undefined, varName = "value"): T {
|
|
6
6
|
if (t === null || t === undefined) {
|
|
7
|
-
throw new Error(`Missing ${varName}`);
|
|
7
|
+
throw new Error(`Missing ${varName}: ${t}`);
|
|
8
8
|
}
|
|
9
9
|
return t;
|
|
10
10
|
}
|