@choksheak/ts-utils 0.2.9 → 0.3.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.
- package/README.md +2 -0
- package/{arrayBuffer.js → arrayBuffer.cjs} +0 -1
- package/arrayBuffer.d.mts +10 -0
- package/arrayBuffer.d.ts +4 -2
- package/arrayBuffer.min.cjs +2 -0
- package/arrayBuffer.min.cjs.map +1 -0
- package/arrayBuffer.min.mjs +2 -0
- package/{arrayBuffer.js.map → arrayBuffer.min.mjs.map} +1 -1
- package/arrayBuffer.mjs +14 -0
- package/{assert.js → assert.cjs} +0 -1
- package/assert.d.mts +7 -0
- package/assert.d.ts +3 -1
- package/assert.min.cjs +2 -0
- package/assert.min.cjs.map +1 -0
- package/assert.min.mjs +2 -0
- package/{assert.js.map → assert.min.mjs.map} +1 -1
- package/assert.mjs +11 -0
- package/{average.js → average.cjs} +0 -1
- package/average.d.mts +7 -0
- package/average.d.ts +3 -1
- package/average.min.cjs +2 -0
- package/{average.js.map → average.min.cjs.map} +1 -1
- package/average.min.mjs +2 -0
- package/average.min.mjs.map +1 -0
- package/average.mjs +20 -0
- package/{base64Url.js → base64Url.cjs} +0 -1
- package/base64Url.d.mts +10 -0
- package/base64Url.d.ts +4 -2
- package/base64Url.min.cjs +2 -0
- package/base64Url.min.cjs.map +1 -0
- package/base64Url.min.mjs +2 -0
- package/{base64Url.js.map → base64Url.min.mjs.map} +1 -1
- package/base64Url.mjs +14 -0
- package/{dateTimeStr.js → dateTimeStr.cjs} +0 -1
- package/dateTimeStr.d.mts +85 -0
- package/dateTimeStr.d.ts +15 -13
- package/dateTimeStr.min.cjs +2 -0
- package/dateTimeStr.min.cjs.map +1 -0
- package/dateTimeStr.min.mjs +2 -0
- package/{dateTimeStr.js.map → dateTimeStr.min.mjs.map} +1 -1
- package/dateTimeStr.mjs +83 -0
- package/{duration.js → duration.cjs} +9 -11
- package/duration.d.mts +78 -0
- package/duration.d.ts +15 -13
- package/duration.min.cjs +2 -0
- package/duration.min.cjs.map +1 -0
- package/duration.min.mjs +2 -0
- package/duration.min.mjs.map +1 -0
- package/duration.mjs +154 -0
- package/{isEmpty.js → isEmpty.cjs} +0 -1
- package/isEmpty.d.mts +6 -0
- package/isEmpty.d.ts +3 -1
- package/isEmpty.min.cjs +2 -0
- package/isEmpty.min.cjs.map +1 -0
- package/isEmpty.min.mjs +2 -0
- package/{isEmpty.js.map → isEmpty.min.mjs.map} +1 -1
- package/isEmpty.mjs +22 -0
- package/iterators.cjs +34 -0
- package/iterators.d.mts +4 -0
- package/iterators.d.ts +4 -0
- package/iterators.min.cjs +2 -0
- package/iterators.min.cjs.map +1 -0
- package/iterators.min.mjs +2 -0
- package/iterators.min.mjs.map +1 -0
- package/iterators.mjs +9 -0
- package/kvStore.cjs +365 -0
- package/kvStore.d.mts +139 -0
- package/kvStore.d.ts +95 -50
- package/kvStore.min.cjs +2 -0
- package/kvStore.min.cjs.map +1 -0
- package/kvStore.min.mjs +2 -0
- package/kvStore.min.mjs.map +1 -0
- package/kvStore.mjs +333 -0
- package/localStore.cjs +267 -0
- package/localStore.d.mts +119 -0
- package/localStore.d.ts +119 -0
- package/localStore.min.cjs +2 -0
- package/localStore.min.cjs.map +1 -0
- package/localStore.min.mjs +2 -0
- package/localStore.min.mjs.map +1 -0
- package/localStore.mjs +235 -0
- package/{logging.js → logging.cjs} +0 -1
- package/logging.d.mts +4 -0
- package/logging.d.ts +4 -2
- package/logging.min.cjs +2 -0
- package/logging.min.cjs.map +1 -0
- package/logging.min.mjs +2 -0
- package/{logging.js.map → logging.min.mjs.map} +1 -1
- package/logging.mjs +21 -0
- package/{nonEmpty.js → nonEmpty.cjs} +0 -1
- package/nonEmpty.d.mts +10 -0
- package/nonEmpty.d.ts +3 -1
- package/nonEmpty.min.cjs +2 -0
- package/{nonEmpty.js.map → nonEmpty.min.cjs.map} +1 -1
- package/nonEmpty.min.mjs +2 -0
- package/nonEmpty.min.mjs.map +1 -0
- package/nonEmpty.mjs +30 -0
- package/{nonNil.js → nonNil.cjs} +0 -1
- package/{src/nonNil.ts → nonNil.d.mts} +3 -6
- package/nonNil.d.ts +3 -1
- package/nonNil.min.cjs +2 -0
- package/nonNil.min.cjs.map +1 -0
- package/nonNil.min.mjs +2 -0
- package/{nonNil.js.map → nonNil.min.mjs.map} +1 -1
- package/nonNil.mjs +10 -0
- package/package.json +447 -24
- package/{round.js → round.cjs} +0 -1
- package/{src/round.ts → round.d.mts} +4 -8
- package/round.d.ts +4 -2
- package/round.min.cjs +2 -0
- package/round.min.cjs.map +1 -0
- package/round.min.mjs +2 -0
- package/{round.js.map → round.min.mjs.map} +1 -1
- package/round.mjs +12 -0
- package/{safeBtoa.js → safeBtoa.cjs} +0 -1
- package/safeBtoa.d.mts +6 -0
- package/safeBtoa.d.ts +3 -1
- package/safeBtoa.min.cjs +2 -0
- package/safeBtoa.min.cjs.map +1 -0
- package/safeBtoa.min.mjs +2 -0
- package/{safeBtoa.js.map → safeBtoa.min.mjs.map} +1 -1
- package/safeBtoa.mjs +9 -0
- package/{safeParseFloat.js → safeParseFloat.cjs} +0 -1
- package/safeParseFloat.d.mts +6 -0
- package/safeParseFloat.d.ts +3 -1
- package/safeParseFloat.min.cjs +2 -0
- package/safeParseFloat.min.cjs.map +1 -0
- package/safeParseFloat.min.mjs +2 -0
- package/{safeParseFloat.js.map → safeParseFloat.min.mjs.map} +1 -1
- package/safeParseFloat.mjs +8 -0
- package/{safeParseInt.js → safeParseInt.cjs} +0 -1
- package/safeParseInt.d.mts +6 -0
- package/safeParseInt.d.ts +3 -1
- package/safeParseInt.min.cjs +2 -0
- package/safeParseInt.min.cjs.map +1 -0
- package/safeParseInt.min.mjs +2 -0
- package/{safeParseInt.js.map → safeParseInt.min.mjs.map} +1 -1
- package/safeParseInt.mjs +8 -0
- package/sha256.cjs +35 -0
- package/sha256.d.mts +6 -0
- package/sha256.d.ts +3 -1
- package/sha256.min.cjs +2 -0
- package/sha256.min.cjs.map +1 -0
- package/sha256.min.mjs +2 -0
- package/{sha256.js.map → sha256.min.mjs.map} +1 -1
- package/sha256.mjs +10 -0
- package/{sleep.js → sleep.cjs} +0 -1
- package/{src/sleep.ts → sleep.d.mts} +3 -3
- package/sleep.d.ts +3 -1
- package/sleep.min.cjs +2 -0
- package/sleep.min.cjs.map +1 -0
- package/sleep.min.mjs +2 -0
- package/{sleep.js.map → sleep.min.mjs.map} +1 -1
- package/sleep.mjs +7 -0
- package/storageAdapter.cjs +18 -0
- package/storageAdapter.d.mts +33 -0
- package/storageAdapter.d.ts +33 -0
- package/storageAdapter.min.cjs +2 -0
- package/storageAdapter.min.cjs.map +1 -0
- package/storageAdapter.min.mjs +1 -0
- package/storageAdapter.min.mjs.map +1 -0
- package/storageAdapter.mjs +0 -0
- package/{sum.js → sum.cjs} +0 -1
- package/sum.d.mts +7 -0
- package/sum.d.ts +3 -1
- package/sum.min.cjs +2 -0
- package/sum.min.cjs.map +1 -0
- package/sum.min.mjs +2 -0
- package/{sum.js.map → sum.min.mjs.map} +1 -1
- package/sum.mjs +13 -0
- package/{timeConstants.js → timeConstants.cjs} +0 -1
- package/timeConstants.d.mts +20 -0
- package/timeConstants.d.ts +16 -14
- package/timeConstants.min.cjs +2 -0
- package/timeConstants.min.cjs.map +1 -0
- package/timeConstants.min.mjs +2 -0
- package/{timeConstants.js.map → timeConstants.min.mjs.map} +1 -1
- package/timeConstants.mjs +31 -0
- package/{timer.js → timer.cjs} +6 -6
- package/timer.d.mts +13 -0
- package/timer.d.ts +4 -2
- package/timer.min.cjs +2 -0
- package/timer.min.cjs.map +1 -0
- package/timer.min.mjs +2 -0
- package/timer.min.mjs.map +1 -0
- package/timer.mjs +161 -0
- package/docs/.nojekyll +0 -1
- package/docs/assets/hierarchy.js +0 -1
- package/docs/assets/highlight.css +0 -22
- package/docs/assets/icons.js +0 -18
- package/docs/assets/icons.svg +0 -1
- package/docs/assets/main.js +0 -60
- package/docs/assets/navigation.js +0 -1
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1640
- package/docs/classes/kvStore.KVStore.html +0 -26
- package/docs/classes/kvStore.KVStoreField.html +0 -7
- package/docs/classes/timer.Timer.html +0 -8
- package/docs/functions/arrayBuffer.arrayBufferToBase64.html +0 -2
- package/docs/functions/arrayBuffer.arrayBufferToHex.html +0 -2
- package/docs/functions/assert.assert.html +0 -3
- package/docs/functions/average.average.html +0 -3
- package/docs/functions/base64Url.base64ToBase64URL.html +0 -2
- package/docs/functions/base64Url.base64UrlToBase64.html +0 -2
- package/docs/functions/dateTimeStr.getDisplayDateTime.html +0 -3
- package/docs/functions/dateTimeStr.getLongMonthNameOneIndexed.html +0 -4
- package/docs/functions/dateTimeStr.getLongMonthNameZeroIndexed.html +0 -4
- package/docs/functions/dateTimeStr.getShortMonthNameOneIndexed.html +0 -4
- package/docs/functions/dateTimeStr.getShortMonthNameZeroIndexed.html +0 -4
- package/docs/functions/dateTimeStr.hhMm.html +0 -4
- package/docs/functions/dateTimeStr.hhMmSs.html +0 -4
- package/docs/functions/dateTimeStr.hhMmSsMs.html +0 -5
- package/docs/functions/dateTimeStr.toDate.html +0 -4
- package/docs/functions/dateTimeStr.tzShort.html +0 -4
- package/docs/functions/dateTimeStr.yyyyMm.html +0 -4
- package/docs/functions/dateTimeStr.yyyyMmDd.html +0 -4
- package/docs/functions/duration.durationOrMsToMs.html +0 -2
- package/docs/functions/duration.durationToMs.html +0 -2
- package/docs/functions/duration.elapsed.html +0 -2
- package/docs/functions/duration.formatDuration.html +0 -4
- package/docs/functions/duration.msToDuration.html +0 -5
- package/docs/functions/duration.readableDuration.html +0 -4
- package/docs/functions/isEmpty.isEmpty.html +0 -2
- package/docs/functions/kvStore.kvStoreItem.html +0 -2
- package/docs/functions/localStorageCache.storeItem.html +0 -15
- package/docs/functions/logging.capLength.html +0 -1
- package/docs/functions/logging.stringify.html +0 -1
- package/docs/functions/nonEmpty.nonEmpty.html +0 -5
- package/docs/functions/nonNil.nonNil.html +0 -5
- package/docs/functions/round.round.html +0 -5
- package/docs/functions/round.roundS.html +0 -3
- package/docs/functions/safeBtoa.safeBtoa.html +0 -2
- package/docs/functions/safeParseFloat.safeParseFloat.html +0 -2
- package/docs/functions/safeParseInt.safeParseInt.html +0 -2
- package/docs/functions/sha256.sha256.html +0 -2
- package/docs/functions/sleep.sleep.html +0 -3
- package/docs/functions/sum.sum.html +0 -3
- package/docs/functions/timer.timer.html +0 -2
- package/docs/hierarchy.html +0 -1
- package/docs/index.html +0 -4
- package/docs/modules/arrayBuffer.html +0 -1
- package/docs/modules/assert.html +0 -1
- package/docs/modules/average.html +0 -1
- package/docs/modules/base64Url.html +0 -1
- package/docs/modules/dateTimeStr.html +0 -1
- package/docs/modules/duration.html +0 -1
- package/docs/modules/isEmpty.html +0 -1
- package/docs/modules/kvStore.html +0 -1
- package/docs/modules/localStorageCache.html +0 -1
- package/docs/modules/logging.html +0 -1
- package/docs/modules/nonEmpty.html +0 -1
- package/docs/modules/nonNil.html +0 -1
- package/docs/modules/round.html +0 -1
- package/docs/modules/safeBtoa.html +0 -1
- package/docs/modules/safeParseFloat.html +0 -1
- package/docs/modules/safeParseInt.html +0 -1
- package/docs/modules/sha256.html +0 -1
- package/docs/modules/sleep.html +0 -1
- package/docs/modules/sum.html +0 -1
- package/docs/modules/timeConstants.html +0 -1
- package/docs/modules/timer.html +0 -1
- package/docs/modules.html +0 -1
- package/docs/types/dateTimeStr.AnyDateTime.html +0 -1
- package/docs/types/duration.Duration.html +0 -6
- package/docs/types/duration.DurationStyle.html +0 -6
- package/docs/types/duration.DurationSuffixMap.html +0 -6
- package/docs/types/duration.DurationSuffixType.html +0 -1
- package/docs/types/duration.DurationType.html +0 -2
- package/docs/types/localStorageCache.StoredItem.html +0 -4
- package/docs/variables/duration.DURATION_STYLE_SUFFIX_MAP.html +0 -1
- package/docs/variables/duration.DURATION_TYPE_SEQUENCE.html +0 -2
- package/docs/variables/kvStore.DEFAULT_EXPIRY_DELTA_MS.html +0 -2
- package/docs/variables/kvStore.GC_INTERVAL_MS.html +0 -2
- package/docs/variables/kvStore.MILLIS_PER_DAY.html +0 -2
- package/docs/variables/kvStore.kvStore.html +0 -3
- package/docs/variables/timeConstants.HOURS_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.HOURS_PER_WEEK.html +0 -1
- package/docs/variables/timeConstants.MINUTES_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.MINUTES_PER_HOUR.html +0 -1
- package/docs/variables/timeConstants.MINUTES_PER_WEEK.html +0 -1
- package/docs/variables/timeConstants.MS_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.MS_PER_HOUR.html +0 -1
- package/docs/variables/timeConstants.MS_PER_MINUTE.html +0 -1
- package/docs/variables/timeConstants.MS_PER_SECOND.html +0 -3
- package/docs/variables/timeConstants.MS_PER_WEEK.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_HOUR.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_MINUTE.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_WEEK.html +0 -1
- package/duration.js.map +0 -1
- package/kvStore.js +0 -383
- package/kvStore.js.map +0 -1
- package/localStorageCache.d.ts +0 -55
- package/localStorageCache.js +0 -121
- package/localStorageCache.js.map +0 -1
- package/sha256.js +0 -58
- package/src/arrayBuffer.ts +0 -29
- package/src/assert.ts +0 -14
- package/src/average.ts +0 -13
- package/src/base64Url.ts +0 -20
- package/src/dateTimeStr.ts +0 -184
- package/src/duration.ts +0 -260
- package/src/isEmpty.ts +0 -32
- package/src/kvStore.ts +0 -444
- package/src/localStorageCache.ts +0 -121
- package/src/logging.ts +0 -26
- package/src/nonEmpty.ts +0 -18
- package/src/safeBtoa.ts +0 -15
- package/src/safeParseFloat.ts +0 -10
- package/src/safeParseInt.ts +0 -10
- package/src/sha256.ts +0 -13
- package/src/sum.ts +0 -17
- package/src/timeConstants.ts +0 -22
- package/src/timer.ts +0 -33
- package/timer.js.map +0 -1
package/kvStore.js
DELETED
|
@@ -1,383 +0,0 @@
|
|
|
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
|
-
var __async = (__this, __arguments, generator) => {
|
|
20
|
-
return new Promise((resolve, reject) => {
|
|
21
|
-
var fulfilled = (value) => {
|
|
22
|
-
try {
|
|
23
|
-
step(generator.next(value));
|
|
24
|
-
} catch (e) {
|
|
25
|
-
reject(e);
|
|
26
|
-
}
|
|
27
|
-
};
|
|
28
|
-
var rejected = (value) => {
|
|
29
|
-
try {
|
|
30
|
-
step(generator.throw(value));
|
|
31
|
-
} catch (e) {
|
|
32
|
-
reject(e);
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
36
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
37
|
-
});
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
// src/kvStore.ts
|
|
41
|
-
var kvStore_exports = {};
|
|
42
|
-
__export(kvStore_exports, {
|
|
43
|
-
DEFAULT_EXPIRY_DELTA_MS: () => DEFAULT_EXPIRY_DELTA_MS,
|
|
44
|
-
GC_INTERVAL_MS: () => GC_INTERVAL_MS,
|
|
45
|
-
KVStore: () => KVStore,
|
|
46
|
-
KVStoreField: () => KVStoreField,
|
|
47
|
-
MILLIS_PER_DAY: () => MILLIS_PER_DAY,
|
|
48
|
-
kvStore: () => kvStore,
|
|
49
|
-
kvStoreItem: () => kvStoreItem
|
|
50
|
-
});
|
|
51
|
-
module.exports = __toCommonJS(kvStore_exports);
|
|
52
|
-
|
|
53
|
-
// src/timeConstants.ts
|
|
54
|
-
var MS_PER_SECOND = 1e3;
|
|
55
|
-
var MS_PER_MINUTE = 6e4;
|
|
56
|
-
var MS_PER_HOUR = 36e5;
|
|
57
|
-
var MS_PER_DAY = 864e5;
|
|
58
|
-
|
|
59
|
-
// src/duration.ts
|
|
60
|
-
function durationToMs(duration) {
|
|
61
|
-
var _a, _b, _c, _d, _e;
|
|
62
|
-
const daysMs = ((_a = duration.days) != null ? _a : 0) * MS_PER_DAY;
|
|
63
|
-
const hoursMs = ((_b = duration.hours) != null ? _b : 0) * MS_PER_HOUR;
|
|
64
|
-
const minsMs = ((_c = duration.minutes) != null ? _c : 0) * MS_PER_MINUTE;
|
|
65
|
-
const secsMs = ((_d = duration.seconds) != null ? _d : 0) * MS_PER_SECOND;
|
|
66
|
-
const msMs = (_e = duration.milliseconds) != null ? _e : 0;
|
|
67
|
-
return daysMs + hoursMs + minsMs + secsMs + msMs;
|
|
68
|
-
}
|
|
69
|
-
function durationOrMsToMs(duration) {
|
|
70
|
-
return typeof duration === "number" ? duration : durationToMs(duration);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// src/kvStore.ts
|
|
74
|
-
var DEFAULT_DB_NAME = "KVStore";
|
|
75
|
-
var DEFAULT_DB_VERSION = 1;
|
|
76
|
-
var STORE_NAME = "kvStore";
|
|
77
|
-
var MILLIS_PER_DAY = 864e5;
|
|
78
|
-
var DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;
|
|
79
|
-
var GC_INTERVAL_MS = MILLIS_PER_DAY;
|
|
80
|
-
function validateStoredObject(obj) {
|
|
81
|
-
if (!obj || typeof obj !== "object" || !("key" in obj) || typeof obj.key !== "string" || !("value" in obj) || !("storedMs" in obj) || typeof obj.storedMs !== "number" || obj.value === void 0 || !("expiryMs" in obj) || typeof obj.expiryMs !== "number" || Date.now() >= obj.expiryMs) {
|
|
82
|
-
return void 0;
|
|
83
|
-
}
|
|
84
|
-
return obj;
|
|
85
|
-
}
|
|
86
|
-
function withOnError(request, reject) {
|
|
87
|
-
request.onerror = (event) => {
|
|
88
|
-
reject(event);
|
|
89
|
-
};
|
|
90
|
-
return request;
|
|
91
|
-
}
|
|
92
|
-
var KVStoreField = class {
|
|
93
|
-
constructor(store, key) {
|
|
94
|
-
this.store = store;
|
|
95
|
-
this.key = key;
|
|
96
|
-
}
|
|
97
|
-
get() {
|
|
98
|
-
return this.store.get(this.key);
|
|
99
|
-
}
|
|
100
|
-
set(t) {
|
|
101
|
-
return this.store.set(this.key, t);
|
|
102
|
-
}
|
|
103
|
-
delete() {
|
|
104
|
-
return this.store.delete(this.key);
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
var KVStore = class {
|
|
108
|
-
constructor(dbName, dbVersion, defaultExpiryDeltaMs) {
|
|
109
|
-
this.dbName = dbName;
|
|
110
|
-
this.dbVersion = dbVersion;
|
|
111
|
-
this.defaultExpiryDeltaMs = defaultExpiryDeltaMs;
|
|
112
|
-
this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${dbVersion}:${STORE_NAME}`;
|
|
113
|
-
}
|
|
114
|
-
getOrCreateDb() {
|
|
115
|
-
return __async(this, null, function* () {
|
|
116
|
-
if (!this.db) {
|
|
117
|
-
this.db = yield new Promise((resolve, reject) => {
|
|
118
|
-
const request = withOnError(
|
|
119
|
-
globalThis.indexedDB.open(this.dbName, this.dbVersion),
|
|
120
|
-
reject
|
|
121
|
-
);
|
|
122
|
-
request.onupgradeneeded = (event) => {
|
|
123
|
-
const db = event.target.result;
|
|
124
|
-
const objectStore = db.createObjectStore(STORE_NAME, {
|
|
125
|
-
keyPath: "key"
|
|
126
|
-
});
|
|
127
|
-
objectStore.createIndex("key", "key", {
|
|
128
|
-
unique: true
|
|
129
|
-
});
|
|
130
|
-
};
|
|
131
|
-
request.onsuccess = (event) => {
|
|
132
|
-
const db = event.target.result;
|
|
133
|
-
resolve(db);
|
|
134
|
-
};
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
return this.db;
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
transact(mode, callback) {
|
|
141
|
-
return __async(this, null, function* () {
|
|
142
|
-
const db = yield this.getOrCreateDb();
|
|
143
|
-
return yield new Promise((resolve, reject) => {
|
|
144
|
-
const transaction = withOnError(db.transaction(STORE_NAME, mode), reject);
|
|
145
|
-
transaction.onabort = (event) => {
|
|
146
|
-
reject(event);
|
|
147
|
-
};
|
|
148
|
-
const objectStore = transaction.objectStore(STORE_NAME);
|
|
149
|
-
callback(objectStore, resolve, reject);
|
|
150
|
-
});
|
|
151
|
-
});
|
|
152
|
-
}
|
|
153
|
-
set(_0, _1) {
|
|
154
|
-
return __async(this, arguments, function* (key, value, expiryDeltaMs = this.defaultExpiryDeltaMs) {
|
|
155
|
-
const nowMs = Date.now();
|
|
156
|
-
const obj = {
|
|
157
|
-
key,
|
|
158
|
-
value,
|
|
159
|
-
storedMs: nowMs,
|
|
160
|
-
expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs)
|
|
161
|
-
};
|
|
162
|
-
return yield this.transact(
|
|
163
|
-
"readwrite",
|
|
164
|
-
(objectStore, resolve, reject) => {
|
|
165
|
-
const request = withOnError(objectStore.put(obj), reject);
|
|
166
|
-
request.onsuccess = () => {
|
|
167
|
-
resolve(value);
|
|
168
|
-
this.gc();
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
);
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
/** Delete one or multiple keys. */
|
|
175
|
-
delete(key) {
|
|
176
|
-
return __async(this, null, function* () {
|
|
177
|
-
return yield this.transact(
|
|
178
|
-
"readwrite",
|
|
179
|
-
(objectStore, resolve, reject) => {
|
|
180
|
-
objectStore.transaction.oncomplete = () => {
|
|
181
|
-
resolve();
|
|
182
|
-
};
|
|
183
|
-
if (typeof key === "string") {
|
|
184
|
-
withOnError(objectStore.delete(key), reject);
|
|
185
|
-
} else {
|
|
186
|
-
for (const k of key) {
|
|
187
|
-
withOnError(objectStore.delete(k), reject);
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
);
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
getStoredObject(key) {
|
|
195
|
-
return __async(this, null, function* () {
|
|
196
|
-
const stored = yield this.transact(
|
|
197
|
-
"readonly",
|
|
198
|
-
(objectStore, resolve, reject) => {
|
|
199
|
-
const request = withOnError(objectStore.get(key), reject);
|
|
200
|
-
request.onsuccess = () => {
|
|
201
|
-
resolve(request.result);
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
);
|
|
205
|
-
if (!stored) {
|
|
206
|
-
return void 0;
|
|
207
|
-
}
|
|
208
|
-
try {
|
|
209
|
-
const obj = validateStoredObject(stored);
|
|
210
|
-
if (!obj) {
|
|
211
|
-
yield this.delete(key);
|
|
212
|
-
this.gc();
|
|
213
|
-
return void 0;
|
|
214
|
-
}
|
|
215
|
-
return obj;
|
|
216
|
-
} catch (e) {
|
|
217
|
-
console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);
|
|
218
|
-
yield this.delete(key);
|
|
219
|
-
this.gc();
|
|
220
|
-
return void 0;
|
|
221
|
-
}
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
get(key) {
|
|
225
|
-
return __async(this, null, function* () {
|
|
226
|
-
const obj = yield this.getStoredObject(key);
|
|
227
|
-
return obj == null ? void 0 : obj.value;
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
forEach(callback) {
|
|
231
|
-
return __async(this, null, function* () {
|
|
232
|
-
yield this.transact("readonly", (objectStore, resolve, reject) => {
|
|
233
|
-
const request = withOnError(objectStore.openCursor(), reject);
|
|
234
|
-
request.onsuccess = (event) => __async(this, null, function* () {
|
|
235
|
-
const cursor = event.target.result;
|
|
236
|
-
if (cursor) {
|
|
237
|
-
if (cursor.key) {
|
|
238
|
-
const obj = validateStoredObject(cursor.value);
|
|
239
|
-
if (obj) {
|
|
240
|
-
yield callback(String(cursor.key), obj.value, obj.expiryMs);
|
|
241
|
-
} else {
|
|
242
|
-
yield callback(String(cursor.key), void 0, 0);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
cursor.continue();
|
|
246
|
-
} else {
|
|
247
|
-
resolve();
|
|
248
|
-
}
|
|
249
|
-
});
|
|
250
|
-
});
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
/** Cannot be a getter because this needs to be async. */
|
|
254
|
-
size() {
|
|
255
|
-
return __async(this, null, function* () {
|
|
256
|
-
let count = 0;
|
|
257
|
-
yield this.forEach(() => {
|
|
258
|
-
count++;
|
|
259
|
-
});
|
|
260
|
-
return count;
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
clear() {
|
|
264
|
-
return __async(this, null, function* () {
|
|
265
|
-
const keys = [];
|
|
266
|
-
yield this.forEach((key) => {
|
|
267
|
-
keys.push(key);
|
|
268
|
-
});
|
|
269
|
-
yield this.delete(keys);
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
/** Mainly for debugging dumps. */
|
|
273
|
-
asMap() {
|
|
274
|
-
return __async(this, null, function* () {
|
|
275
|
-
const map = /* @__PURE__ */ new Map();
|
|
276
|
-
yield this.forEach((key, value, expiryMs) => {
|
|
277
|
-
map.set(key, { value, expiryMs });
|
|
278
|
-
});
|
|
279
|
-
return map;
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
get lastGcMs() {
|
|
283
|
-
const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);
|
|
284
|
-
if (!lastGcMsStr) return 0;
|
|
285
|
-
const ms = Number(lastGcMsStr);
|
|
286
|
-
return isNaN(ms) ? 0 : ms;
|
|
287
|
-
}
|
|
288
|
-
set lastGcMs(ms) {
|
|
289
|
-
globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));
|
|
290
|
-
}
|
|
291
|
-
/** Perform garbage-collection if due. */
|
|
292
|
-
gc() {
|
|
293
|
-
return __async(this, null, function* () {
|
|
294
|
-
const lastGcMs = this.lastGcMs;
|
|
295
|
-
if (!lastGcMs) {
|
|
296
|
-
this.lastGcMs = Date.now();
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
if (Date.now() < lastGcMs + GC_INTERVAL_MS) {
|
|
300
|
-
return;
|
|
301
|
-
}
|
|
302
|
-
yield this.gcNow();
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
/** Perform garbage-collection immediately without checking. */
|
|
306
|
-
gcNow() {
|
|
307
|
-
return __async(this, null, function* () {
|
|
308
|
-
console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);
|
|
309
|
-
this.lastGcMs = Date.now();
|
|
310
|
-
const keysToDelete = [];
|
|
311
|
-
yield this.forEach(
|
|
312
|
-
(key, value, expiryMs) => __async(this, null, function* () {
|
|
313
|
-
if (value === void 0 || Date.now() >= expiryMs) {
|
|
314
|
-
keysToDelete.push(key);
|
|
315
|
-
}
|
|
316
|
-
})
|
|
317
|
-
);
|
|
318
|
-
if (keysToDelete.length) {
|
|
319
|
-
yield this.delete(keysToDelete);
|
|
320
|
-
}
|
|
321
|
-
console.log(
|
|
322
|
-
`Finished kvStore GC on ${this.dbName} v${this.dbVersion} - deleted ${keysToDelete.length} keys`
|
|
323
|
-
);
|
|
324
|
-
this.lastGcMs = Date.now();
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
/** Get an independent store item with a locked key and value type. */
|
|
328
|
-
field(key) {
|
|
329
|
-
return new KVStoreField(this, key);
|
|
330
|
-
}
|
|
331
|
-
};
|
|
332
|
-
var kvStore = new KVStore(
|
|
333
|
-
DEFAULT_DB_NAME,
|
|
334
|
-
DEFAULT_DB_VERSION,
|
|
335
|
-
DEFAULT_EXPIRY_DELTA_MS
|
|
336
|
-
);
|
|
337
|
-
var KvStoreItem = class {
|
|
338
|
-
constructor(key, defaultExpiryDeltaMs, store = kvStore) {
|
|
339
|
-
this.key = key;
|
|
340
|
-
this.defaultExpiryDeltaMs = defaultExpiryDeltaMs;
|
|
341
|
-
this.store = store;
|
|
342
|
-
}
|
|
343
|
-
/**
|
|
344
|
-
* Example usage:
|
|
345
|
-
*
|
|
346
|
-
* const { value, storedMs, expiryMs } = await myKvItem.getStoredObject();
|
|
347
|
-
*/
|
|
348
|
-
getStoredObject() {
|
|
349
|
-
return __async(this, null, function* () {
|
|
350
|
-
return yield this.store.getStoredObject(this.key);
|
|
351
|
-
});
|
|
352
|
-
}
|
|
353
|
-
get() {
|
|
354
|
-
return __async(this, null, function* () {
|
|
355
|
-
return yield this.store.get(this.key);
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
set(_0) {
|
|
359
|
-
return __async(this, arguments, function* (value, expiryDeltaMs = this.defaultExpiryDeltaMs) {
|
|
360
|
-
yield this.store.set(this.key, value, expiryDeltaMs);
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
delete() {
|
|
364
|
-
return __async(this, null, function* () {
|
|
365
|
-
yield this.store.delete(this.key);
|
|
366
|
-
});
|
|
367
|
-
}
|
|
368
|
-
};
|
|
369
|
-
function kvStoreItem(key, defaultExpiration) {
|
|
370
|
-
const defaultExpiryDeltaMs = durationOrMsToMs(defaultExpiration);
|
|
371
|
-
return new KvStoreItem(key, defaultExpiryDeltaMs);
|
|
372
|
-
}
|
|
373
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
374
|
-
0 && (module.exports = {
|
|
375
|
-
DEFAULT_EXPIRY_DELTA_MS,
|
|
376
|
-
GC_INTERVAL_MS,
|
|
377
|
-
KVStore,
|
|
378
|
-
KVStoreField,
|
|
379
|
-
MILLIS_PER_DAY,
|
|
380
|
-
kvStore,
|
|
381
|
-
kvStoreItem
|
|
382
|
-
});
|
|
383
|
-
//# sourceMappingURL=kvStore.js.map
|
package/kvStore.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/kvStore.ts","../src/timeConstants.ts","../src/duration.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. No need to worry about running out of storage.\n * 2. Extremely simple interface to use indexed DBs.\n * 3. Auto-expirations frees you from worrying about data clean-up.\n * 4. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\n\n// Updating the DB name will cause all old entries to be gone.\nconst DEFAULT_DB_NAME = \"KVStore\";\n\n// Updating the version will cause all old entries to be gone.\nconst DEFAULT_DB_VERSION = 1;\n\n// Use a constant store name to keep things simple.\nconst STORE_NAME = \"kvStore\";\n\n/** One day in milliseconds. */\nexport const MILLIS_PER_DAY = 86_400_000;\n\n/** 30 days in ms. */\nexport const DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;\n\n/** Do GC once per day. */\nexport const GC_INTERVAL_MS = MILLIS_PER_DAY;\n\ntype StoredObject<T> = {\n key: string;\n value: T;\n storedMs: number;\n expiryMs: number;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: StoredObject<T>,\n): StoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"key\" in obj) ||\n typeof obj.key !== \"string\" ||\n !(\"value\" in obj) ||\n !(\"storedMs\" in obj) ||\n typeof obj.storedMs !== \"number\" ||\n obj.value === undefined ||\n !(\"expiryMs\" in obj) ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\nexport class KVStoreField<T> {\n public constructor(\n public readonly store: KVStore,\n public readonly key: string,\n ) {}\n\n public get(): Promise<T | undefined> {\n return this.store.get(this.key);\n }\n\n public set(t: T): Promise<T> {\n return this.store.set(this.key, t);\n }\n\n public delete(): Promise<void> {\n return this.store.delete(this.key);\n }\n}\n\n/**\n * You can create multiple KVStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\nexport class KVStore {\n // We'll init the DB only on first use.\n private db: IDBDatabase | undefined;\n\n // Local storage key name for the last GC completed timestamp.\n public readonly gcMsStorageKey: string;\n\n public constructor(\n public readonly dbName: string,\n public readonly dbVersion: number,\n public readonly defaultExpiryDeltaMs: number,\n ) {\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${dbVersion}:${STORE_NAME}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(STORE_NAME, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(db.transaction(STORE_NAME, mode), reject);\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(STORE_NAME);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryDeltaMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: StoredObject<T> = {\n key,\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs),\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n public async getStoredObject<T>(\n key: string,\n ): Promise<StoredObject<T> | undefined> {\n const stored = await this.transact<StoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const obj = await this.getStoredObject<T>(key);\n\n return obj?.value;\n }\n\n public async forEach(\n callback: (\n key: string,\n value: unknown,\n expiryMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj) {\n await callback(String(cursor.key), obj.value, obj.expiryMs);\n } else {\n await callback(String(cursor.key), undefined, 0);\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /** Cannot be a getter because this needs to be async. */\n public async size() {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n public async clear() {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /** Mainly for debugging dumps. */\n public async asMap(): Promise<Map<string, unknown>> {\n const map = new Map<string, unknown>();\n await this.forEach((key, value, expiryMs) => {\n map.set(key, { value, expiryMs });\n });\n return map;\n }\n\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due. */\n public async gc() {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + GC_INTERVAL_MS) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /** Perform garbage-collection immediately without checking. */\n public async gcNow() {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expiryMs: number) => {\n if (value === undefined || Date.now() >= expiryMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Get an independent store item with a locked key and value type. */\n public field<T>(key: string) {\n return new KVStoreField<T>(this, key);\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KVStore(\n DEFAULT_DB_NAME,\n DEFAULT_DB_VERSION,\n DEFAULT_EXPIRY_DELTA_MS,\n);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nclass KvStoreItem<T> {\n public constructor(\n public readonly key: string,\n public readonly defaultExpiryDeltaMs: number,\n public readonly store = kvStore,\n ) {}\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs } = await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<StoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n public async set(\n value: T,\n expiryDeltaMs: number = this.defaultExpiryDeltaMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/**\n * Create a KV store item with a key and a default expiration.\n */\nexport function kvStoreItem<T>(\n key: string,\n defaultExpiration: number | Duration,\n): KvStoreItem<T> {\n const defaultExpiryDeltaMs = durationOrMsToMs(defaultExpiration);\n\n return new KvStoreItem<T>(key, defaultExpiryDeltaMs);\n}\n","/**\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\n","/**\n * Bunch of miscellaneous constants and utility functions related to handling\n * date and time durations.\n *\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file. Weeks have fixed durations, but are excluded because we\n * use days as the max duration supported.\n */\n\nimport {\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\n/**\n * One of: days, hours, minutes, seconds, milliseconds\n */\nexport type DurationType = keyof Duration;\n\n/**\n * Order in which the duration type appears in the duration string.\n */\nexport const DURATION_TYPE_SEQUENCE: DurationType[] = [\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\n/**\n * Follows the same format as Intl.DurationFormat.prototype.format().\n *\n * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\n * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,\n * 7 milliseconds, 8 microseconds, 9 nanoseconds\n * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\n */\nexport type DurationStyle = \"short\" | \"long\" | \"narrow\";\n\nexport type DurationSuffixMap = {\n short: string;\n shorts: string;\n long: string;\n longs: string;\n narrow: string;\n};\n\nexport type DurationSuffixType = keyof DurationSuffixMap;\n\nexport const DURATION_STYLE_SUFFIX_MAP: Record<\n DurationType,\n DurationSuffixMap\n> = {\n days: {\n short: \"day\",\n shorts: \"days\",\n long: \"day\",\n longs: \"days\",\n narrow: \"d\",\n },\n hours: {\n short: \"hr\",\n shorts: \"hrs\",\n long: \"hour\",\n longs: \"hours\",\n narrow: \"h\",\n },\n minutes: {\n short: \"min\",\n shorts: \"mins\",\n long: \"minute\",\n longs: \"minutes\",\n narrow: \"m\",\n },\n seconds: {\n short: \"sec\",\n shorts: \"secs\",\n long: \"second\",\n longs: \"seconds\",\n narrow: \"s\",\n },\n milliseconds: {\n short: \"ms\",\n shorts: \"ms\",\n long: \"millisecond\",\n longs: \"milliseconds\",\n narrow: \"ms\",\n },\n};\n\nfunction getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {\n return style == \"short\" ? \"shorts\" : style === \"long\" ? \"longs\" : style;\n}\n\nfunction getValueAndUnitSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \"\" : \" \";\n}\n\nfunction getDurationTypeSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \" \" : \", \";\n}\n\n/**\n * Convert a milliseconds duration into a Duration object. If the given ms is\n * zero, then return an object with a single field of zero with duration type\n * of durationTypeForZero.\n *\n * @param durationTypeForZero Defaults to 'milliseconds'\n */\nexport function msToDuration(\n ms: number,\n durationTypeForZero?: DurationType,\n): Duration {\n if (ms === 0) {\n durationTypeForZero = durationTypeForZero ?? \"milliseconds\";\n return { [durationTypeForZero]: 0 };\n }\n\n const duration: Duration = {};\n\n for (let i = 0; i < 1; i++) {\n let seconds = Math.floor(ms / MS_PER_SECOND);\n const millis = ms - seconds * MS_PER_SECOND;\n\n if (millis > 0) {\n duration[\"milliseconds\"] = millis;\n }\n\n if (seconds === 0) {\n break;\n }\n\n let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);\n seconds -= minutes * SECONDS_PER_MINUTE;\n\n if (seconds > 0) {\n duration[\"seconds\"] = seconds;\n }\n\n if (minutes === 0) {\n break;\n }\n\n let hours = Math.floor(minutes / MINUTES_PER_HOUR);\n minutes -= hours * MINUTES_PER_HOUR;\n\n if (minutes > 0) {\n duration[\"minutes\"] = minutes;\n }\n\n if (hours === 0) {\n break;\n }\n\n const days = Math.floor(hours / HOURS_PER_DAY);\n hours -= days * HOURS_PER_DAY;\n\n if (hours > 0) {\n duration[\"hours\"] = hours;\n }\n\n if (days > 0) {\n duration[\"days\"] = days;\n }\n }\n\n return duration;\n}\n\n/**\n * Returns the number of milliseconds for the given duration.\n */\nexport function durationToMs(duration: Duration): number {\n const daysMs = (duration.days ?? 0) * MS_PER_DAY;\n const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;\n const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;\n const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;\n const msMs = duration.milliseconds ?? 0;\n\n return daysMs + hoursMs + minsMs + secsMs + msMs;\n}\n\n/**\n * Convenience function to return a duration given an ms or Duration.\n */\nexport function durationOrMsToMs(duration: number | Duration): number {\n return typeof duration === \"number\" ? duration : durationToMs(duration);\n}\n\n/**\n * Format a given Duration object into a string. If the object has no fields,\n * then returns an empty string.\n *\n * @param style Defaults to 'short'\n */\nexport function formatDuration(duration: Duration, style?: DurationStyle) {\n style = style ?? \"short\";\n const stylePlural = getDurationStyleForPlural(style);\n\n const space = getValueAndUnitSeparator(style);\n\n const a: string[] = [];\n\n for (const unit of DURATION_TYPE_SEQUENCE) {\n const value = duration[unit];\n if (value === undefined) continue;\n\n const suffixMap = DURATION_STYLE_SUFFIX_MAP[unit];\n const suffix = value === 1 ? suffixMap[style] : suffixMap[stylePlural];\n a.push(value + space + suffix);\n }\n\n const separator = getDurationTypeSeparator(style);\n return a.join(separator);\n}\n\n/**\n * Convert a millisecond duration into a human-readable duration string.\n *\n * @param options.durationTypeForZero - Defaults to 'milliseconds'\n * @param options.style - Defaults to 'short'\n */\nexport function readableDuration(\n ms: number,\n options?: { durationTypeForZero?: DurationType; style?: DurationStyle },\n): string {\n const duration = msToDuration(ms, options?.durationTypeForZero);\n\n return formatDuration(duration, options?.style);\n}\n\n/** A shortened duration string useful for logging timings. */\nexport function elapsed(ms: number): string {\n // Use long format for 1 minute or over.\n if (ms > MS_PER_MINUTE) {\n return readableDuration(ms);\n }\n\n // Use seconds format for over 100ms.\n if (ms > 100) {\n return `${(ms / 1000).toFixed(3)}s`;\n }\n\n // Use milliseconds format.\n return ms + \"ms\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,aAAa;;;ACkLnB,SAAS,aAAa,UAA4B;AA1LzD;AA2LE,QAAM,WAAU,cAAS,SAAT,YAAiB,KAAK;AACtC,QAAM,YAAW,cAAS,UAAT,YAAkB,KAAK;AACxC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,QAAO,cAAS,iBAAT,YAAyB;AAEtC,SAAO,SAAS,UAAU,SAAS,SAAS;AAC9C;AAKO,SAAS,iBAAiB,UAAqC;AACpE,SAAO,OAAO,aAAa,WAAW,WAAW,aAAa,QAAQ;AACxE;;;AFzLA,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,aAAa;AAGZ,IAAM,iBAAiB;AAGvB,IAAM,0BAA0B,iBAAiB;AAGjD,IAAM,iBAAiB;AAa9B,SAAS,qBACP,KAC6B;AAC7B,MACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,SAAS,QACX,OAAO,IAAI,QAAQ,YACnB,EAAE,WAAW,QACb,EAAE,cAAc,QAChB,OAAO,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]}
|
package/localStorageCache.d.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { Duration } from "./duration";
|
|
2
|
-
export type StoredItem<T> = {
|
|
3
|
-
value: T;
|
|
4
|
-
storedMs: number;
|
|
5
|
-
expiryMs: number;
|
|
6
|
-
};
|
|
7
|
-
/**
|
|
8
|
-
* Simple local storage cache with support for auto-expiration.
|
|
9
|
-
* Note that this works in the browser context only because nodejs does not
|
|
10
|
-
* have local storage.
|
|
11
|
-
*
|
|
12
|
-
* Create a cache item accessor object with auto-expiration. The value will
|
|
13
|
-
* always be stored as a string by applying JSON.stringify(), and will be
|
|
14
|
-
* returned in the same object type by applying JSON.parse().
|
|
15
|
-
*
|
|
16
|
-
* In order to provide proper type-checking, please always specify the T
|
|
17
|
-
* type parameter. E.g. const item = storeItem<string>("name", 10_000);
|
|
18
|
-
*
|
|
19
|
-
* @param key The store key in local storage.
|
|
20
|
-
* @param expires Either a number in milliseconds, or a Duration object
|
|
21
|
-
* @param logError Log an error if we found an invalid object in the store.
|
|
22
|
-
* The invalid object is usually a string that cannot be parsed as JSON.
|
|
23
|
-
* @param defaultValue Specify a default value to use for the object. Defaults
|
|
24
|
-
* to undefined.
|
|
25
|
-
*/
|
|
26
|
-
export declare function storeItem<T>(key: string, expires: number | Duration, logError?: boolean, defaultValue?: T): CacheItem<T>;
|
|
27
|
-
declare class CacheItem<T> {
|
|
28
|
-
readonly key: string;
|
|
29
|
-
readonly expireDeltaMs: number;
|
|
30
|
-
readonly logError: boolean;
|
|
31
|
-
readonly defaultValue: T | undefined;
|
|
32
|
-
/**
|
|
33
|
-
* Create a cache item accessor object with auto-expiration.
|
|
34
|
-
*/
|
|
35
|
-
constructor(key: string, expireDeltaMs: number, logError: boolean, defaultValue: T | undefined);
|
|
36
|
-
/**
|
|
37
|
-
* Set the value of this item with auto-expiration.
|
|
38
|
-
*/
|
|
39
|
-
set(value: T, expiryDelta?: number | Duration): void;
|
|
40
|
-
/**
|
|
41
|
-
* Example usage:
|
|
42
|
-
*
|
|
43
|
-
* const { value, storedMs, expiryMs } = await myItem.getStoredItem();
|
|
44
|
-
*/
|
|
45
|
-
getStoredItem(): StoredItem<T> | undefined;
|
|
46
|
-
/**
|
|
47
|
-
* Get the value of this item, or undefined if value is not set or expired.
|
|
48
|
-
*/
|
|
49
|
-
get(): T | undefined;
|
|
50
|
-
/**
|
|
51
|
-
* Remove the value of this item.
|
|
52
|
-
*/
|
|
53
|
-
remove(): void;
|
|
54
|
-
}
|
|
55
|
-
export {};
|
package/localStorageCache.js
DELETED
|
@@ -1,121 +0,0 @@
|
|
|
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/localStorageCache.ts
|
|
21
|
-
var localStorageCache_exports = {};
|
|
22
|
-
__export(localStorageCache_exports, {
|
|
23
|
-
storeItem: () => storeItem
|
|
24
|
-
});
|
|
25
|
-
module.exports = __toCommonJS(localStorageCache_exports);
|
|
26
|
-
|
|
27
|
-
// src/timeConstants.ts
|
|
28
|
-
var MS_PER_SECOND = 1e3;
|
|
29
|
-
var MS_PER_MINUTE = 6e4;
|
|
30
|
-
var MS_PER_HOUR = 36e5;
|
|
31
|
-
var MS_PER_DAY = 864e5;
|
|
32
|
-
|
|
33
|
-
// src/duration.ts
|
|
34
|
-
function durationToMs(duration) {
|
|
35
|
-
var _a, _b, _c, _d, _e;
|
|
36
|
-
const daysMs = ((_a = duration.days) != null ? _a : 0) * MS_PER_DAY;
|
|
37
|
-
const hoursMs = ((_b = duration.hours) != null ? _b : 0) * MS_PER_HOUR;
|
|
38
|
-
const minsMs = ((_c = duration.minutes) != null ? _c : 0) * MS_PER_MINUTE;
|
|
39
|
-
const secsMs = ((_d = duration.seconds) != null ? _d : 0) * MS_PER_SECOND;
|
|
40
|
-
const msMs = (_e = duration.milliseconds) != null ? _e : 0;
|
|
41
|
-
return daysMs + hoursMs + minsMs + secsMs + msMs;
|
|
42
|
-
}
|
|
43
|
-
function durationOrMsToMs(duration) {
|
|
44
|
-
return typeof duration === "number" ? duration : durationToMs(duration);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// src/localStorageCache.ts
|
|
48
|
-
function storeItem(key, expires, logError = true, defaultValue) {
|
|
49
|
-
const expireDeltaMs = durationOrMsToMs(expires);
|
|
50
|
-
return new CacheItem(key, expireDeltaMs, logError, defaultValue);
|
|
51
|
-
}
|
|
52
|
-
var CacheItem = class {
|
|
53
|
-
/**
|
|
54
|
-
* Create a cache item accessor object with auto-expiration.
|
|
55
|
-
*/
|
|
56
|
-
constructor(key, expireDeltaMs, logError, defaultValue) {
|
|
57
|
-
this.key = key;
|
|
58
|
-
this.expireDeltaMs = expireDeltaMs;
|
|
59
|
-
this.logError = logError;
|
|
60
|
-
this.defaultValue = defaultValue;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Set the value of this item with auto-expiration.
|
|
64
|
-
*/
|
|
65
|
-
set(value, expiryDelta = this.expireDeltaMs) {
|
|
66
|
-
const nowMs = Date.now();
|
|
67
|
-
const toStore = {
|
|
68
|
-
value,
|
|
69
|
-
storedMs: nowMs,
|
|
70
|
-
expiryMs: nowMs + durationOrMsToMs(expiryDelta)
|
|
71
|
-
};
|
|
72
|
-
const valueStr = JSON.stringify(toStore);
|
|
73
|
-
globalThis.localStorage.setItem(this.key, valueStr);
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Example usage:
|
|
77
|
-
*
|
|
78
|
-
* const { value, storedMs, expiryMs } = await myItem.getStoredItem();
|
|
79
|
-
*/
|
|
80
|
-
getStoredItem() {
|
|
81
|
-
const jsonStr = globalThis.localStorage.getItem(this.key);
|
|
82
|
-
if (!jsonStr) {
|
|
83
|
-
return void 0;
|
|
84
|
-
}
|
|
85
|
-
try {
|
|
86
|
-
const obj = JSON.parse(jsonStr);
|
|
87
|
-
if (!obj || typeof obj !== "object" || !("value" in obj) || !("storedMs" in obj) || typeof obj.storedMs !== "number" || !("expiryMs" in obj) || typeof obj.expiryMs !== "number" || Date.now() >= obj.expiryMs) {
|
|
88
|
-
this.remove();
|
|
89
|
-
return void 0;
|
|
90
|
-
}
|
|
91
|
-
return obj;
|
|
92
|
-
} catch (e) {
|
|
93
|
-
if (this.logError) {
|
|
94
|
-
console.error(
|
|
95
|
-
`Found invalid storage value: ${this.key}=${jsonStr}:`,
|
|
96
|
-
e
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
this.remove();
|
|
100
|
-
return void 0;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Get the value of this item, or undefined if value is not set or expired.
|
|
105
|
-
*/
|
|
106
|
-
get() {
|
|
107
|
-
const stored = this.getStoredItem();
|
|
108
|
-
return stored !== void 0 ? stored.value : this.defaultValue;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Remove the value of this item.
|
|
112
|
-
*/
|
|
113
|
-
remove() {
|
|
114
|
-
globalThis.localStorage.removeItem(this.key);
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
118
|
-
0 && (module.exports = {
|
|
119
|
-
storeItem
|
|
120
|
-
});
|
|
121
|
-
//# sourceMappingURL=localStorageCache.js.map
|
package/localStorageCache.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/localStorageCache.ts","../src/timeConstants.ts","../src/duration.ts"],"sourcesContent":["import { Duration, durationOrMsToMs } from \"./duration\";\n\nexport type StoredItem<T> = { value: T; storedMs: number; expiryMs: number };\n\n/**\n * Simple local storage cache with support for auto-expiration.\n * Note that this works in the browser context only because nodejs does not\n * have local storage.\n *\n * Create a cache item accessor object with auto-expiration. The value will\n * always be stored as a string by applying JSON.stringify(), and will be\n * returned in the same object type by applying JSON.parse().\n *\n * In order to provide proper type-checking, please always specify the T\n * type parameter. E.g. const item = storeItem<string>(\"name\", 10_000);\n *\n * @param key The store key in local storage.\n * @param expires Either a number in milliseconds, or a Duration object\n * @param logError Log an error if we found an invalid object in the store.\n * The invalid object is usually a string that cannot be parsed as JSON.\n * @param defaultValue Specify a default value to use for the object. Defaults\n * to undefined.\n */\nexport function storeItem<T>(\n key: string,\n expires: number | Duration,\n logError = true,\n defaultValue?: T,\n) {\n const expireDeltaMs = durationOrMsToMs(expires);\n\n return new CacheItem<T>(key, expireDeltaMs, logError, defaultValue);\n}\n\nclass CacheItem<T> {\n /**\n * Create a cache item accessor object with auto-expiration.\n */\n public constructor(\n public readonly key: string,\n public readonly expireDeltaMs: number,\n public readonly logError: boolean,\n public readonly defaultValue: T | undefined,\n ) {}\n\n /**\n * Set the value of this item with auto-expiration.\n */\n public set(\n value: T,\n expiryDelta: number | Duration = this.expireDeltaMs,\n ): void {\n const nowMs = Date.now();\n const toStore: StoredItem<T> = {\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDelta),\n };\n const valueStr = JSON.stringify(toStore);\n\n globalThis.localStorage.setItem(this.key, valueStr);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs } = await myItem.getStoredItem();\n */\n public getStoredItem(): StoredItem<T> | undefined {\n const jsonStr = globalThis.localStorage.getItem(this.key);\n\n if (!jsonStr) {\n return undefined;\n }\n\n try {\n const obj: StoredItem<T> | undefined = JSON.parse(jsonStr);\n\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"value\" in obj) ||\n !(\"storedMs\" in obj) ||\n typeof obj.storedMs !== \"number\" ||\n !(\"expiryMs\" in obj) ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n this.remove();\n return undefined;\n }\n\n return obj;\n } catch (e) {\n if (this.logError) {\n console.error(\n `Found invalid storage value: ${this.key}=${jsonStr}:`,\n e,\n );\n }\n this.remove();\n return undefined;\n }\n }\n\n /**\n * Get the value of this item, or undefined if value is not set or expired.\n */\n public get(): T | undefined {\n const stored = this.getStoredItem();\n\n return stored !== undefined ? stored.value : this.defaultValue;\n }\n\n /**\n * Remove the value of this item.\n */\n public remove(): void {\n globalThis.localStorage.removeItem(this.key);\n }\n}\n","/**\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\n","/**\n * Bunch of miscellaneous constants and utility functions related to handling\n * date and time durations.\n *\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file. Weeks have fixed durations, but are excluded because we\n * use days as the max duration supported.\n */\n\nimport {\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\n/**\n * One of: days, hours, minutes, seconds, milliseconds\n */\nexport type DurationType = keyof Duration;\n\n/**\n * Order in which the duration type appears in the duration string.\n */\nexport const DURATION_TYPE_SEQUENCE: DurationType[] = [\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\n/**\n * Follows the same format as Intl.DurationFormat.prototype.format().\n *\n * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\n * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,\n * 7 milliseconds, 8 microseconds, 9 nanoseconds\n * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\n */\nexport type DurationStyle = \"short\" | \"long\" | \"narrow\";\n\nexport type DurationSuffixMap = {\n short: string;\n shorts: string;\n long: string;\n longs: string;\n narrow: string;\n};\n\nexport type DurationSuffixType = keyof DurationSuffixMap;\n\nexport const DURATION_STYLE_SUFFIX_MAP: Record<\n DurationType,\n DurationSuffixMap\n> = {\n days: {\n short: \"day\",\n shorts: \"days\",\n long: \"day\",\n longs: \"days\",\n narrow: \"d\",\n },\n hours: {\n short: \"hr\",\n shorts: \"hrs\",\n long: \"hour\",\n longs: \"hours\",\n narrow: \"h\",\n },\n minutes: {\n short: \"min\",\n shorts: \"mins\",\n long: \"minute\",\n longs: \"minutes\",\n narrow: \"m\",\n },\n seconds: {\n short: \"sec\",\n shorts: \"secs\",\n long: \"second\",\n longs: \"seconds\",\n narrow: \"s\",\n },\n milliseconds: {\n short: \"ms\",\n shorts: \"ms\",\n long: \"millisecond\",\n longs: \"milliseconds\",\n narrow: \"ms\",\n },\n};\n\nfunction getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {\n return style == \"short\" ? \"shorts\" : style === \"long\" ? \"longs\" : style;\n}\n\nfunction getValueAndUnitSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \"\" : \" \";\n}\n\nfunction getDurationTypeSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \" \" : \", \";\n}\n\n/**\n * Convert a milliseconds duration into a Duration object. If the given ms is\n * zero, then return an object with a single field of zero with duration type\n * of durationTypeForZero.\n *\n * @param durationTypeForZero Defaults to 'milliseconds'\n */\nexport function msToDuration(\n ms: number,\n durationTypeForZero?: DurationType,\n): Duration {\n if (ms === 0) {\n durationTypeForZero = durationTypeForZero ?? \"milliseconds\";\n return { [durationTypeForZero]: 0 };\n }\n\n const duration: Duration = {};\n\n for (let i = 0; i < 1; i++) {\n let seconds = Math.floor(ms / MS_PER_SECOND);\n const millis = ms - seconds * MS_PER_SECOND;\n\n if (millis > 0) {\n duration[\"milliseconds\"] = millis;\n }\n\n if (seconds === 0) {\n break;\n }\n\n let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);\n seconds -= minutes * SECONDS_PER_MINUTE;\n\n if (seconds > 0) {\n duration[\"seconds\"] = seconds;\n }\n\n if (minutes === 0) {\n break;\n }\n\n let hours = Math.floor(minutes / MINUTES_PER_HOUR);\n minutes -= hours * MINUTES_PER_HOUR;\n\n if (minutes > 0) {\n duration[\"minutes\"] = minutes;\n }\n\n if (hours === 0) {\n break;\n }\n\n const days = Math.floor(hours / HOURS_PER_DAY);\n hours -= days * HOURS_PER_DAY;\n\n if (hours > 0) {\n duration[\"hours\"] = hours;\n }\n\n if (days > 0) {\n duration[\"days\"] = days;\n }\n }\n\n return duration;\n}\n\n/**\n * Returns the number of milliseconds for the given duration.\n */\nexport function durationToMs(duration: Duration): number {\n const daysMs = (duration.days ?? 0) * MS_PER_DAY;\n const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;\n const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;\n const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;\n const msMs = duration.milliseconds ?? 0;\n\n return daysMs + hoursMs + minsMs + secsMs + msMs;\n}\n\n/**\n * Convenience function to return a duration given an ms or Duration.\n */\nexport function durationOrMsToMs(duration: number | Duration): number {\n return typeof duration === \"number\" ? duration : durationToMs(duration);\n}\n\n/**\n * Format a given Duration object into a string. If the object has no fields,\n * then returns an empty string.\n *\n * @param style Defaults to 'short'\n */\nexport function formatDuration(duration: Duration, style?: DurationStyle) {\n style = style ?? \"short\";\n const stylePlural = getDurationStyleForPlural(style);\n\n const space = getValueAndUnitSeparator(style);\n\n const a: string[] = [];\n\n for (const unit of DURATION_TYPE_SEQUENCE) {\n const value = duration[unit];\n if (value === undefined) continue;\n\n const suffixMap = DURATION_STYLE_SUFFIX_MAP[unit];\n const suffix = value === 1 ? suffixMap[style] : suffixMap[stylePlural];\n a.push(value + space + suffix);\n }\n\n const separator = getDurationTypeSeparator(style);\n return a.join(separator);\n}\n\n/**\n * Convert a millisecond duration into a human-readable duration string.\n *\n * @param options.durationTypeForZero - Defaults to 'milliseconds'\n * @param options.style - Defaults to 'short'\n */\nexport function readableDuration(\n ms: number,\n options?: { durationTypeForZero?: DurationType; style?: DurationStyle },\n): string {\n const duration = msToDuration(ms, options?.durationTypeForZero);\n\n return formatDuration(duration, options?.style);\n}\n\n/** A shortened duration string useful for logging timings. */\nexport function elapsed(ms: number): string {\n // Use long format for 1 minute or over.\n if (ms > MS_PER_MINUTE) {\n return readableDuration(ms);\n }\n\n // Use seconds format for over 100ms.\n if (ms > 100) {\n return `${(ms / 1000).toFixed(3)}s`;\n }\n\n // Use milliseconds format.\n return ms + \"ms\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAA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