@choksheak/ts-utils 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +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\n if (!jsonStr || typeof jsonStr !== \"string\") {\n return undefined;\n }\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 typeof obj.expireMs !== \"number\" ||\n Date.now() >= obj.expireMs\n ) {\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\n/** Same as above, but saves some config for reuse. */\nexport class LocalStorageCacheItem<T> {\n public constructor(\n public readonly key: string,\n public readonly expireDeltaMs: number,\n public readonly logError = true,\n defaultValue?: T,\n ) {\n if (defaultValue !== undefined) {\n if (this.get() === undefined) {\n this.set(defaultValue);\n }\n }\n }\n\n public set(value: T) {\n LocalStorageCache.setValue(this.key, value, this.expireDeltaMs);\n }\n\n public get(): T | undefined {\n return LocalStorageCache.getValue(this.key, this.logError);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;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;AAEnD,QAAI,CAAC,WAAW,OAAO,YAAY,UAAU;AAC3C,aAAO;AAAA,IACT;AAEA,QAAI;AACF,YAAM,MACJ,KAAK,MAAM,OAAO;AACpB,UACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,WAAW,QACb,EAAE,cAAc,QAChB,OAAO,IAAI,aAAa,YACxB,KAAK,IAAI,KAAK,IAAI,UAClB;AACA,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;AAGO,IAAM,wBAAN,MAA+B;AAAA,EAC7B,YACW,KACA,eACA,WAAW,MAC3B,cACA;AAJgB;AACA;AACA;AAGhB,QAAI,iBAAiB,QAAW;AAC9B,UAAI,KAAK,IAAI,MAAM,QAAW;AAC5B,aAAK,IAAI,YAAY;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAAA,EAEO,IAAI,OAAU;AACnB,sBAAkB,SAAS,KAAK,KAAK,OAAO,KAAK,aAAa;AAAA,EAChE;AAAA,EAEO,MAAqB;AAC1B,WAAO,kBAAkB,SAAS,KAAK,KAAK,KAAK,QAAQ;AAAA,EAC3D;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/localStorageCache.ts","../src/timeConstants.ts","../src/duration.ts"],"sourcesContent":["import { Duration, durationToMs } from \"./duration\";\n\n/**\n * Simple local storage cache with support for auto-expiration.\n * Note that this works in the browser context only because nodejs does not\n * have local storage.\n *\n * Create a cache item accessor object with auto-expiration. The value will\n * always be stored as a string by applying JSON.stringify(), and will be\n * returned in the same object type by applying JSON.parse().\n *\n * In order to provide proper type-checking, please always specify the T\n * type parameter. E.g. const item = storeItem<string>(\"name\", 10_000);\n *\n * expires - Either a number in milliseconds, or a Duration object\n */\nexport function storeItem<T>(\n key: string,\n expires: number | Duration,\n logError = true,\n defaultValue?: T,\n) {\n const expireDeltaMs =\n typeof expires === \"number\" ? expires : durationToMs(expires);\n\n return new CacheItem<T>(key, expireDeltaMs, logError, defaultValue);\n}\n\nclass CacheItem<T> {\n /**\n * Create a cache item accessor object with auto-expiration.\n */\n public constructor(\n public readonly key: string,\n public readonly expireDeltaMs: number,\n public readonly logError: boolean,\n defaultValue: T | undefined,\n ) {\n if (defaultValue !== undefined) {\n if (this.get() === undefined) {\n this.set(defaultValue);\n }\n }\n }\n\n /**\n * Set the value of this item with auto-expiration.\n */\n public set(value: T): void {\n const expireMs = Date.now() + this.expireDeltaMs;\n const valueStr = JSON.stringify({ value, expireMs });\n\n globalThis.localStorage.setItem(this.key, valueStr);\n }\n\n /**\n * Get the value of this item, or undefined if value is not set or expired.\n */\n public get(): T | undefined {\n const jsonStr = globalThis.localStorage.getItem(this.key);\n\n if (!jsonStr || typeof jsonStr !== \"string\") {\n return undefined;\n }\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 typeof obj.expireMs !== \"number\" ||\n Date.now() >= obj.expireMs\n ) {\n globalThis.localStorage.removeItem(this.key);\n return undefined;\n }\n\n return obj.value;\n } catch (e) {\n if (this.logError) {\n console.error(\n `Found invalid storage value: ${this.key}=${jsonStr}:`,\n e,\n );\n }\n globalThis.localStorage.removeItem(this.key);\n return undefined;\n }\n }\n\n /**\n * Remove the value of this item.\n */\n public remove(): void {\n globalThis.localStorage.removeItem(this.key);\n }\n}\n","/**\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\n","/**\n * Bunch of miscellaneous constants and utility functions related to handling\n * date and time durations.\n *\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nimport {\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\nexport type DurationType = keyof Duration;\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.\n *\n * 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 * Format a given Duration object into a string. If the object has no fields,\n * then returns an empty string.\n *\n * 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 * options.durationTypeForZero - Defaults to 'milliseconds'\n * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,aAAa;;;AC0KnB,SAAS,aAAa,UAA4B;AAlLzD;AAmLE,QAAM,WAAU,cAAS,SAAT,YAAiB,KAAK;AACtC,QAAM,YAAW,cAAS,UAAT,YAAkB,KAAK;AACxC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,QAAO,cAAS,iBAAT,YAAyB;AAEtC,SAAO,SAAS,UAAU,SAAS,SAAS;AAC9C;;;AF1KO,SAAS,UACd,KACA,SACA,WAAW,MACX,cACA;AACA,QAAM,gBACJ,OAAO,YAAY,WAAW,UAAU,aAAa,OAAO;AAE9D,SAAO,IAAI,UAAa,KAAK,eAAe,UAAU,YAAY;AACpE;AAEA,IAAM,YAAN,MAAmB;AAAA;AAAA;AAAA;AAAA,EAIV,YACW,KACA,eACA,UAChB,cACA;AAJgB;AACA;AACA;AAGhB,QAAI,iBAAiB,QAAW;AAC9B,UAAI,KAAK,IAAI,MAAM,QAAW;AAC5B,aAAK,IAAI,YAAY;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKO,IAAI,OAAgB;AACzB,UAAM,WAAW,KAAK,IAAI,IAAI,KAAK;AACnC,UAAM,WAAW,KAAK,UAAU,EAAE,OAAO,SAAS,CAAC;AAEnD,eAAW,aAAa,QAAQ,KAAK,KAAK,QAAQ;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKO,MAAqB;AAC1B,UAAM,UAAU,WAAW,aAAa,QAAQ,KAAK,GAAG;AAExD,QAAI,CAAC,WAAW,OAAO,YAAY,UAAU;AAC3C,aAAO;AAAA,IACT;AAEA,QAAI;AACF,YAAM,MACJ,KAAK,MAAM,OAAO;AACpB,UACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,WAAW,QACb,EAAE,cAAc,QAChB,OAAO,IAAI,aAAa,YACxB,KAAK,IAAI,KAAK,IAAI,UAClB;AACA,mBAAW,aAAa,WAAW,KAAK,GAAG;AAC3C,eAAO;AAAA,MACT;AAEA,aAAO,IAAI;AAAA,IACb,SAAS,GAAG;AACV,UAAI,KAAK,UAAU;AACjB,gBAAQ;AAAA,UACN,gCAAgC,KAAK,GAAG,IAAI,OAAO;AAAA,UACnD;AAAA,QACF;AAAA,MACF;AACA,iBAAW,aAAa,WAAW,KAAK,GAAG;AAC3C,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKO,SAAe;AACpB,eAAW,aAAa,WAAW,KAAK,GAAG;AAAA,EAC7C;AACF;","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.7",
4
+ "version": "0.1.9",
5
5
  "description": "Random Typescript utilities with support for full tree-shaking",
6
6
  "private": false,
7
7
  "scripts": {
package/safeBtoa.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Base 64 encode the given input string, but safely.
3
+ */
4
+ export declare function safeBtoa(input: string): string;
package/safeBtoa.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/safeBtoa.ts
21
+ var safeBtoa_exports = {};
22
+ __export(safeBtoa_exports, {
23
+ safeBtoa: () => safeBtoa
24
+ });
25
+ module.exports = __toCommonJS(safeBtoa_exports);
26
+ function safeBtoa(input) {
27
+ const utf8Bytes = new TextEncoder().encode(input);
28
+ const binaryString = Array.from(utf8Bytes).map((byte) => String.fromCodePoint(byte)).join("");
29
+ return btoa(binaryString);
30
+ }
31
+ // Annotate the CommonJS export names for ESM import in node:
32
+ 0 && (module.exports = {
33
+ safeBtoa
34
+ });
35
+ //# sourceMappingURL=safeBtoa.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/safeBtoa.ts"],"sourcesContent":["/**\n * Base 64 encode the given input string, but safely.\n */\nexport function safeBtoa(input: string): string {\n // Convert the string to a UTF-8 encoded binary-safe string\n const utf8Bytes = new TextEncoder().encode(input);\n\n // Convert the binary data to a string for btoa\n const binaryString = Array.from(utf8Bytes)\n .map((byte) => String.fromCodePoint(byte))\n .join(\"\");\n\n // Use btoa to encode the binary-safe string\n return btoa(binaryString);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,SAAS,SAAS,OAAuB;AAE9C,QAAM,YAAY,IAAI,YAAY,EAAE,OAAO,KAAK;AAGhD,QAAM,eAAe,MAAM,KAAK,SAAS,EACtC,IAAI,CAAC,SAAS,OAAO,cAAc,IAAI,CAAC,EACxC,KAAK,EAAE;AAGV,SAAO,KAAK,YAAY;AAC1B;","names":[]}
package/sha256.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * SHA-256 hash an input string into an ArrayBuffer.
3
+ */
4
+ export declare function sha256(input: string): Promise<ArrayBuffer>;
package/sha256.js ADDED
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __async = (__this, __arguments, generator) => {
20
+ return new Promise((resolve, reject) => {
21
+ var fulfilled = (value) => {
22
+ try {
23
+ step(generator.next(value));
24
+ } catch (e) {
25
+ reject(e);
26
+ }
27
+ };
28
+ var rejected = (value) => {
29
+ try {
30
+ step(generator.throw(value));
31
+ } catch (e) {
32
+ reject(e);
33
+ }
34
+ };
35
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
36
+ step((generator = generator.apply(__this, __arguments)).next());
37
+ });
38
+ };
39
+
40
+ // src/sha256.ts
41
+ var sha256_exports = {};
42
+ __export(sha256_exports, {
43
+ sha256: () => sha256
44
+ });
45
+ module.exports = __toCommonJS(sha256_exports);
46
+ function sha256(input) {
47
+ return __async(this, null, function* () {
48
+ const encoder = new TextEncoder();
49
+ const uint8Array = encoder.encode(input);
50
+ const arrayBuffer = yield crypto.subtle.digest("SHA-256", uint8Array);
51
+ return arrayBuffer;
52
+ });
53
+ }
54
+ // Annotate the CommonJS export names for ESM import in node:
55
+ 0 && (module.exports = {
56
+ sha256
57
+ });
58
+ //# sourceMappingURL=sha256.js.map
package/sha256.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sha256.ts"],"sourcesContent":["/**\n * SHA-256 hash an input string into an ArrayBuffer.\n */\nexport async function sha256(input: string): Promise<ArrayBuffer> {\n // Encode the input string as a Uint8Array\n const encoder = new TextEncoder();\n const uint8Array = encoder.encode(input);\n\n // Compute the SHA-256 hash using the SubtleCrypto API\n const arrayBuffer = await crypto.subtle.digest(\"SHA-256\", uint8Array);\n\n return arrayBuffer;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,SAAsB,OAAO,OAAqC;AAAA;AAEhE,UAAM,UAAU,IAAI,YAAY;AAChC,UAAM,aAAa,QAAQ,OAAO,KAAK;AAGvC,UAAM,cAAc,MAAM,OAAO,OAAO,OAAO,WAAW,UAAU;AAEpE,WAAO;AAAA,EACT;AAAA;","names":[]}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Encode an input ArrayBuffer into a hex string.
3
+ */
4
+ export function arrayBufferToHex(buffer: ArrayBuffer): string {
5
+ // Create a Uint8Array view of the ArrayBuffer
6
+ const byteArray = new Uint8Array(buffer);
7
+
8
+ // Convert each byte to a two-character hexadecimal string
9
+ return Array.from(byteArray)
10
+ .map((byte) => byte.toString(16).padStart(2, "0"))
11
+ .join("");
12
+ }
13
+
14
+ /**
15
+ * Encode an input ArrayBuffer into a base64 string.
16
+ */
17
+ export function arrayBufferToBase64(buffer: ArrayBuffer): string {
18
+ // Convert the ArrayBuffer to a Uint8Array
19
+ const byteArray = new Uint8Array(buffer);
20
+
21
+ // Create a binary string from the byte array
22
+ const binaryString = Array.from(byteArray)
23
+ .map((byte) => String.fromCodePoint(byte))
24
+ .join("");
25
+
26
+ // Encode the binary string to base64. No need to use safeBtoa because we
27
+ // already simplified the binary input above.
28
+ return btoa(binaryString);
29
+ }
@@ -1,83 +1,82 @@
1
- export class DateTimeStr {
2
- public static yyyyMmDd(dt = new Date(), separator = "-"): string {
3
- const yr = dt.getFullYear();
4
- const mth = dt.getMonth() + 1;
5
- const day = dt.getDate();
1
+ export function yyyyMmDd(dt = new Date(), separator = "-"): string {
2
+ const yr = dt.getFullYear();
3
+ const mth = dt.getMonth() + 1;
4
+ const day = dt.getDate();
6
5
 
7
- return (
8
- yr +
9
- separator +
10
- (mth < 10 ? "0" + mth : mth) +
11
- separator +
12
- (day < 10 ? "0" + day : day)
13
- );
14
- }
15
-
16
- public static hhMmSs(dt = new Date(), separator = ":"): string {
17
- const hr = dt.getHours();
18
- const min = dt.getMinutes();
19
- const sec = dt.getSeconds();
6
+ return (
7
+ yr +
8
+ separator +
9
+ (mth < 10 ? "0" + mth : mth) +
10
+ separator +
11
+ (day < 10 ? "0" + day : day)
12
+ );
13
+ }
20
14
 
21
- return (
22
- (hr < 10 ? "0" + hr : hr) +
23
- separator +
24
- (min < 10 ? "0" + min : min) +
25
- separator +
26
- (sec < 10 ? "0" + sec : sec)
27
- );
28
- }
15
+ export function hhMmSs(dt = new Date(), separator = ":"): string {
16
+ const hr = dt.getHours();
17
+ const min = dt.getMinutes();
18
+ const sec = dt.getSeconds();
29
19
 
30
- public static hhMmSsMs(
31
- dt = new Date(),
32
- timeSeparator = ":",
33
- msSeparator = ".",
34
- ): string {
35
- const ms = dt.getMilliseconds();
20
+ return (
21
+ (hr < 10 ? "0" + hr : hr) +
22
+ separator +
23
+ (min < 10 ? "0" + min : min) +
24
+ separator +
25
+ (sec < 10 ? "0" + sec : sec)
26
+ );
27
+ }
36
28
 
37
- return (
38
- DateTimeStr.hhMmSs(dt, timeSeparator) +
39
- msSeparator +
40
- (ms < 10 ? "00" + ms : ms < 100 ? "0" + ms : ms)
41
- );
42
- }
29
+ export function hhMmSsMs(
30
+ dt = new Date(),
31
+ timeSeparator = ":",
32
+ msSeparator = ".",
33
+ ): string {
34
+ const ms = dt.getMilliseconds();
43
35
 
44
- public static tz(dt = new Date()): string {
45
- if (dt.getTimezoneOffset() === 0) {
46
- return "Z";
47
- }
36
+ return (
37
+ hhMmSs(dt, timeSeparator) +
38
+ msSeparator +
39
+ (ms < 10 ? "00" + ms : ms < 100 ? "0" + ms : ms)
40
+ );
41
+ }
48
42
 
49
- const tzHours = dt.getTimezoneOffset() / 60;
50
- return tzHours >= 0 ? "+" + tzHours : String(tzHours);
43
+ export function tzShort(dt = new Date()): string {
44
+ if (dt.getTimezoneOffset() === 0) {
45
+ return "Z";
51
46
  }
52
47
 
53
- /** Full local date/time string. */
54
- public static local(
55
- dt = new Date(),
56
- dateSeparator = "-",
57
- dtSeparator = " ",
58
- timeSeparator = ":",
59
- msSeparator = ".",
60
- ): string {
61
- return (
62
- DateTimeStr.yyyyMmDd(dt, dateSeparator) +
63
- dtSeparator +
64
- DateTimeStr.hhMmSsMs(dt, timeSeparator, msSeparator) +
65
- DateTimeStr.tz(dt)
66
- );
67
- }
48
+ const tzHours = dt.getTimezoneOffset() / 60;
49
+ return tzHours >= 0 ? "+" + tzHours : String(tzHours);
50
+ }
68
51
 
69
- /** Use the default ISO string function to keep things simple here. */
70
- public static utc(dt = new Date()) {
71
- return dt.toISOString();
72
- }
52
+ export function getLongMonthNameZeroIndexed(
53
+ month: number,
54
+ locales: Intl.LocalesArgument = "default",
55
+ ): string {
56
+ return new Date(2024, month, 15).toLocaleString(locales, {
57
+ month: "long",
58
+ });
59
+ }
73
60
 
74
- /** Default full local date+time string with full & concise info. */
75
- public static get now() {
76
- return DateTimeStr.local();
77
- }
61
+ export function getLongMonthNameOneIndexed(
62
+ month: number,
63
+ locales: Intl.LocalesArgument = "default",
64
+ ): string {
65
+ return getLongMonthNameZeroIndexed(month - 1, locales);
66
+ }
78
67
 
79
- /** Default full UTC date+time string with full & concise info. */
80
- public static get utcNow() {
81
- return DateTimeStr.utc();
82
- }
68
+ export function getShortMonthNameZeroIndexed(
69
+ month: number,
70
+ locales: Intl.LocalesArgument = "default",
71
+ ): string {
72
+ return new Date(2000, month, 15).toLocaleString(locales, {
73
+ month: "short",
74
+ });
75
+ }
76
+
77
+ export function getShortMonthNameOneIndexed(
78
+ month: number,
79
+ locales: Intl.LocalesArgument = "default",
80
+ ): string {
81
+ return getShortMonthNameZeroIndexed(month - 1, locales);
83
82
  }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Bunch of miscellaneous constants and utility functions related to handling
3
+ * date and time durations.
4
+ *
5
+ * Note that month and year do not have fixed durations, and hence are excluded
6
+ * from this file.
7
+ */
8
+
9
+ import {
10
+ MS_PER_SECOND,
11
+ SECONDS_PER_MINUTE,
12
+ MINUTES_PER_HOUR,
13
+ HOURS_PER_DAY,
14
+ MS_PER_DAY,
15
+ MS_PER_MINUTE,
16
+ MS_PER_HOUR,
17
+ } from "./timeConstants";
18
+
19
+ export type Duration = {
20
+ days?: number;
21
+ hours?: number;
22
+ minutes?: number;
23
+ seconds?: number;
24
+ milliseconds?: number;
25
+ };
26
+
27
+ export type DurationType = keyof Duration;
28
+
29
+ export const DURATION_TYPE_SEQUENCE: DurationType[] = [
30
+ "days",
31
+ "hours",
32
+ "minutes",
33
+ "seconds",
34
+ "milliseconds",
35
+ ];
36
+
37
+ /**
38
+ * Follows the same format as Intl.DurationFormat.prototype.format().
39
+ *
40
+ * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns
41
+ * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,
42
+ * 7 milliseconds, 8 microseconds, 9 nanoseconds
43
+ * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns
44
+ */
45
+ export type DurationStyle = "short" | "long" | "narrow";
46
+
47
+ export type DurationSuffixMap = {
48
+ short: string;
49
+ shorts: string;
50
+ long: string;
51
+ longs: string;
52
+ narrow: string;
53
+ };
54
+
55
+ export type DurationSuffixType = keyof DurationSuffixMap;
56
+
57
+ export const DURATION_STYLE_SUFFIX_MAP: Record<
58
+ DurationType,
59
+ DurationSuffixMap
60
+ > = {
61
+ days: {
62
+ short: "day",
63
+ shorts: "days",
64
+ long: "day",
65
+ longs: "days",
66
+ narrow: "d",
67
+ },
68
+ hours: {
69
+ short: "hr",
70
+ shorts: "hrs",
71
+ long: "hour",
72
+ longs: "hours",
73
+ narrow: "h",
74
+ },
75
+ minutes: {
76
+ short: "min",
77
+ shorts: "mins",
78
+ long: "minute",
79
+ longs: "minutes",
80
+ narrow: "m",
81
+ },
82
+ seconds: {
83
+ short: "sec",
84
+ shorts: "secs",
85
+ long: "second",
86
+ longs: "seconds",
87
+ narrow: "s",
88
+ },
89
+ milliseconds: {
90
+ short: "ms",
91
+ shorts: "ms",
92
+ long: "millisecond",
93
+ longs: "milliseconds",
94
+ narrow: "ms",
95
+ },
96
+ };
97
+
98
+ function getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {
99
+ return style == "short" ? "shorts" : style === "long" ? "longs" : style;
100
+ }
101
+
102
+ function getValueAndUnitSeparator(style: DurationStyle): string {
103
+ return style === "narrow" ? "" : " ";
104
+ }
105
+
106
+ function getDurationTypeSeparator(style: DurationStyle): string {
107
+ return style === "narrow" ? " " : ", ";
108
+ }
109
+
110
+ /**
111
+ * Convert a milliseconds duration into a Duration object. If the given ms is
112
+ * zero, then return an object with a single field of zero.
113
+ *
114
+ * durationTypeForZero - Defaults to 'milliseconds'
115
+ */
116
+ export function msToDuration(
117
+ ms: number,
118
+ durationTypeForZero?: DurationType,
119
+ ): Duration {
120
+ if (ms === 0) {
121
+ durationTypeForZero = durationTypeForZero ?? "milliseconds";
122
+ return { [durationTypeForZero]: 0 };
123
+ }
124
+
125
+ const duration: Duration = {};
126
+
127
+ for (let i = 0; i < 1; i++) {
128
+ let seconds = Math.floor(ms / MS_PER_SECOND);
129
+ const millis = ms - seconds * MS_PER_SECOND;
130
+
131
+ if (millis > 0) {
132
+ duration["milliseconds"] = millis;
133
+ }
134
+
135
+ if (seconds === 0) {
136
+ break;
137
+ }
138
+
139
+ let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);
140
+ seconds -= minutes * SECONDS_PER_MINUTE;
141
+
142
+ if (seconds > 0) {
143
+ duration["seconds"] = seconds;
144
+ }
145
+
146
+ if (minutes === 0) {
147
+ break;
148
+ }
149
+
150
+ let hours = Math.floor(minutes / MINUTES_PER_HOUR);
151
+ minutes -= hours * MINUTES_PER_HOUR;
152
+
153
+ if (minutes > 0) {
154
+ duration["minutes"] = minutes;
155
+ }
156
+
157
+ if (hours === 0) {
158
+ break;
159
+ }
160
+
161
+ const days = Math.floor(hours / HOURS_PER_DAY);
162
+ hours -= days * HOURS_PER_DAY;
163
+
164
+ if (hours > 0) {
165
+ duration["hours"] = hours;
166
+ }
167
+
168
+ if (days > 0) {
169
+ duration["days"] = days;
170
+ }
171
+ }
172
+
173
+ return duration;
174
+ }
175
+
176
+ /**
177
+ * Returns the number of milliseconds for the given duration.
178
+ */
179
+ export function durationToMs(duration: Duration): number {
180
+ const daysMs = (duration.days ?? 0) * MS_PER_DAY;
181
+ const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;
182
+ const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;
183
+ const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;
184
+ const msMs = duration.milliseconds ?? 0;
185
+
186
+ return daysMs + hoursMs + minsMs + secsMs + msMs;
187
+ }
188
+
189
+ /**
190
+ * Format a given Duration object into a string. If the object has no fields,
191
+ * then returns an empty string.
192
+ *
193
+ * style - Defaults to 'short'
194
+ */
195
+ export function formatDuration(duration: Duration, style?: DurationStyle) {
196
+ style = style ?? "short";
197
+ const stylePlural = getDurationStyleForPlural(style);
198
+
199
+ const space = getValueAndUnitSeparator(style);
200
+
201
+ const a: string[] = [];
202
+
203
+ for (const unit of DURATION_TYPE_SEQUENCE) {
204
+ const value = duration[unit];
205
+ if (value === undefined) continue;
206
+
207
+ const suffixMap = DURATION_STYLE_SUFFIX_MAP[unit];
208
+ const suffix = value === 1 ? suffixMap[style] : suffixMap[stylePlural];
209
+ a.push(value + space + suffix);
210
+ }
211
+
212
+ const separator = getDurationTypeSeparator(style);
213
+ return a.join(separator);
214
+ }
215
+
216
+ /**
217
+ * Convert a millisecond duration into a human-readable duration string.
218
+ *
219
+ * options.durationTypeForZero - Defaults to 'milliseconds'
220
+ * options.style - Defaults to 'short'
221
+ */
222
+ export function readableDuration(
223
+ ms: number,
224
+ options?: { durationTypeForZero?: DurationType; style?: DurationStyle },
225
+ ): string {
226
+ const duration = msToDuration(ms, options?.durationTypeForZero);
227
+
228
+ return formatDuration(duration, options?.style);
229
+ }