@choksheak/ts-utils 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Type asserts that `t` is truthy. Throws an error with `errorMessage` if
3
+ * `t` is falsy.
4
+ */
5
+ export declare function assert<T>(t: T | null | undefined | "" | 0 | -0 | 0n | false | typeof NaN, errorMessage: string): asserts t is T;
package/dist/assert.js ADDED
@@ -0,0 +1,35 @@
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/assert.ts
21
+ var assert_exports = {};
22
+ __export(assert_exports, {
23
+ assert: () => assert
24
+ });
25
+ module.exports = __toCommonJS(assert_exports);
26
+ function assert(t, errorMessage) {
27
+ if (!t) {
28
+ throw new Error(errorMessage);
29
+ }
30
+ }
31
+ // Annotate the CommonJS export names for ESM import in node:
32
+ 0 && (module.exports = {
33
+ assert
34
+ });
35
+ //# sourceMappingURL=assert.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/assert.ts"],"sourcesContent":["/**\n * Type asserts that `t` is truthy. Throws an error with `errorMessage` if\n * `t` is falsy.\n */\nexport function assert<T>(\n t: T | null | undefined | \"\" | 0 | -0 | 0n | false | typeof NaN,\n errorMessage: string,\n): asserts t is T {\n if (!t) {\n throw new Error(errorMessage);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,SAAS,OACd,GACA,cACgB;AAChB,MAAI,CAAC,GAAG;AACN,UAAM,IAAI,MAAM,YAAY;AAAA,EAC9B;AACF;","names":[]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Simple local storage cache with support for auto-expiration.
3
+ * Note that this works in the browser context only because nodejs does not
4
+ * have local storage.
5
+ */
6
+ export declare class LocalStorageCache {
7
+ static setValue<T>(key: string, value: T, expireDeltaMs: number): void;
8
+ static getValue<T>(key: string, logError?: boolean): T | undefined;
9
+ }
@@ -0,0 +1,59 @@
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
+ LocalStorageCache: () => LocalStorageCache
24
+ });
25
+ module.exports = __toCommonJS(localStorageCache_exports);
26
+ var LocalStorageCache = class {
27
+ static setValue(key, value, expireDeltaMs) {
28
+ const expireMs = Date.now() + expireDeltaMs;
29
+ const valueStr = JSON.stringify({ value, expireMs });
30
+ globalThis.localStorage.setItem(key, valueStr);
31
+ }
32
+ static getValue(key, logError = true) {
33
+ const jsonStr = globalThis.localStorage.getItem(key);
34
+ if (!jsonStr) return void 0;
35
+ try {
36
+ const obj = JSON.parse(jsonStr);
37
+ if (!obj || typeof obj !== "object" || !("value" in obj) || !("expireMs" in obj)) {
38
+ globalThis.localStorage.removeItem(key);
39
+ return void 0;
40
+ }
41
+ if (Date.now() >= obj.expireMs) {
42
+ globalThis.localStorage.removeItem(key);
43
+ return void 0;
44
+ }
45
+ return obj.value;
46
+ } catch (e) {
47
+ if (logError) {
48
+ console.error(`Found invalid storage value: ${key}=${jsonStr}:`, e);
49
+ }
50
+ globalThis.localStorage.removeItem(key);
51
+ return void 0;
52
+ }
53
+ }
54
+ };
55
+ // Annotate the CommonJS export names for ESM import in node:
56
+ 0 && (module.exports = {
57
+ LocalStorageCache
58
+ });
59
+ //# sourceMappingURL=localStorageCache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/localStorageCache.ts"],"sourcesContent":["/**\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 */\nexport class LocalStorageCache {\n public static setValue<T>(key: string, value: T, expireDeltaMs: number) {\n const expireMs = Date.now() + expireDeltaMs;\n const valueStr = JSON.stringify({ value, expireMs });\n\n globalThis.localStorage.setItem(key, valueStr);\n }\n\n public static getValue<T>(key: string, logError = true): T | undefined {\n const jsonStr = globalThis.localStorage.getItem(key);\n if (!jsonStr) return undefined;\n\n try {\n const obj: { value: T; expireMs: number } | undefined =\n JSON.parse(jsonStr);\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"value\" in obj) ||\n !(\"expireMs\" in obj)\n ) {\n globalThis.localStorage.removeItem(key);\n return undefined;\n }\n\n if (Date.now() >= obj.expireMs) {\n globalThis.localStorage.removeItem(key);\n return undefined;\n }\n\n return obj.value;\n } catch (e) {\n if (logError) {\n console.error(`Found invalid storage value: ${key}=${jsonStr}:`, e);\n }\n globalThis.localStorage.removeItem(key);\n return undefined;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,IAAM,oBAAN,MAAwB;AAAA,EAC7B,OAAc,SAAY,KAAa,OAAU,eAAuB;AACtE,UAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,UAAM,WAAW,KAAK,UAAU,EAAE,OAAO,SAAS,CAAC;AAEnD,eAAW,aAAa,QAAQ,KAAK,QAAQ;AAAA,EAC/C;AAAA,EAEA,OAAc,SAAY,KAAa,WAAW,MAAqB;AACrE,UAAM,UAAU,WAAW,aAAa,QAAQ,GAAG;AACnD,QAAI,CAAC,QAAS,QAAO;AAErB,QAAI;AACF,YAAM,MACJ,KAAK,MAAM,OAAO;AACpB,UACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,WAAW,QACb,EAAE,cAAc,MAChB;AACA,mBAAW,aAAa,WAAW,GAAG;AACtC,eAAO;AAAA,MACT;AAEA,UAAI,KAAK,IAAI,KAAK,IAAI,UAAU;AAC9B,mBAAW,aAAa,WAAW,GAAG;AACtC,eAAO;AAAA,MACT;AAEA,aAAO,IAAI;AAAA,IACb,SAAS,GAAG;AACV,UAAI,UAAU;AACZ,gBAAQ,MAAM,gCAAgC,GAAG,IAAI,OAAO,KAAK,CAAC;AAAA,MACpE;AACA,iBAAW,aAAa,WAAW,GAAG;AACtC,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+
3
+ // src/localStorageCache.ts
4
+ var LocalStorageCache = class {
5
+ static setValue(key, value, expireDeltaMs) {
6
+ const expireMs = Date.now() + expireDeltaMs;
7
+ const valueStr = JSON.stringify({ value, expireMs });
8
+ globalThis.localStorage.setItem(key, valueStr);
9
+ }
10
+ static getValue(key, logError = true) {
11
+ const jsonStr = globalThis.localStorage.getItem(key);
12
+ if (!jsonStr) return void 0;
13
+ try {
14
+ const obj = JSON.parse(jsonStr);
15
+ if (!obj || typeof obj !== "object" || !("value" in obj) || !("expireMs" in obj)) {
16
+ globalThis.localStorage.removeItem(key);
17
+ return void 0;
18
+ }
19
+ if (Date.now() >= obj.expireMs) {
20
+ globalThis.localStorage.removeItem(key);
21
+ return void 0;
22
+ }
23
+ return obj.value;
24
+ } catch (e) {
25
+ if (logError) {
26
+ console.error(`Found invalid storage value: ${key}=${jsonStr}:`, e);
27
+ }
28
+ globalThis.localStorage.removeItem(key);
29
+ return void 0;
30
+ }
31
+ }
32
+ };
33
+
34
+ // src/localStorageCache.test.ts
35
+ describe("LocalStorageCache", () => {
36
+ beforeEach(() => {
37
+ global.localStorage.clear();
38
+ jest.useFakeTimers();
39
+ });
40
+ afterEach(() => {
41
+ jest.useRealTimers();
42
+ });
43
+ describe("setValue", () => {
44
+ it("should store a value with an expiration time", () => {
45
+ const key = "testKey";
46
+ const value = "testValue";
47
+ const expireDeltaMs = 1e3;
48
+ LocalStorageCache.setValue(key, value, expireDeltaMs);
49
+ const storedValue = JSON.parse(
50
+ global.localStorage.getItem(key)
51
+ );
52
+ expect(storedValue.value).toBe(value);
53
+ expect(typeof storedValue.expireMs).toBe("number");
54
+ });
55
+ });
56
+ describe("getValue", () => {
57
+ it("should retrieve a stored value if not expired", () => {
58
+ const key = "testKey";
59
+ const value = "testValue";
60
+ const expireDeltaMs = 1e3;
61
+ LocalStorageCache.setValue(key, value, expireDeltaMs);
62
+ expect(LocalStorageCache.getValue(key)).toBe(value);
63
+ });
64
+ it("should return undefined if the value has expired", () => {
65
+ const key = "testKey";
66
+ const value = "testValue";
67
+ const expireDeltaMs = 1e3;
68
+ LocalStorageCache.setValue(key, value, expireDeltaMs);
69
+ jest.advanceTimersByTime(2e3);
70
+ expect(LocalStorageCache.getValue(key)).toBeUndefined();
71
+ expect(global.localStorage.getItem(key)).toBeNull();
72
+ });
73
+ it("should return undefined if the key does not exist", () => {
74
+ expect(LocalStorageCache.getValue("nonexistentKey")).toBeUndefined();
75
+ });
76
+ it("should return undefined if the stored data is invalid and remove it from storage", () => {
77
+ const consoleError = jest.spyOn(console, "error").mockReturnValue();
78
+ const key = "testKey";
79
+ global.localStorage.setItem(key, "invalidJSON");
80
+ expect(LocalStorageCache.getValue(key)).toBeUndefined();
81
+ expect(global.localStorage.getItem(key)).toBeNull();
82
+ expect(consoleError).toHaveBeenCalledTimes(1);
83
+ expect(consoleError.mock.calls[0][0]).toBe(
84
+ "Found invalid storage value: testKey=invalidJSON:"
85
+ );
86
+ });
87
+ it("should return undefined if stored data is missing required fields and remove it from storage", () => {
88
+ const key = "testKey";
89
+ global.localStorage.setItem(
90
+ key,
91
+ JSON.stringify({ someOtherField: "data" })
92
+ );
93
+ expect(LocalStorageCache.getValue(key)).toBeUndefined();
94
+ expect(global.localStorage.getItem(key)).toBeNull();
95
+ });
96
+ });
97
+ });
98
+ //# sourceMappingURL=localStorageCache.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/localStorageCache.ts","../src/localStorageCache.test.ts"],"sourcesContent":["/**\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 */\nexport class LocalStorageCache {\n public static setValue<T>(key: string, value: T, expireDeltaMs: number) {\n const expireMs = Date.now() + expireDeltaMs;\n const valueStr = JSON.stringify({ value, expireMs });\n\n globalThis.localStorage.setItem(key, valueStr);\n }\n\n public static getValue<T>(key: string, logError = true): T | undefined {\n const jsonStr = globalThis.localStorage.getItem(key);\n if (!jsonStr) return undefined;\n\n try {\n const obj: { value: T; expireMs: number } | undefined =\n JSON.parse(jsonStr);\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"value\" in obj) ||\n !(\"expireMs\" in obj)\n ) {\n globalThis.localStorage.removeItem(key);\n return undefined;\n }\n\n if (Date.now() >= obj.expireMs) {\n globalThis.localStorage.removeItem(key);\n return undefined;\n }\n\n return obj.value;\n } catch (e) {\n if (logError) {\n console.error(`Found invalid storage value: ${key}=${jsonStr}:`, e);\n }\n globalThis.localStorage.removeItem(key);\n return undefined;\n }\n }\n}\n","import { LocalStorageCache } from \"./localStorageCache\";\n\ndescribe(\"LocalStorageCache\", () => {\n beforeEach(() => {\n // Clear localStorage before each test\n global.localStorage.clear();\n jest.useFakeTimers(); // Use fake timers to control Date.now\n });\n\n afterEach(() => {\n jest.useRealTimers(); // Restore real timers after each test\n });\n\n describe(\"setValue\", () => {\n it(\"should store a value with an expiration time\", () => {\n const key = \"testKey\";\n const value = \"testValue\";\n const expireDeltaMs = 1000; // 1 second\n\n LocalStorageCache.setValue(key, value, expireDeltaMs);\n\n const storedValue = JSON.parse(\n global.localStorage.getItem(key) as string,\n );\n expect(storedValue.value).toBe(value);\n expect(typeof storedValue.expireMs).toBe(\"number\");\n });\n });\n\n describe(\"getValue\", () => {\n it(\"should retrieve a stored value if not expired\", () => {\n const key = \"testKey\";\n const value = \"testValue\";\n const expireDeltaMs = 1000; // 1 second\n\n LocalStorageCache.setValue(key, value, expireDeltaMs);\n\n expect(LocalStorageCache.getValue(key)).toBe(value);\n });\n\n it(\"should return undefined if the value has expired\", () => {\n const key = \"testKey\";\n const value = \"testValue\";\n const expireDeltaMs = 1000; // 1 second\n\n LocalStorageCache.setValue(key, value, expireDeltaMs);\n\n // Advance time by 2 seconds to ensure expiration\n jest.advanceTimersByTime(2000);\n\n expect(LocalStorageCache.getValue(key)).toBeUndefined();\n expect(global.localStorage.getItem(key)).toBeNull(); // Ensure item is removed\n });\n\n it(\"should return undefined if the key does not exist\", () => {\n expect(LocalStorageCache.getValue(\"nonexistentKey\")).toBeUndefined();\n });\n\n it(\"should return undefined if the stored data is invalid and remove it from storage\", () => {\n const consoleError = jest.spyOn(console, \"error\").mockReturnValue();\n\n const key = \"testKey\";\n // Set an invalid JSON format in localStorage\n global.localStorage.setItem(key, \"invalidJSON\");\n\n expect(LocalStorageCache.getValue(key)).toBeUndefined();\n expect(global.localStorage.getItem(key)).toBeNull(); // Ensure item is removed\n expect(consoleError).toHaveBeenCalledTimes(1);\n expect(consoleError.mock.calls[0][0]).toBe(\n \"Found invalid storage value: testKey=invalidJSON:\",\n );\n });\n\n it(\"should return undefined if stored data is missing required fields and remove it from storage\", () => {\n const key = \"testKey\";\n // Set JSON with missing fields\n global.localStorage.setItem(\n key,\n JSON.stringify({ someOtherField: \"data\" }),\n );\n\n expect(LocalStorageCache.getValue(key)).toBeUndefined();\n expect(global.localStorage.getItem(key)).toBeNull(); // Ensure item is removed\n });\n });\n});\n"],"mappings":"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","names":[]}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Type asserts that `t` is neither null nor undefined.
3
+ * Throws an error if `t` is null or undefined.
4
+ */
5
+ export declare function nonNil<T>(t: T | null | undefined, varName?: string): T;
package/dist/nonNil.js ADDED
@@ -0,0 +1,36 @@
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/nonNil.ts
21
+ var nonNil_exports = {};
22
+ __export(nonNil_exports, {
23
+ nonNil: () => nonNil
24
+ });
25
+ module.exports = __toCommonJS(nonNil_exports);
26
+ function nonNil(t, varName = "variable") {
27
+ if (t === null || t === void 0) {
28
+ throw new Error(`Missing ${varName}`);
29
+ }
30
+ return t;
31
+ }
32
+ // Annotate the CommonJS export names for ESM import in node:
33
+ 0 && (module.exports = {
34
+ nonNil
35
+ });
36
+ //# sourceMappingURL=nonNil.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nonNil.ts"],"sourcesContent":["/**\n * Type asserts that `t` is neither null nor undefined.\n * Throws an error if `t` is null or undefined.\n */\nexport function nonNil<T>(t: T | null | undefined, varName = \"variable\"): T {\n if (t === null || t === undefined) {\n throw new Error(`Missing ${varName}`);\n }\n return t;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,SAAS,OAAU,GAAyB,UAAU,YAAe;AAC1E,MAAI,MAAM,QAAQ,MAAM,QAAW;AACjC,UAAM,IAAI,MAAM,WAAW,OAAO,EAAE;AAAA,EACtC;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Returns 0 if the string is not a valid number.
3
+ */
4
+ export declare function safeParseInt(s: string, logError?: boolean): number;
@@ -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/safeParseInt.ts
21
+ var safeParseInt_exports = {};
22
+ __export(safeParseInt_exports, {
23
+ safeParseInt: () => safeParseInt
24
+ });
25
+ module.exports = __toCommonJS(safeParseInt_exports);
26
+ function safeParseInt(s, logError = false) {
27
+ const i = Number(s);
28
+ if (isNaN(i)) {
29
+ if (logError) {
30
+ console.error(`Not a number: "${s}"`);
31
+ }
32
+ return 0;
33
+ }
34
+ return Math.floor(i);
35
+ }
36
+ // Annotate the CommonJS export names for ESM import in node:
37
+ 0 && (module.exports = {
38
+ safeParseInt
39
+ });
40
+ //# sourceMappingURL=safeParseInt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/safeParseInt.ts"],"sourcesContent":["/**\n * Returns 0 if the string is not a valid number.\n */\nexport function safeParseInt(s: string, logError = false): number {\n const i = Number(s);\n\n if (isNaN(i)) {\n if (logError) {\n console.error(`Not a number: \"${s}\"`);\n }\n return 0;\n }\n\n return Math.floor(i);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,SAAS,aAAa,GAAW,WAAW,OAAe;AAChE,QAAM,IAAI,OAAO,CAAC;AAElB,MAAI,MAAM,CAAC,GAAG;AACZ,QAAI,UAAU;AACZ,cAAQ,MAAM,kBAAkB,CAAC,GAAG;AAAA,IACtC;AACA,WAAO;AAAA,EACT;AAEA,SAAO,KAAK,MAAM,CAAC;AACrB;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@choksheak/ts-utils",
3
3
  "license": "The Unlicense",
