@choksheak/ts-utils 0.3.1 → 0.3.3
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/asNumber.cjs +39 -0
- package/asNumber.d.mts +6 -0
- package/asNumber.d.ts +6 -0
- package/asNumber.min.cjs +2 -0
- package/asNumber.min.cjs.map +1 -0
- package/asNumber.min.mjs +2 -0
- package/asNumber.min.mjs.map +1 -0
- package/asNumber.mjs +14 -0
- package/average.cjs +15 -7
- package/average.min.cjs +1 -1
- package/average.min.cjs.map +1 -1
- package/average.min.mjs +1 -1
- package/average.min.mjs.map +1 -1
- package/average.mjs +15 -7
- package/isPromise.cjs +40 -0
- package/isPromise.d.mts +19 -0
- package/isPromise.d.ts +19 -0
- package/isPromise.min.cjs +2 -0
- package/isPromise.min.cjs.map +1 -0
- package/isPromise.min.mjs +2 -0
- package/isPromise.min.mjs.map +1 -0
- package/isPromise.mjs +14 -0
- package/kvStore.cjs +5 -4
- package/kvStore.min.cjs +1 -1
- package/kvStore.min.cjs.map +1 -1
- package/kvStore.min.mjs +1 -1
- package/kvStore.min.mjs.map +1 -1
- package/kvStore.mjs +5 -4
- package/mean.cjs +53 -0
- package/mean.d.mts +7 -0
- package/mean.d.ts +7 -0
- package/mean.min.cjs +2 -0
- package/mean.min.cjs.map +1 -0
- package/mean.min.mjs +2 -0
- package/mean.min.mjs.map +1 -0
- package/mean.mjs +26 -0
- package/median.cjs +56 -0
- package/median.d.mts +7 -0
- package/median.d.ts +7 -0
- package/median.min.cjs +2 -0
- package/median.min.cjs.map +1 -0
- package/median.min.mjs +2 -0
- package/median.min.mjs.map +1 -0
- package/median.mjs +29 -0
- package/package.json +65 -1
- package/round.cjs +4 -1
- package/round.d.mts +2 -1
- package/round.d.ts +2 -1
- package/round.min.cjs +1 -1
- package/round.min.cjs.map +1 -1
- package/round.min.mjs +1 -1
- package/round.min.mjs.map +1 -1
- package/round.mjs +4 -1
- package/storageAdapter.d.mts +5 -2
- package/storageAdapter.d.ts +5 -2
- package/storageAdapter.min.cjs +1 -1
- package/storageAdapter.min.cjs.map +1 -1
- package/sum.cjs +17 -7
- package/sum.d.mts +3 -3
- package/sum.d.ts +3 -3
- package/sum.min.cjs +1 -1
- package/sum.min.cjs.map +1 -1
- package/sum.min.mjs +1 -1
- package/sum.min.mjs.map +1 -1
- package/sum.mjs +15 -7
package/asNumber.cjs
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
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/asNumber.ts
|
|
21
|
+
var asNumber_exports = {};
|
|
22
|
+
__export(asNumber_exports, {
|
|
23
|
+
asNumber: () => asNumber
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(asNumber_exports);
|
|
26
|
+
function asNumber(u) {
|
|
27
|
+
if (typeof u === "number" && isFinite(u)) {
|
|
28
|
+
return u;
|
|
29
|
+
}
|
|
30
|
+
const n = Number(u);
|
|
31
|
+
if (typeof n === "number" && isFinite(n)) {
|
|
32
|
+
return n;
|
|
33
|
+
}
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
37
|
+
0 && (module.exports = {
|
|
38
|
+
asNumber
|
|
39
|
+
});
|
package/asNumber.d.mts
ADDED
package/asNumber.d.ts
ADDED
package/asNumber.min.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var i=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var m=(e,n)=>{for(var t in n)i(e,t,{get:n[t],enumerable:!0})},s=(e,n,t,u)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of b(n))!f.call(e,r)&&r!==t&&i(e,r,{get:()=>n[r],enumerable:!(u=o(n,r))||u.enumerable});return e};var p=e=>s(i({},"__esModule",{value:!0}),e);var y={};m(y,{asNumber:()=>c});module.exports=p(y);function c(e){if(typeof e=="number"&&isFinite(e))return e;let n=Number(e);return typeof n=="number"&&isFinite(n)?n:0}0&&(module.exports={asNumber});
|
|
2
|
+
//# sourceMappingURL=asNumber.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/asNumber.ts"],"sourcesContent":["/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,cAAAE,IAAA,eAAAC,EAAAH,GAGO,SAASE,EAASE,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAM,EAAI,OAAOA,CAAC,EAClB,OAAI,OAAO,GAAM,UAAY,SAAS,CAAC,EAC9B,EAKF,CACT","names":["asNumber_exports","__export","asNumber","__toCommonJS","u"]}
|
package/asNumber.min.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/asNumber.ts"],"sourcesContent":["/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n"],"mappings":"AAGO,SAASA,EAASC,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAMC,EAAI,OAAOD,CAAC,EAClB,OAAI,OAAOC,GAAM,UAAY,SAASA,CAAC,EAC9BA,EAKF,CACT","names":["asNumber","u","n"]}
|
package/asNumber.mjs
ADDED
package/average.cjs
CHANGED
|
@@ -24,15 +24,23 @@ __export(average_exports, {
|
|
|
24
24
|
});
|
|
25
25
|
module.exports = __toCommonJS(average_exports);
|
|
26
26
|
|
|
27
|
+
// src/asNumber.ts
|
|
28
|
+
function asNumber(u) {
|
|
29
|
+
if (typeof u === "number" && isFinite(u)) {
|
|
30
|
+
return u;
|
|
31
|
+
}
|
|
32
|
+
const n = Number(u);
|
|
33
|
+
if (typeof n === "number" && isFinite(n)) {
|
|
34
|
+
return n;
|
|
35
|
+
}
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
27
39
|
// src/sum.ts
|
|
28
40
|
function sum(numbers) {
|
|
29
|
-
return numbers.reduce(
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return accumulated + value;
|
|
33
|
-
},
|
|
34
|
-
0
|
|
35
|
-
);
|
|
41
|
+
return numbers.reduce((accumulated, current) => {
|
|
42
|
+
return accumulated + asNumber(current);
|
|
43
|
+
}, 0);
|
|
36
44
|
}
|
|
37
45
|
|
|
38
46
|
// src/average.ts
|
package/average.min.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var u=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var a=(n,r)=>{for(var e in r)u(n,e,{get:r[e],enumerable:!0})},c=(n,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of b(r))!p.call(n,t)&&t!==e&&u(n,t,{get:()=>r[t],enumerable:!(o=f(r,t))||o.enumerable});return n};var l=n=>c(u({},"__esModule",{value:!0}),n);var d={};a(d,{average:()=>s});module.exports=l(d);function i(n){if(typeof n=="number"&&isFinite(n))return n;let r=Number(n);return typeof r=="number"&&isFinite(r)?r:0}function m(n){return n.reduce((r,e)=>r+i(e),0)}function s(n){return n.length===0?0:m(n)/n.length}0&&(module.exports={average});
|
|
2
2
|
//# sourceMappingURL=average.min.cjs.map
|
package/average.min.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/average.ts","../src/sum.ts"],"sourcesContent":["import { sum } from \"./sum\";\n\n/**\n * Average all the numbers together in the given array. Treats null, undefined\n * and NaN as zero.\n */\nexport function average(numbers: (number | null | undefined)[]): number {\n if (numbers.length === 0) return 0;\n\n const total = sum(numbers);\n\n return total / numbers.length;\n}\n","/**\n *
|
|
1
|
+
{"version":3,"sources":["../src/average.ts","../src/asNumber.ts","../src/sum.ts"],"sourcesContent":["import { sum } from \"./sum\";\n\n/**\n * Average all the numbers together in the given array. Treats null, undefined\n * and NaN as zero.\n */\nexport function average(numbers: (number | null | undefined)[]): number {\n if (numbers.length === 0) return 0;\n\n const total = sum(numbers);\n\n return total / numbers.length;\n}\n","/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n","import { asNumber } from \"./asNumber\";\n\n/**\n * Add all the numbers together in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function sum(numbers: unknown[]): number {\n return numbers.reduce((accumulated: number, current: unknown) => {\n return accumulated + asNumber(current);\n }, 0);\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCGO,SAASI,EAASC,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAMC,EAAI,OAAOD,CAAC,EAClB,OAAI,OAAOC,GAAM,UAAY,SAASA,CAAC,EAC9BA,EAKF,CACT,CCZO,SAASC,EAAIC,EAA4B,CAC9C,OAAOA,EAAQ,OAAO,CAACC,EAAqBC,IACnCD,EAAcE,EAASD,CAAO,EACpC,CAAC,CACN,CFJO,SAASE,EAAQC,EAAgD,CACtE,OAAIA,EAAQ,SAAW,EAAU,EAEnBC,EAAID,CAAO,EAEVA,EAAQ,MACzB","names":["average_exports","__export","average","__toCommonJS","asNumber","u","n","sum","numbers","accumulated","current","asNumber","average","numbers","sum"]}
|
package/average.min.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function e(n){if(typeof n=="number"&&isFinite(n))return n;let r=Number(n);return typeof r=="number"&&isFinite(r)?r:0}function t(n){return n.reduce((r,u)=>r+e(u),0)}function b(n){return n.length===0?0:t(n)/n.length}export{b as average};
|
|
2
2
|
//# sourceMappingURL=average.min.mjs.map
|
package/average.min.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sum.ts","../src/average.ts"],"sourcesContent":["/**\n *
|
|
1
|
+
{"version":3,"sources":["../src/asNumber.ts","../src/sum.ts","../src/average.ts"],"sourcesContent":["/**\n * Coerce `u` into a number if possible, otherwise just return 0.\n */\nexport function asNumber(u: unknown): number {\n // No transformation needed if u is already a number.\n if (typeof u === \"number\" && isFinite(u)) {\n return u;\n }\n\n // Try to make into a number if possible.\n const n = Number(u);\n if (typeof n === \"number\" && isFinite(n)) {\n return n;\n }\n\n // Return 0 for everything else. This is usually ok if want to just ignore\n // all other noise.\n return 0;\n}\n","import { asNumber } from \"./asNumber\";\n\n/**\n * Add all the numbers together in the given array.\n * Non-numbers will be coerced into numbers if possible.\n */\nexport function sum(numbers: unknown[]): number {\n return numbers.reduce((accumulated: number, current: unknown) => {\n return accumulated + asNumber(current);\n }, 0);\n}\n","import { sum } from \"./sum\";\n\n/**\n * Average all the numbers together in the given array. Treats null, undefined\n * and NaN as zero.\n */\nexport function average(numbers: (number | null | undefined)[]): number {\n if (numbers.length === 0) return 0;\n\n const total = sum(numbers);\n\n return total / numbers.length;\n}\n"],"mappings":"AAGO,SAASA,EAASC,EAAoB,CAE3C,GAAI,OAAOA,GAAM,UAAY,SAASA,CAAC,EACrC,OAAOA,EAIT,IAAMC,EAAI,OAAOD,CAAC,EAClB,OAAI,OAAOC,GAAM,UAAY,SAASA,CAAC,EAC9BA,EAKF,CACT,CCZO,SAASC,EAAIC,EAA4B,CAC9C,OAAOA,EAAQ,OAAO,CAACC,EAAqBC,IACnCD,EAAcE,EAASD,CAAO,EACpC,CAAC,CACN,CCJO,SAASE,EAAQC,EAAgD,CACtE,OAAIA,EAAQ,SAAW,EAAU,EAEnBC,EAAID,CAAO,EAEVA,EAAQ,MACzB","names":["asNumber","u","n","sum","numbers","accumulated","current","asNumber","average","numbers","sum"]}
|
package/average.mjs
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
|
+
// src/asNumber.ts
|
|
2
|
+
function asNumber(u) {
|
|
3
|
+
if (typeof u === "number" && isFinite(u)) {
|
|
4
|
+
return u;
|
|
5
|
+
}
|
|
6
|
+
const n = Number(u);
|
|
7
|
+
if (typeof n === "number" && isFinite(n)) {
|
|
8
|
+
return n;
|
|
9
|
+
}
|
|
10
|
+
return 0;
|
|
11
|
+
}
|
|
12
|
+
|
|
1
13
|
// src/sum.ts
|
|
2
14
|
function sum(numbers) {
|
|
3
|
-
return numbers.reduce(
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
return accumulated + value;
|
|
7
|
-
},
|
|
8
|
-
0
|
|
9
|
-
);
|
|
15
|
+
return numbers.reduce((accumulated, current) => {
|
|
16
|
+
return accumulated + asNumber(current);
|
|
17
|
+
}, 0);
|
|
10
18
|
}
|
|
11
19
|
|
|
12
20
|
// src/average.ts
|
package/isPromise.cjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
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/isPromise.ts
|
|
21
|
+
var isPromise_exports = {};
|
|
22
|
+
__export(isPromise_exports, {
|
|
23
|
+
isNativePromise: () => isNativePromise,
|
|
24
|
+
isPromise: () => isPromise
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(isPromise_exports);
|
|
27
|
+
function isPromise(obj) {
|
|
28
|
+
if (!obj || typeof obj !== "object" && typeof obj !== "function") {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
return "then" in obj && typeof obj.then === "function";
|
|
32
|
+
}
|
|
33
|
+
function isNativePromise(obj) {
|
|
34
|
+
return obj instanceof Promise;
|
|
35
|
+
}
|
|
36
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
37
|
+
0 && (module.exports = {
|
|
38
|
+
isNativePromise,
|
|
39
|
+
isPromise
|
|
40
|
+
});
|
package/isPromise.d.mts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A type guard to check if an object is a Promise (or a "thenable"). It checks
|
|
3
|
+
* if the object is not null, is an object, and has a callable .then method.
|
|
4
|
+
*
|
|
5
|
+
* Note that if the Promise expects a certain type like `Promise<T>`, there is
|
|
6
|
+
* no way to validate the type of T unless we resolve the promise. This function
|
|
7
|
+
* does not attempt to typecheck for T in any way.
|
|
8
|
+
*/
|
|
9
|
+
declare function isPromise(obj: unknown): obj is Promise<unknown>;
|
|
10
|
+
/**
|
|
11
|
+
* A type guard to check if an object is a native Promise.
|
|
12
|
+
*
|
|
13
|
+
* Note that if the Promise expects a certain type like `Promise<T>`, there is
|
|
14
|
+
* no way to validate the type of T unless we resolve the promise. This function
|
|
15
|
+
* does not attempt to typecheck for T in any way.
|
|
16
|
+
*/
|
|
17
|
+
declare function isNativePromise(obj: unknown): obj is Promise<unknown>;
|
|
18
|
+
|
|
19
|
+
export { isNativePromise, isPromise };
|
package/isPromise.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A type guard to check if an object is a Promise (or a "thenable"). It checks
|
|
3
|
+
* if the object is not null, is an object, and has a callable .then method.
|
|
4
|
+
*
|
|
5
|
+
* Note that if the Promise expects a certain type like `Promise<T>`, there is
|
|
6
|
+
* no way to validate the type of T unless we resolve the promise. This function
|
|
7
|
+
* does not attempt to typecheck for T in any way.
|
|
8
|
+
*/
|
|
9
|
+
declare function isPromise(obj: unknown): obj is Promise<unknown>;
|
|
10
|
+
/**
|
|
11
|
+
* A type guard to check if an object is a native Promise.
|
|
12
|
+
*
|
|
13
|
+
* Note that if the Promise expects a certain type like `Promise<T>`, there is
|
|
14
|
+
* no way to validate the type of T unless we resolve the promise. This function
|
|
15
|
+
* does not attempt to typecheck for T in any way.
|
|
16
|
+
*/
|
|
17
|
+
declare function isNativePromise(obj: unknown): obj is Promise<unknown>;
|
|
18
|
+
|
|
19
|
+
export { isNativePromise, isPromise };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var t=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var c=(n,e)=>{for(var i in e)t(n,i,{get:e[i],enumerable:!0})},m=(n,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of u(e))!f.call(n,o)&&o!==i&&t(n,o,{get:()=>e[o],enumerable:!(r=s(e,o))||r.enumerable});return n};var p=n=>m(t({},"__esModule",{value:!0}),n);var w={};c(w,{isNativePromise:()=>k,isPromise:()=>P});module.exports=p(w);function P(n){return!n||typeof n!="object"&&typeof n!="function"?!1:"then"in n&&typeof n.then=="function"}function k(n){return n instanceof Promise}0&&(module.exports={isNativePromise,isPromise});
|
|
2
|
+
//# sourceMappingURL=isPromise.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/isPromise.ts"],"sourcesContent":["/**\n * A type guard to check if an object is a Promise (or a \"thenable\"). It checks\n * if the object is not null, is an object, and has a callable .then method.\n *\n * Note that if the Promise expects a certain type like `Promise<T>`, there is\n * no way to validate the type of T unless we resolve the promise. This function\n * does not attempt to typecheck for T in any way.\n */\nexport function isPromise(obj: unknown): obj is Promise<unknown> {\n // Check if the object is defined and not null.\n if (!obj || (typeof obj !== \"object\" && typeof obj !== \"function\")) {\n return false;\n }\n\n // Check if the .then property is a function (callable).\n return \"then\" in obj && typeof obj.then === \"function\";\n}\n\n/**\n * A type guard to check if an object is a native Promise.\n *\n * Note that if the Promise expects a certain type like `Promise<T>`, there is\n * no way to validate the type of T unless we resolve the promise. This function\n * does not attempt to typecheck for T in any way.\n */\nexport function isNativePromise(obj: unknown): obj is Promise<unknown> {\n return obj instanceof Promise;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,cAAAC,IAAA,eAAAC,EAAAJ,GAQO,SAASG,EAAUE,EAAuC,CAE/D,MAAI,CAACA,GAAQ,OAAOA,GAAQ,UAAY,OAAOA,GAAQ,WAC9C,GAIF,SAAUA,GAAO,OAAOA,EAAI,MAAS,UAC9C,CASO,SAASH,EAAgBG,EAAuC,CACrE,OAAOA,aAAe,OACxB","names":["isPromise_exports","__export","isNativePromise","isPromise","__toCommonJS","obj"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/isPromise.ts"],"sourcesContent":["/**\n * A type guard to check if an object is a Promise (or a \"thenable\"). It checks\n * if the object is not null, is an object, and has a callable .then method.\n *\n * Note that if the Promise expects a certain type like `Promise<T>`, there is\n * no way to validate the type of T unless we resolve the promise. This function\n * does not attempt to typecheck for T in any way.\n */\nexport function isPromise(obj: unknown): obj is Promise<unknown> {\n // Check if the object is defined and not null.\n if (!obj || (typeof obj !== \"object\" && typeof obj !== \"function\")) {\n return false;\n }\n\n // Check if the .then property is a function (callable).\n return \"then\" in obj && typeof obj.then === \"function\";\n}\n\n/**\n * A type guard to check if an object is a native Promise.\n *\n * Note that if the Promise expects a certain type like `Promise<T>`, there is\n * no way to validate the type of T unless we resolve the promise. This function\n * does not attempt to typecheck for T in any way.\n */\nexport function isNativePromise(obj: unknown): obj is Promise<unknown> {\n return obj instanceof Promise;\n}\n"],"mappings":"AAQO,SAASA,EAAUC,EAAuC,CAE/D,MAAI,CAACA,GAAQ,OAAOA,GAAQ,UAAY,OAAOA,GAAQ,WAC9C,GAIF,SAAUA,GAAO,OAAOA,EAAI,MAAS,UAC9C,CASO,SAASC,EAAgBD,EAAuC,CACrE,OAAOA,aAAe,OACxB","names":["isPromise","obj","isNativePromise"]}
|
package/isPromise.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// src/isPromise.ts
|
|
2
|
+
function isPromise(obj) {
|
|
3
|
+
if (!obj || typeof obj !== "object" && typeof obj !== "function") {
|
|
4
|
+
return false;
|
|
5
|
+
}
|
|
6
|
+
return "then" in obj && typeof obj.then === "function";
|
|
7
|
+
}
|
|
8
|
+
function isNativePromise(obj) {
|
|
9
|
+
return obj instanceof Promise;
|
|
10
|
+
}
|
|
11
|
+
export {
|
|
12
|
+
isNativePromise,
|
|
13
|
+
isPromise
|
|
14
|
+
};
|
package/kvStore.cjs
CHANGED
|
@@ -251,11 +251,12 @@ var KvStore = class {
|
|
|
251
251
|
}
|
|
252
252
|
/** Remove all items from the store. */
|
|
253
253
|
async clear() {
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
254
|
+
await this.transact("readwrite", (objectStore, resolve, reject) => {
|
|
255
|
+
const request = withOnError(objectStore.clear(), reject);
|
|
256
|
+
request.onsuccess = () => {
|
|
257
|
+
resolve();
|
|
258
|
+
};
|
|
257
259
|
});
|
|
258
|
-
await this.delete(keys);
|
|
259
260
|
}
|
|
260
261
|
/**
|
|
261
262
|
* Returns all items as map of key to value, mainly used for debugging dumps.
|
package/kvStore.min.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var f=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var T=(r,t)=>{for(var e in t)f(r,e,{get:t[e],enumerable:!0})},E=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of M(t))!D.call(r,n)&&n!==e&&f(r,n,{get:()=>t[n],enumerable:!(s=S(t,n))||s.enumerable});return r};var _=r=>E(f({},"__esModule",{value:!0}),r);var R={};T(R,{KvStore:()=>b,KvStoreConfig:()=>
|
|
1
|
+
"use strict";var f=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var T=(r,t)=>{for(var e in t)f(r,e,{get:t[e],enumerable:!0})},E=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of M(t))!D.call(r,n)&&n!==e&&f(r,n,{get:()=>t[n],enumerable:!(s=S(t,n))||s.enumerable});return r};var _=r=>E(f({},"__esModule",{value:!0}),r);var R={};T(R,{KvStore:()=>b,KvStoreConfig:()=>l,KvStoreItem:()=>g,configureKvStore:()=>O,kvStore:()=>h,kvStoreItem:()=>N});module.exports=_(R);function P(r){let t=(r.days??0)*864e5,e=(r.hours??0)*36e5,s=(r.minutes??0)*6e4,n=(r.seconds??0)*1e3,o=r.milliseconds??0;return t+e+s+n+o}function d(r){return typeof r=="number"?r:P(r)}var l={dbName:"KVStore",dbVersion:1,storeName:"kvStore",expiryMs:864e5*30,gcIntervalMs:864e5};function O(r){Object.assign(l,r)}function m(r){if(!(!r||typeof r!="object"||typeof r.key!="string"||r.value===void 0||typeof r.storedMs!="number"||typeof r.expiryMs!="number"||Date.now()>=r.expiryMs))return r}function c(r,t){return r.onerror=e=>{t(e)},r}var b=class{constructor(t,e){this.dbName=t;this.dbVersion=e?.dbVersion??l.dbVersion,this.storeName=e?.storeName??l.storeName,this.defaultExpiryMs=e?.defaultExpiryMs?d(e.defaultExpiryMs):l.expiryMs,this.gcIntervalMs=e?.gcIntervalMs?d(e.gcIntervalMs):l.gcIntervalMs,this.gcMsStorageKey=`__kvStore:lastGcMs:${t}:v${this.dbVersion}:${this.storeName}`}db;gcMsStorageKey;dbVersion;storeName;defaultExpiryMs;gcIntervalMs;async getOrCreateDb(){return this.db||(this.db=await new Promise((t,e)=>{let s=c(globalThis.indexedDB.open(this.dbName,this.dbVersion),e);s.onupgradeneeded=n=>{n.target.result.createObjectStore(this.storeName,{keyPath:"key"}).createIndex("key","key",{unique:!0})},s.onsuccess=n=>{let o=n.target.result;t(o)}})),this.db}async transact(t,e){let s=await this.getOrCreateDb();return await new Promise((n,o)=>{let i=c(s.transaction(this.storeName,t),o);i.onabort=u=>{o(u)};let a=i.objectStore(this.storeName);e(a,n,o)})}async set(t,e,s=this.defaultExpiryMs){let n=Date.now(),o={key:t,value:e,storedMs:n,expiryMs:n+d(s)};return await this.transact("readwrite",(i,a,u)=>{let y=c(i.put(o),u);y.onsuccess=()=>{a(e),this.gc()}})}async delete(t){return await this.transact("readwrite",(e,s,n)=>{if(e.transaction.oncomplete=()=>{s()},typeof t=="string")c(e.delete(t),n);else for(let o of t)c(e.delete(o),n)})}async getStoredObject(t){let e=await this.transact("readonly",(s,n,o)=>{let i=c(s.get(t),o);i.onsuccess=()=>{n(i.result)}});if(e)try{let s=m(e);if(!s){await this.delete(t),this.gc();return}return s}catch(s){console.error(`Invalid kv value: ${t}=${JSON.stringify(e)}:`,s),await this.delete(t),this.gc();return}}async get(t){return(await this.getStoredObject(t))?.value}async forEach(t){await this.transact("readonly",(e,s,n)=>{let o=c(e.openCursor(),n);o.onsuccess=async i=>{let a=i.target.result;if(a){if(a.key){let u=m(a.value);u!==void 0&&await t(String(a.key),u.value,u.expiryMs,u.storedMs)}a.continue()}else s()}})}async size(){let t=0;return await this.forEach(()=>{t++}),t}async clear(){await this.transact("readwrite",(t,e,s)=>{let n=c(t.clear(),s);n.onsuccess=()=>{e()}})}async asMap(){let t=new Map;return await this.forEach((e,s,n,o)=>{t.set(e,{value:s,expiryMs:n,storedMs:o})}),t}get lastGcMs(){let t=globalThis.localStorage.getItem(this.gcMsStorageKey);if(!t)return 0;let e=Number(t);return isNaN(e)?0:e}set lastGcMs(t){globalThis.localStorage.setItem(this.gcMsStorageKey,String(t))}async gc(){let t=this.lastGcMs;if(!t){this.lastGcMs=Date.now();return}Date.now()<t+this.gcIntervalMs||await this.gcNow()}async gcNow(){console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`),this.lastGcMs=Date.now();let t=[];await this.forEach(async(e,s,n)=>{(s===void 0||Date.now()>=n)&&t.push(e)}),t.length&&await this.delete(t),console.log(`Finished kvStore GC on ${this.dbName} v${this.dbVersion} - deleted ${t.length} keys`),this.lastGcMs=Date.now()}asStorageAdapter(){return this}},h=new b(l.dbName),g=class{constructor(t,e=l.expiryMs,s=h){this.key=t;this.store=s;this.defaultExpiryMs=e&&d(e)}defaultExpiryMs;async set(t,e=this.defaultExpiryMs){await this.store.set(this.key,t,e)}async getStoredObject(){return await this.store.getStoredObject(this.key)}async get(){return await this.store.get(this.key)}async delete(){await this.store.delete(this.key)}};function N(r,t,e=h){return t=t&&d(t),new g(r,t,e)}0&&(module.exports={KvStore,KvStoreConfig,KvStoreItem,configureKvStore,kvStore,kvStoreItem});
|
|
2
2
|
//# sourceMappingURL=kvStore.min.cjs.map
|
package/kvStore.min.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/kvStore.ts","../src/duration.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. Extremely simple interface to use indexed DBs.\n * 2. Auto-expirations with GC frees you from worrying about data clean-up.\n * 3. 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, but with\n * async interface functions as required by indexed DB.\n *\n * Why not use the indexed DB directly?\n * It will require you to write a lot of code to reinvent the wheel.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\nimport {\n FullStorageAdapter,\n StorageAdapter,\n StoredObject,\n} from \"./storageAdapter\";\nimport { MS_PER_DAY } from \"./timeConstants\";\n\n/** Global defaults can be updated directly. */\nexport const KvStoreConfig = {\n /**\n * Name of the DB in the indexed DB.\n * Updating the DB name will cause all old entries to be gone.\n */\n dbName: \"KVStore\",\n\n /**\n * Version of the DB schema. Most likely you will never want to change this.\n * Updating the version will cause all old entries to be gone.\n */\n dbVersion: 1,\n\n /**\n * Name of the store within the indexed DB. Each DB can have multiple stores.\n * In practice, it doesn't matter what you name this to be.\n */\n storeName: \"kvStore\",\n\n /** 30 days in ms. */\n expiryMs: MS_PER_DAY * 30,\n\n /** Do GC once per day. */\n gcIntervalMs: MS_PER_DAY,\n};\n\nexport type KvStoreConfig = typeof KvStoreConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureKvStore(config: Partial<KvStoreConfig>) {\n Object.assign(KvStoreConfig, config);\n}\n\n/** Type to represent a full object with metadata stored in the store. */\nexport type KvStoredObject<T> = StoredObject<T> & {\n // The key is required by the ObjectStore.\n key: string;\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: KvStoredObject<T>,\n): KvStoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n typeof obj.key !== \"string\" ||\n obj.value === undefined ||\n typeof obj.storedMs !== \"number\" ||\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\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 */\n// Using `any` because the store could store any type of data for each key,\n// but the caller can specify a more specific type when calling each of the\n// methods.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class KvStore implements FullStorageAdapter<any> {\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 readonly dbVersion: number;\n public readonly storeName: string;\n public readonly defaultExpiryMs: number;\n public readonly gcIntervalMs: number;\n\n public constructor(\n public readonly dbName: string,\n options?: {\n dbVersion?: number;\n storeName?: string;\n defaultExpiryMs?: number | Duration;\n gcIntervalMs?: number | Duration;\n },\n ) {\n this.dbVersion = options?.dbVersion ?? KvStoreConfig.dbVersion;\n this.storeName = options?.storeName ?? KvStoreConfig.storeName;\n\n this.defaultExpiryMs = options?.defaultExpiryMs\n ? durationOrMsToMs(options.defaultExpiryMs)\n : KvStoreConfig.expiryMs;\n\n this.gcIntervalMs = options?.gcIntervalMs\n ? durationOrMsToMs(options.gcIntervalMs)\n : KvStoreConfig.gcIntervalMs;\n\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${this.dbVersion}:${this.storeName}`;\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(this.storeName, {\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(\n db.transaction(this.storeName, mode),\n reject,\n );\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(this.storeName);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n /** Set a value in the store. */\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: KvStoredObject<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 /** Mainly used to get the expiration timestamp of an object. */\n public async getStoredObject<T>(\n key: string,\n ): Promise<KvStoredObject<T> | undefined> {\n const stored = await this.transact<KvStoredObject<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 /** Get a value by key, or undefined if it does not exist. */\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 /** Generic way to iterate through all entries. */\n public async forEach<T>(\n callback: (\n key: string,\n value: T,\n expiryMs: number,\n storedMs: 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 !== undefined) {\n await callback(\n String(cursor.key),\n obj.value as T,\n obj.expiryMs,\n obj.storedMs,\n );\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /**\n * Returns the number of items in the store. Note that getting the size\n * requires iterating through the entire store because the items could expire\n * at any time, and hence the size is a dynamic number.\n */\n public async size(): Promise<number> {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n /** Remove all items from the store. */\n public async clear(): Promise<void> {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /**\n * Returns all items as map of key to value, mainly used for debugging dumps.\n * The type T is applied to all values, even though they might not be of type\n * T (in the case when you store different data types in the same store).\n */\n public async asMap<T>(): Promise<Map<string, StoredObject<T>>> {\n const map = new Map<string, StoredObject<T>>();\n await this.forEach((key, value, expiryMs, storedMs) => {\n map.set(key, { value: value as T, expiryMs, storedMs });\n });\n return map;\n }\n\n /** Returns the ms timestamp for the last GC (garbage collection). */\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 /** Set the ms timestamp for the last GC (garbage collection). */\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due, else do nothing. */\n public async gc(): Promise<void> {\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 + this.gcIntervalMs) {\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 /**\n * Perform garbage collection immediately without checking whether we are\n * due for the next GC or not.\n */\n public async gcNow(): Promise<void> {\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 /** Returns `this` casted into a StorageAdapter<T>. */\n public asStorageAdapter<T>(): StorageAdapter<T> {\n return this as StorageAdapter<T>;\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(KvStoreConfig.dbName);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nexport class KvStoreItem<T> {\n public readonly defaultExpiryMs: number;\n\n public constructor(\n public readonly key: string,\n defaultExpiryMs: number | Duration = KvStoreConfig.expiryMs,\n public readonly store = kvStore,\n ) {\n this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);\n }\n\n /** Set a value in the store. */\n public async set(\n value: T,\n expiryDeltaMs: number | undefined = this.defaultExpiryMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs, storedMs } =\n * await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<KvStoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n /** Delete this key from the store. */\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/** Create a KV store item with a key and a default expiration. */\nexport function kvStoreItem<T>(\n key: string,\n expiryMs?: number | Duration,\n store = kvStore,\n): KvStoreItem<T> {\n expiryMs = expiryMs && durationOrMsToMs(expiryMs);\n\n return new KvStoreItem<T>(key, expiryMs, store);\n}\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 HOURS_PER_DAY,\n MINUTES_PER_HOUR,\n MS_PER_DAY,\n MS_PER_HOUR,\n MS_PER_MINUTE,\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\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":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,kBAAAC,EAAA,gBAAAC,EAAA,qBAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,EAAAR,GC0LO,SAASS,EAAaC,EAA4B,CACvD,IAAMC,GAAUD,EAAS,MAAQ,GAAK,MAChCE,GAAWF,EAAS,OAAS,GAAK,KAClCG,GAAUH,EAAS,SAAW,GAAK,IACnCI,GAAUJ,EAAS,SAAW,GAAK,IACnCK,EAAOL,EAAS,cAAgB,EAEtC,OAAOC,EAASC,EAAUC,EAASC,EAASC,CAC9C,CAKO,SAASC,EAAiBN,EAAqC,CACpE,OAAO,OAAOA,GAAa,SAAWA,EAAWD,EAAaC,CAAQ,CACxE,CDhLO,IAAMO,EAAgB,CAK3B,OAAQ,UAMR,UAAW,EAMX,UAAW,UAGX,SAAU,MAAa,GAGvB,aAAc,KAChB,EAKO,SAASC,EAAiBC,EAAgC,CAC/D,OAAO,OAAOF,EAAeE,CAAM,CACrC,CAYA,SAASC,EACPC,EAC+B,CAC/B,GACE,GAACA,GACD,OAAOA,GAAQ,UACf,OAAOA,EAAI,KAAQ,UACnBA,EAAI,QAAU,QACd,OAAOA,EAAI,UAAa,UACxB,OAAOA,EAAI,UAAa,UACxB,KAAK,IAAI,GAAKA,EAAI,UAKpB,OAAOA,CACT,CAGA,SAASC,EACPC,EACAC,EACG,CACH,OAAAD,EAAQ,QAAWE,GAAU,CAC3BD,EAAOC,CAAK,CACd,EAEOF,CACT,CAUO,IAAMG,EAAN,KAAiD,CAY/C,YACWC,EAChBC,EAMA,CAPgB,YAAAD,EAQhB,KAAK,U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Store_exports","__export","KvStore","KvStoreConfig","KvStoreItem","configureKvStore","kvStore","kvStoreItem","__toCommonJS","durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","KvStoreConfig","configureKvStore","config","validateStoredObject","obj","withOnError","request","reject","event","KvStore","dbName","options","durationOrMsToMs","resolve","db","mode","callback","transaction","objectStore","key","value","expiryDeltaMs","nowMs","k","stored","e","cursor","count","keys","map","expiryMs","storedMs","lastGcMsStr","ms","lastGcMs","keysToDelete","kvStore","KvStoreItem","defaultExpiryMs","store","kvStoreItem"]}
|
|
1
|
+
{"version":3,"sources":["../src/kvStore.ts","../src/duration.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. Extremely simple interface to use indexed DBs.\n * 2. Auto-expirations with GC frees you from worrying about data clean-up.\n * 3. 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, but with\n * async interface functions as required by indexed DB.\n *\n * Why not use the indexed DB directly?\n * It will require you to write a lot of code to reinvent the wheel.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\nimport {\n FullStorageAdapter,\n StorageAdapter,\n StoredObject,\n} from \"./storageAdapter\";\nimport { MS_PER_DAY } from \"./timeConstants\";\n\n/** Global defaults can be updated directly. */\nexport const KvStoreConfig = {\n /**\n * Name of the DB in the indexed DB.\n * Updating the DB name will cause all old entries to be gone.\n */\n dbName: \"KVStore\",\n\n /**\n * Version of the DB schema. Most likely you will never want to change this.\n * Updating the version will cause all old entries to be gone.\n */\n dbVersion: 1,\n\n /**\n * Name of the store within the indexed DB. Each DB can have multiple stores.\n * In practice, it doesn't matter what you name this to be.\n */\n storeName: \"kvStore\",\n\n /** 30 days in ms. */\n expiryMs: MS_PER_DAY * 30,\n\n /** Do GC once per day. */\n gcIntervalMs: MS_PER_DAY,\n};\n\nexport type KvStoreConfig = typeof KvStoreConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureKvStore(config: Partial<KvStoreConfig>) {\n Object.assign(KvStoreConfig, config);\n}\n\n/** Type to represent a full object with metadata stored in the store. */\nexport type KvStoredObject<T> = StoredObject<T> & {\n // The key is required by the ObjectStore.\n key: string;\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: KvStoredObject<T>,\n): KvStoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n typeof obj.key !== \"string\" ||\n obj.value === undefined ||\n typeof obj.storedMs !== \"number\" ||\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\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 */\n// Using `any` because the store could store any type of data for each key,\n// but the caller can specify a more specific type when calling each of the\n// methods.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class KvStore implements FullStorageAdapter<any> {\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 readonly dbVersion: number;\n public readonly storeName: string;\n public readonly defaultExpiryMs: number;\n public readonly gcIntervalMs: number;\n\n public constructor(\n public readonly dbName: string,\n options?: {\n dbVersion?: number;\n storeName?: string;\n defaultExpiryMs?: number | Duration;\n gcIntervalMs?: number | Duration;\n },\n ) {\n this.dbVersion = options?.dbVersion ?? KvStoreConfig.dbVersion;\n this.storeName = options?.storeName ?? KvStoreConfig.storeName;\n\n this.defaultExpiryMs = options?.defaultExpiryMs\n ? durationOrMsToMs(options.defaultExpiryMs)\n : KvStoreConfig.expiryMs;\n\n this.gcIntervalMs = options?.gcIntervalMs\n ? durationOrMsToMs(options.gcIntervalMs)\n : KvStoreConfig.gcIntervalMs;\n\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${this.dbVersion}:${this.storeName}`;\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(this.storeName, {\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(\n db.transaction(this.storeName, mode),\n reject,\n );\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(this.storeName);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n /** Set a value in the store. */\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: KvStoredObject<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 /** Mainly used to get the expiration timestamp of an object. */\n public async getStoredObject<T>(\n key: string,\n ): Promise<KvStoredObject<T> | undefined> {\n const stored = await this.transact<KvStoredObject<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 /** Get a value by key, or undefined if it does not exist. */\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 /** Generic way to iterate through all entries. */\n public async forEach<T>(\n callback: (\n key: string,\n value: T,\n expiryMs: number,\n storedMs: 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 !== undefined) {\n await callback(\n String(cursor.key),\n obj.value as T,\n obj.expiryMs,\n obj.storedMs,\n );\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /**\n * Returns the number of items in the store. Note that getting the size\n * requires iterating through the entire store because the items could expire\n * at any time, and hence the size is a dynamic number.\n */\n public async size(): Promise<number> {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n /** Remove all items from the store. */\n public async clear(): Promise<void> {\n await this.transact<void>(\"readwrite\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.clear(), reject);\n\n request.onsuccess = () => {\n resolve();\n };\n });\n }\n\n /**\n * Returns all items as map of key to value, mainly used for debugging dumps.\n * The type T is applied to all values, even though they might not be of type\n * T (in the case when you store different data types in the same store).\n */\n public async asMap<T>(): Promise<Map<string, StoredObject<T>>> {\n const map = new Map<string, StoredObject<T>>();\n await this.forEach((key, value, expiryMs, storedMs) => {\n map.set(key, { value: value as T, expiryMs, storedMs });\n });\n return map;\n }\n\n /** Returns the ms timestamp for the last GC (garbage collection). */\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 /** Set the ms timestamp for the last GC (garbage collection). */\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due, else do nothing. */\n public async gc(): Promise<void> {\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 + this.gcIntervalMs) {\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 /**\n * Perform garbage collection immediately without checking whether we are\n * due for the next GC or not.\n */\n public async gcNow(): Promise<void> {\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 /** Returns `this` casted into a StorageAdapter<T>. */\n public asStorageAdapter<T>(): StorageAdapter<T> {\n return this as StorageAdapter<T>;\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(KvStoreConfig.dbName);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nexport class KvStoreItem<T> {\n public readonly defaultExpiryMs: number;\n\n public constructor(\n public readonly key: string,\n defaultExpiryMs: number | Duration = KvStoreConfig.expiryMs,\n public readonly store = kvStore,\n ) {\n this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);\n }\n\n /** Set a value in the store. */\n public async set(\n value: T,\n expiryDeltaMs: number | undefined = this.defaultExpiryMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs, storedMs } =\n * await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<KvStoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n /** Delete this key from the store. */\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/** Create a KV store item with a key and a default expiration. */\nexport function kvStoreItem<T>(\n key: string,\n expiryMs?: number | Duration,\n store = kvStore,\n): KvStoreItem<T> {\n expiryMs = expiryMs && durationOrMsToMs(expiryMs);\n\n return new KvStoreItem<T>(key, expiryMs, store);\n}\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 HOURS_PER_DAY,\n MINUTES_PER_HOUR,\n MS_PER_DAY,\n MS_PER_HOUR,\n MS_PER_MINUTE,\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\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":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,kBAAAC,EAAA,gBAAAC,EAAA,qBAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,EAAAR,GC0L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AAG,CAEzB,CACF,EAEIe,EAAa,QACf,MAAM,KAAK,OAAOA,CAAY,EAGhC,QAAQ,IACN,0BAA0B,KAAK,MAAM,KAAK,KAAK,SAAS,cACzCA,EAAa,MAAM,OACpC,EAGA,KAAK,SAAW,KAAK,IAAI,CAC3B,CAGO,kBAAyC,CAC9C,OAAO,IACT,CACF,EAMaC,EAAU,IAAI1B,EAAQT,EAAc,MAAM,EAK1CoC,EAAN,KAAqB,CAGnB,YACWjB,EAChBkB,EAAqCrC,EAAc,SACnCsC,EAAQH,EACxB,CAHgB,SAAAhB,EAEA,WAAAmB,EAEhB,KAAK,gBAAkBD,GAAmBzB,EAAiByB,CAAe,CAC5E,CARgB,gBAWhB,MAAa,IACXjB,EACAC,EAAoC,KAAK,gBAC1B,CACf,MAAM,KAAK,MAAM,IAAI,KAAK,IAAKD,EAAOC,CAAa,CACrD,CAQA,MAAa,iBAA0D,CACrE,OAAO,MAAM,KAAK,MAAM,gBAAgB,KAAK,GAAG,CAClD,CAGA,MAAa,KAA8B,CACzC,OAAO,MAAM,KAAK,MAAM,IAAI,KAAK,GAAG,CACtC,CAGA,MAAa,QAAwB,CACnC,MAAM,KAAK,MAAM,OAAO,KAAK,GAAG,CAClC,CACF,EAGO,SAASkB,EACdpB,EACAU,EACAS,EAAQH,EACQ,CAChB,OAAAN,EAAWA,GAAYjB,EAAiBiB,CAAQ,EAEzC,IAAIO,EAAejB,EAAKU,EAAUS,CAAK,CAChD","names":["kvStore_exports","__export","KvStore","KvStoreConfig","KvStoreItem","configureKvStore","kvStore","kvStoreItem","__toCommonJS","durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","KvStoreConfig","configureKvStore","config","validateStoredObject","obj","withOnError","request","reject","event","KvStore","dbName","options","durationOrMsToMs","resolve","db","mode","callback","transaction","objectStore","key","value","expiryDeltaMs","nowMs","k","stored","e","cursor","count","map","expiryMs","storedMs","lastGcMsStr","ms","lastGcMs","keysToDelete","kvStore","KvStoreItem","defaultExpiryMs","store","kvStoreItem"]}
|
package/kvStore.min.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function D(r){let t=(r.days??0)*864e5,e=(r.hours??0)*36e5,s=(r.minutes??0)*6e4,n=(r.seconds??0)*1e3,o=r.milliseconds??0;return t+e+s+n+o}function d(r){return typeof r=="number"?r:D(r)}var l={dbName:"KVStore",dbVersion:1,storeName:"kvStore",expiryMs:864e5*30,gcIntervalMs:864e5};function R(r){Object.assign(l,r)}function f(r){if(!(!r||typeof r!="object"||typeof r.key!="string"||r.value===void 0||typeof r.storedMs!="number"||typeof r.expiryMs!="number"||Date.now()>=r.expiryMs))return r}function c(r,t){return r.onerror=e=>{t(e)},r}var b=class{constructor(t,e){this.dbName=t;this.dbVersion=e?.dbVersion??l.dbVersion,this.storeName=e?.storeName??l.storeName,this.defaultExpiryMs=e?.defaultExpiryMs?d(e.defaultExpiryMs):l.expiryMs,this.gcIntervalMs=e?.gcIntervalMs?d(e.gcIntervalMs):l.gcIntervalMs,this.gcMsStorageKey=`__kvStore:lastGcMs:${t}:v${this.dbVersion}:${this.storeName}`}db;gcMsStorageKey;dbVersion;storeName;defaultExpiryMs;gcIntervalMs;async getOrCreateDb(){return this.db||(this.db=await new Promise((t,e)=>{let s=c(globalThis.indexedDB.open(this.dbName,this.dbVersion),e);s.onupgradeneeded=n=>{n.target.result.createObjectStore(this.storeName,{keyPath:"key"}).createIndex("key","key",{unique:!0})},s.onsuccess=n=>{let o=n.target.result;t(o)}})),this.db}async transact(t,e){let s=await this.getOrCreateDb();return await new Promise((n,o)=>{let i=c(s.transaction(this.storeName,t),o);i.onabort=u=>{o(u)};let a=i.objectStore(this.storeName);e(a,n,o)})}async set(t,e,s=this.defaultExpiryMs){let n=Date.now(),o={key:t,value:e,storedMs:n,expiryMs:n+d(s)};return await this.transact("readwrite",(i,a,u)=>{let m=c(i.put(o),u);m.onsuccess=()=>{a(e),this.gc()}})}async delete(t){return await this.transact("readwrite",(e,s,n)=>{if(e.transaction.oncomplete=()=>{s()},typeof t=="string")c(e.delete(t),n);else for(let o of t)c(e.delete(o),n)})}async getStoredObject(t){let e=await this.transact("readonly",(s,n,o)=>{let i=c(s.get(t),o);i.onsuccess=()=>{n(i.result)}});if(e)try{let s=f(e);if(!s){await this.delete(t),this.gc();return}return s}catch(s){console.error(`Invalid kv value: ${t}=${JSON.stringify(e)}:`,s),await this.delete(t),this.gc();return}}async get(t){return(await this.getStoredObject(t))?.value}async forEach(t){await this.transact("readonly",(e,s,n)=>{let o=c(e.openCursor(),n);o.onsuccess=async i=>{let a=i.target.result;if(a){if(a.key){let u=f(a.value);u!==void 0&&await t(String(a.key),u.value,u.expiryMs,u.storedMs)}a.continue()}else s()}})}async size(){let t=0;return await this.forEach(()=>{t++}),t}async clear(){
|
|
1
|
+
function D(r){let t=(r.days??0)*864e5,e=(r.hours??0)*36e5,s=(r.minutes??0)*6e4,n=(r.seconds??0)*1e3,o=r.milliseconds??0;return t+e+s+n+o}function d(r){return typeof r=="number"?r:D(r)}var l={dbName:"KVStore",dbVersion:1,storeName:"kvStore",expiryMs:864e5*30,gcIntervalMs:864e5};function R(r){Object.assign(l,r)}function f(r){if(!(!r||typeof r!="object"||typeof r.key!="string"||r.value===void 0||typeof r.storedMs!="number"||typeof r.expiryMs!="number"||Date.now()>=r.expiryMs))return r}function c(r,t){return r.onerror=e=>{t(e)},r}var b=class{constructor(t,e){this.dbName=t;this.dbVersion=e?.dbVersion??l.dbVersion,this.storeName=e?.storeName??l.storeName,this.defaultExpiryMs=e?.defaultExpiryMs?d(e.defaultExpiryMs):l.expiryMs,this.gcIntervalMs=e?.gcIntervalMs?d(e.gcIntervalMs):l.gcIntervalMs,this.gcMsStorageKey=`__kvStore:lastGcMs:${t}:v${this.dbVersion}:${this.storeName}`}db;gcMsStorageKey;dbVersion;storeName;defaultExpiryMs;gcIntervalMs;async getOrCreateDb(){return this.db||(this.db=await new Promise((t,e)=>{let s=c(globalThis.indexedDB.open(this.dbName,this.dbVersion),e);s.onupgradeneeded=n=>{n.target.result.createObjectStore(this.storeName,{keyPath:"key"}).createIndex("key","key",{unique:!0})},s.onsuccess=n=>{let o=n.target.result;t(o)}})),this.db}async transact(t,e){let s=await this.getOrCreateDb();return await new Promise((n,o)=>{let i=c(s.transaction(this.storeName,t),o);i.onabort=u=>{o(u)};let a=i.objectStore(this.storeName);e(a,n,o)})}async set(t,e,s=this.defaultExpiryMs){let n=Date.now(),o={key:t,value:e,storedMs:n,expiryMs:n+d(s)};return await this.transact("readwrite",(i,a,u)=>{let m=c(i.put(o),u);m.onsuccess=()=>{a(e),this.gc()}})}async delete(t){return await this.transact("readwrite",(e,s,n)=>{if(e.transaction.oncomplete=()=>{s()},typeof t=="string")c(e.delete(t),n);else for(let o of t)c(e.delete(o),n)})}async getStoredObject(t){let e=await this.transact("readonly",(s,n,o)=>{let i=c(s.get(t),o);i.onsuccess=()=>{n(i.result)}});if(e)try{let s=f(e);if(!s){await this.delete(t),this.gc();return}return s}catch(s){console.error(`Invalid kv value: ${t}=${JSON.stringify(e)}:`,s),await this.delete(t),this.gc();return}}async get(t){return(await this.getStoredObject(t))?.value}async forEach(t){await this.transact("readonly",(e,s,n)=>{let o=c(e.openCursor(),n);o.onsuccess=async i=>{let a=i.target.result;if(a){if(a.key){let u=f(a.value);u!==void 0&&await t(String(a.key),u.value,u.expiryMs,u.storedMs)}a.continue()}else s()}})}async size(){let t=0;return await this.forEach(()=>{t++}),t}async clear(){await this.transact("readwrite",(t,e,s)=>{let n=c(t.clear(),s);n.onsuccess=()=>{e()}})}async asMap(){let t=new Map;return await this.forEach((e,s,n,o)=>{t.set(e,{value:s,expiryMs:n,storedMs:o})}),t}get lastGcMs(){let t=globalThis.localStorage.getItem(this.gcMsStorageKey);if(!t)return 0;let e=Number(t);return isNaN(e)?0:e}set lastGcMs(t){globalThis.localStorage.setItem(this.gcMsStorageKey,String(t))}async gc(){let t=this.lastGcMs;if(!t){this.lastGcMs=Date.now();return}Date.now()<t+this.gcIntervalMs||await this.gcNow()}async gcNow(){console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`),this.lastGcMs=Date.now();let t=[];await this.forEach(async(e,s,n)=>{(s===void 0||Date.now()>=n)&&t.push(e)}),t.length&&await this.delete(t),console.log(`Finished kvStore GC on ${this.dbName} v${this.dbVersion} - deleted ${t.length} keys`),this.lastGcMs=Date.now()}asStorageAdapter(){return this}},h=new b(l.dbName),g=class{constructor(t,e=l.expiryMs,s=h){this.key=t;this.store=s;this.defaultExpiryMs=e&&d(e)}defaultExpiryMs;async set(t,e=this.defaultExpiryMs){await this.store.set(this.key,t,e)}async getStoredObject(){return await this.store.getStoredObject(this.key)}async get(){return await this.store.get(this.key)}async delete(){await this.store.delete(this.key)}};function I(r,t,e=h){return t=t&&d(t),new g(r,t,e)}export{b as KvStore,l as KvStoreConfig,g as KvStoreItem,R as configureKvStore,h as kvStore,I as kvStoreItem};
|
|
2
2
|
//# sourceMappingURL=kvStore.min.mjs.map
|