4
- "version": "0.1.2",
4
+ "version": "0.1.4",
5
5
  "description": "Random Typescript utilities with support for full tree-shaking",
6
6
  "private": false,
7
7
  "scripts": {
@@ -9,9 +9,16 @@
9
9
  "format": "prettier --write \"**/*.{js,ts}\"",
10
10
  "test": "jest",
11
11
  "test:watch": "jest --watch",
12
+ "clean": "rm -rf dist",
12
13
  "build": "tsup src/*",
13
- "pub": "npm run build && npm publish --access=public"
14
+ "gen-types": "tsc --emitDeclarationOnly --declaration",
15
+ "pub": "npm run build && npm run gen-types && npm publish --access=public"
14
16
  },
17
+ "files": [
18
+ "README.md",
19
+ "dist",
20
+ "src"
21
+ ],
15
22
  "devDependencies": {
16
23
  "@eslint/js": "^9.14.0",
17
24
  "@jest/globals": "^29.7.0",
package/.prettierrc.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "printWidth": 80
3
- }
@@ -1,3 +0,0 @@
1
- {
2
- "editor.formatOnSave": true
3
- }
package/eslint.config.mjs DELETED
@@ -1,11 +0,0 @@
1
- import globals from "globals";
2
- import pluginJs from "@eslint/js";
3
- import tseslint from "typescript-eslint";
4
-
5
- /** @type {import('eslint').Linter.Config[]} */
6
- export default [
7
- { files: ["**/*.{js,mjs,cjs,ts}"] },
8
- { languageOptions: { globals: globals.browser } },
9
- pluginJs.configs.recommended,
10
- ...tseslint.configs.recommended,
11
- ];
package/jest.config.ts DELETED
@@ -1,201 +0,0 @@
1
- /**
2
- * For a detailed explanation regarding each configuration property, visit:
3
- * https://jestjs.io/docs/configuration
4
- */
5
-
6
- import type { Config } from "jest";
7
-
8
- const config: Config = {
9
- // All imported modules in your tests should be mocked automatically
10
- // automock: false,
11
-
12
- // Stop running tests after `n` failures
13
- // bail: 0,
14
-
15
- // The directory where Jest should store its cached dependency information
16
- // cacheDirectory: "/private/var/folders/28/7mrft8f11893k5phsxjryjfm0000gp/T/jest_dy",
17
-
18
- // Automatically clear mock calls, instances, contexts and results before every test
19
- clearMocks: true,
20
-
21
- // Indicates whether the coverage information should be collected while executing the test
22
- // collectCoverage: false,
23
-
24
- // An array of glob patterns indicating a set of files for which coverage information should be collected
25
- // collectCoverageFrom: undefined,
26
-
27
- // The directory where Jest should output its coverage files
28
- // coverageDirectory: undefined,
29
-
30
- // An array of regexp pattern strings used to skip coverage collection
31
- // coveragePathIgnorePatterns: [
32
- // "/node_modules/"
33
- // ],
34
-
35
- // Indicates which provider should be used to instrument code for coverage
36
- coverageProvider: "v8",
37
-
38
- // A list of reporter names that Jest uses when writing coverage reports
39
- // coverageReporters: [
40
- // "json",
41
- // "text",
42
- // "lcov",
43
- // "clover"
44
- // ],
45
-
46
- // An object that configures minimum threshold enforcement for coverage results
47
- // coverageThreshold: undefined,
48
-
49
- // A path to a custom dependency extractor
50
- // dependencyExtractor: undefined,
51
-
52
- // Make calling deprecated APIs throw helpful error messages
53
- // errorOnDeprecated: false,
54
-
55
- // The default configuration for fake timers
56
- // fakeTimers: {
57
- // "enableGlobally": false
58
- // },
59
-
60
- // Force coverage collection from ignored files using an array of glob patterns
61
- // forceCoverageMatch: [],
62
-
63
- // A path to a module which exports an async function that is triggered once before all test suites
64
- // globalSetup: undefined,
65
-
66
- // A path to a module which exports an async function that is triggered once after all test suites
67
- // globalTeardown: undefined,
68
-
69
- // A set of global variables that need to be available in all test environments
70
- // globals: {},
71
-
72
- // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
73
- // maxWorkers: "50%",
74
-
75
- // An array of directory names to be searched recursively up from the requiring module's location
76
- // moduleDirectories: [
77
- // "node_modules"
78
- // ],
79
-
80
- // An array of file extensions your modules use
81
- // moduleFileExtensions: [
82
- // "js",
83
- // "mjs",
84
- // "cjs",
85
- // "jsx",
86
- // "ts",
87
- // "tsx",
88
- // "json",
89
- // "node"
90
- // ],
91
-
92
- // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
93
- // moduleNameMapper: {},
94
-
95
- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
96
- // modulePathIgnorePatterns: [],
97
-
98
- // Activates notifications for test results
99
- // notify: false,
100
-
101
- // An enum that specifies notification mode. Requires { notify: true }
102
- // notifyMode: "failure-change",
103
-
104
- // A preset that is used as a base for Jest's configuration
105
- preset: "ts-jest",
106
-
107
- // Run tests from one or more projects
108
- // projects: undefined,
109
-
110
- // Use this configuration option to add custom reporters to Jest
111
- // reporters: undefined,
112
-
113
- // Automatically reset mock state before every test
114
- // resetMocks: false,
115
-
116
- // Reset the module registry before running each individual test
117
- // resetModules: false,
118
-
119
- // A path to a custom resolver
120
- // resolver: undefined,
121
-
122
- // Automatically restore mock state and implementation before every test
123
- // restoreMocks: false,
124
-
125
- // The root directory that Jest should scan for tests and modules within
126
- // rootDir: undefined,
127
-
128
- // A list of paths to directories that Jest should use to search for files in
129
- // roots: [
130
- // "<rootDir>"
131
- // ],
132
-
133
- // Allows you to use a custom runner instead of Jest's default test runner
134
- // runner: "jest-runner",
135
-
136
- // The paths to modules that run some code to configure or set up the testing environment before each test
137
- setupFiles: ["jest-localstorage-mock"],
138
-
139
- // A list of paths to modules that run some code to configure or set up the testing framework before each test
140
- // setupFilesAfterEnv: [],
141
-
142
- // The number of seconds after which a test is considered as slow and reported as such in the results.
143
- // slowTestThreshold: 5,
144
-
145
- // A list of paths to snapshot serializer modules Jest should use for snapshot testing
146
- // snapshotSerializers: [],
147
-
148
- // The test environment that will be used for testing
149
- testEnvironment: "jsdom",
150
-
151
- // Options that will be passed to the testEnvironment
152
- // testEnvironmentOptions: {},
153
-
154
- // Adds a location field to test results
155
- // testLocationInResults: false,
156
-
157
- // The glob patterns Jest uses to detect test files
158
- // testMatch: [
159
- // "**/__tests__/**/*.[jt]s?(x)",
160
- // "**/?(*.)+(spec|test).[tj]s?(x)"
161
- // ],
162
-
163
- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
164
- // testPathIgnorePatterns: [
165
- // "/node_modules/"
166
- // ],
167
-
168
- // The regexp pattern or array of patterns that Jest uses to detect test files
169
- // testRegex: [],
170
-
171
- // This option allows the use of a custom results processor
172
- // testResultsProcessor: undefined,
173
-
174
- // This option allows use of a custom test runner
175
- // testRunner: "jest-circus/runner",
176
-
177
- // A map from regular expressions to paths to transformers
178
- transform: {
179
- "^.+\\.tsx?$": "ts-jest",
180
- },
181
-
182
- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
183
- // transformIgnorePatterns: [
184
- // "/node_modules/",
185
- // "\\.pnp\\.[^\\/]+$"
186
- // ],
187
-
188
- // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
189
- // unmockedModulePathPatterns: undefined,
190
-
191
- // Indicates whether each individual test should be reported during the run
192
- // verbose: undefined,
193
-
194
- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
195
- // watchPathIgnorePatterns: [],
196
-
197
- // Whether to use watchman for file crawling
198
- // watchman: true,
199
- };
200
-
201
- export default config;
package/tsup.config.ts DELETED
@@ -1,7 +0,0 @@
1
- import { defineConfig } from "tsup";
2
-
3
- export default defineConfig({
4
- splitting: false,
5
- sourcemap: true,
6
- clean: true,
7
- });