@choksheak/ts-utils 0.1.8 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dateTimeStr.d.ts +68 -14
- package/dateTimeStr.js +68 -41
- package/dateTimeStr.js.map +1 -1
- package/duration.d.ts +70 -0
- package/duration.js +174 -0
- package/duration.js.map +1 -0
- package/kvStore.d.ts +18 -1
- package/kvStore.js +31 -4
- package/kvStore.js.map +1 -1
- package/localStorageCache.d.ts +37 -7
- package/localStorageCache.js +64 -36
- package/localStorageCache.js.map +1 -1
- package/nonEmpty.d.ts +3 -0
- package/nonEmpty.js.map +1 -1
- package/nonNil.d.ts +3 -0
- package/nonNil.js.map +1 -1
- package/package.json +1 -1
- package/safeParseInt.d.ts +3 -0
- package/safeParseInt.js.map +1 -1
- package/sleep.d.ts +4 -0
- package/sleep.js.map +1 -1
- package/src/dateTimeStr.ts +141 -69
- package/src/duration.ts +237 -0
- package/src/kvStore.ts +38 -2
- package/src/localStorageCache.ts +72 -39
- package/src/nonEmpty.ts +3 -0
- package/src/nonNil.ts +3 -0
- package/src/safeParseInt.ts +3 -0
- package/src/sleep.ts +4 -0
- package/src/timeConstants.ts +22 -0
- package/timeConstants.d.ts +18 -0
- package/timeConstants.js +70 -0
- package/timeConstants.js.map +1 -0
package/kvStore.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/kvStore.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. No need to worry about running out of storage.\n * 2. Extremely simple interface to use indexed DBs.\n * 3. Auto-expirations frees you from worrying about data clean-up.\n * 4. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage.\n */\n\n// Updating the DB name will cause all old entries to be gone.\nconst DEFAULT_DB_NAME = \"KVStore\";\n\n// Updating the version will cause all old entries to be gone.\nconst DEFAULT_DB_VERSION = 1;\n\n// Use a constant store name to keep things simple.\nconst STORE_NAME = \"kvStore\";\n\n/** One day in milliseconds. */\nexport const MILLIS_PER_DAY = 86_400_000;\n\n/** 30 days in ms. */\nexport const DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;\n\n/** Do GC once per day. */\nexport const GC_INTERVAL_MS = MILLIS_PER_DAY;\n\ntype StoredObject<T> = {\n key: string;\n value: T;\n expireMs: number;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: StoredObject<T>,\n): StoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"key\" in obj) ||\n typeof obj.key !== \"string\" ||\n !(\"value\" in obj) ||\n obj.value === undefined ||\n !(\"expireMs\" in obj) ||\n typeof obj.expireMs !== \"number\" ||\n Date.now() >= obj.expireMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\nexport class KVStoreField<T> {\n public constructor(\n public readonly store: KVStore,\n public readonly key: string,\n ) {}\n\n public get(): Promise<T | undefined> {\n return this.store.get(this.key);\n }\n\n public set(t: T): Promise<T> {\n return this.store.set(this.key, t);\n }\n\n public delete(): Promise<void> {\n return this.store.delete(this.key);\n }\n}\n\n/**\n * You can create multiple KVStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\nexport class KVStore {\n // We'll init the DB only on first use.\n private db: IDBDatabase | undefined;\n\n // Local storage key name for the last GC completed timestamp.\n public readonly gcMsStorageKey: string;\n\n public constructor(\n public readonly dbName: string,\n public readonly dbVersion: number,\n public readonly defaultExpiryDeltaMs: number,\n ) {\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${dbVersion}:${STORE_NAME}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(STORE_NAME, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(db.transaction(STORE_NAME, mode), reject);\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(STORE_NAME);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n public async set<T>(\n key: string,\n value: T,\n expireDeltaMs: number = this.defaultExpiryDeltaMs,\n ): Promise<T> {\n const obj = {\n key,\n value,\n expireMs: Date.now() + expireDeltaMs,\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const stored = await this.transact<StoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj.value;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n public async forEach(\n callback: (\n key: string,\n value: unknown,\n expireMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj) {\n await callback(String(cursor.key), obj.value, obj.expireMs);\n } else {\n await callback(String(cursor.key), undefined, 0);\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /** Cannot be a getter because this needs to be async. */\n public async size() {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n public async clear() {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /** Mainly for debugging dumps. */\n public async asMap(): Promise<Map<string, unknown>> {\n const map = new Map<string, unknown>();\n await this.forEach((key, value, expireMs) => {\n map.set(key, { value, expireMs });\n });\n return map;\n }\n\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due. */\n public async gc() {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + GC_INTERVAL_MS) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /** Perform garbage-collection immediately without checking. */\n public async gcNow() {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expireMs: number) => {\n if (value === undefined || Date.now() >= expireMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Get an independent store item with a locked key and value type. */\n public field<T>(key: string) {\n return new KVStoreField<T>(this, key);\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KVStore(\n DEFAULT_DB_NAME,\n DEFAULT_DB_VERSION,\n DEFAULT_EXPIRY_DELTA_MS,\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,aAAa;AAGZ,IAAM,iBAAiB;AAGvB,IAAM,0BAA0B,iBAAiB;AAGjD,IAAM,iBAAiB;AAY9B,SAAS,qBACP,KAC6B;AAC7B,MACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,SAAS,QACX,OAAO,IAAI,QAAQ,YACnB,EAAE,WAAW,QACb,IAAI,UAAU,UACd,EAAE,cAAc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,QACF;AAAA,MACF;AAEA,UAAI,aAAa,QAAQ;AACvB,cAAM,KAAK,OAAO,YAAY;AAAA,MAChC;AAEA,cAAQ;AAAA,QACN,0BAA0B,KAAK,MAAM,KAAK,KAAK,SAAS,cACzC,aAAa,MAAM;AAAA,MACpC;AAGA,WAAK,WAAW,KAAK,IAAI;AAAA,IAC3B;AAAA;AAAA;AAAA,EAGO,MAAS,KAAa;AAC3B,WAAO,IAAI,aAAgB,MAAM,GAAG;AAAA,EACtC;AACF;AAMO,IAAM,UAAU,IAAI;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/kvStore.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. No need to worry about running out of storage.\n * 2. Extremely simple interface to use indexed DBs.\n * 3. Auto-expirations frees you from worrying about data clean-up.\n * 4. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage.\n */\n\n// Updating the DB name will cause all old entries to be gone.\nconst DEFAULT_DB_NAME = \"KVStore\";\n\n// Updating the version will cause all old entries to be gone.\nconst DEFAULT_DB_VERSION = 1;\n\n// Use a constant store name to keep things simple.\nconst STORE_NAME = \"kvStore\";\n\n/** One day in milliseconds. */\nexport const MILLIS_PER_DAY = 86_400_000;\n\n/** 30 days in ms. */\nexport const DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;\n\n/** Do GC once per day. */\nexport const GC_INTERVAL_MS = MILLIS_PER_DAY;\n\ntype StoredObject<T> = {\n key: string;\n value: T;\n expireMs: number;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: StoredObject<T>,\n): StoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"key\" in obj) ||\n typeof obj.key !== \"string\" ||\n !(\"value\" in obj) ||\n obj.value === undefined ||\n !(\"expireMs\" in obj) ||\n typeof obj.expireMs !== \"number\" ||\n Date.now() >= obj.expireMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\nexport class KVStoreField<T> {\n public constructor(\n public readonly store: KVStore,\n public readonly key: string,\n ) {}\n\n public get(): Promise<T | undefined> {\n return this.store.get(this.key);\n }\n\n public set(t: T): Promise<T> {\n return this.store.set(this.key, t);\n }\n\n public delete(): Promise<void> {\n return this.store.delete(this.key);\n }\n}\n\n/**\n * You can create multiple KVStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\nexport class KVStore {\n // We'll init the DB only on first use.\n private db: IDBDatabase | undefined;\n\n // Local storage key name for the last GC completed timestamp.\n public readonly gcMsStorageKey: string;\n\n public constructor(\n public readonly dbName: string,\n public readonly dbVersion: number,\n public readonly defaultExpiryDeltaMs: number,\n ) {\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${dbVersion}:${STORE_NAME}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(STORE_NAME, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(db.transaction(STORE_NAME, mode), reject);\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(STORE_NAME);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number = this.defaultExpiryDeltaMs,\n ): Promise<T> {\n const obj = {\n key,\n value,\n expireMs: Date.now() + expiryDeltaMs,\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const stored = await this.transact<StoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj.value;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n public async forEach(\n callback: (\n key: string,\n value: unknown,\n expireMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj) {\n await callback(String(cursor.key), obj.value, obj.expireMs);\n } else {\n await callback(String(cursor.key), undefined, 0);\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /** Cannot be a getter because this needs to be async. */\n public async size() {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n public async clear() {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /** Mainly for debugging dumps. */\n public async asMap(): Promise<Map<string, unknown>> {\n const map = new Map<string, unknown>();\n await this.forEach((key, value, expireMs) => {\n map.set(key, { value, expireMs });\n });\n return map;\n }\n\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due. */\n public async gc() {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + GC_INTERVAL_MS) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /** Perform garbage-collection immediately without checking. */\n public async gcNow() {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expireMs: number) => {\n if (value === undefined || Date.now() >= expireMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Get an independent store item with a locked key and value type. */\n public field<T>(key: string) {\n return new KVStoreField<T>(this, key);\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KVStore(\n DEFAULT_DB_NAME,\n DEFAULT_DB_VERSION,\n DEFAULT_EXPIRY_DELTA_MS,\n);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nclass KvStoreItem<T> {\n public constructor(\n public readonly key: string,\n public readonly defaultExpiryDeltaMs: number,\n public readonly store = kvStore,\n ) {}\n\n public async get(): Promise<Awaited<T> | undefined> {\n return await this.store.get(this.key);\n }\n\n public async set(\n value: T,\n expiryDeltaMs: number = this.defaultExpiryDeltaMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/**\n * Create a KV store item with a key and a default expiration.\n */\nexport function kvStoreItem<T>(\n key: string,\n defaultExpiryDeltaMs: number,\n): KvStoreItem<T> {\n return new KvStoreItem<T>(key, defaultExpiryDeltaMs);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,aAAa;AAGZ,IAAM,iBAAiB;AAGvB,IAAM,0BAA0B,iBAAiB;AAGjD,IAAM,iBAAiB;AAY9B,SAAS,qBACP,KAC6B;AAC7B,MACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,SAAS,QACX,OAAO,IAAI,QAAQ,YACnB,EAAE,WAAW,QACb,IAAI,UAAU,UACd,EAAE,cAAc,QAChB,OAAO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MACF;AAEA,UAAI,aAAa,QAAQ;AACvB,cAAM,KAAK,OAAO,YAAY;AAAA,MAChC;AAEA,cAAQ;AAAA,QACN,0BAA0B,KAAK,MAAM,KAAK,KAAK,SAAS,cACzC,aAAa,MAAM;AAAA,MACpC;AAGA,WAAK,WAAW,KAAK,IAAI;AAAA,IAC3B;AAAA;AAAA;AAAA,EAGO,MAAS,KAAa;AAC3B,WAAO,IAAI,aAAgB,MAAM,GAAG;AAAA,EACtC;AACF;AAMO,IAAM,UAAU,IAAI;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AACF;AAKA,IAAM,cAAN,MAAqB;AAAA,EACZ,YACW,KACA,sBACA,QAAQ,SACxB;AAHgB;AACA;AACA;AAAA,EACf;AAAA,EAEU,MAAuC;AAAA;AAClD,aAAO,MAAM,KAAK,MAAM,IAAI,KAAK,GAAG;AAAA,IACtC;AAAA;AAAA,EAEa,IACX,IAEe;AAAA,+CAFf,OACA,gBAAwB,KAAK,sBACd;AACf,YAAM,KAAK,MAAM,IAAI,KAAK,KAAK,OAAO,aAAa;AAAA,IACrD;AAAA;AAAA,EAEa,SAAwB;AAAA;AACnC,YAAM,KAAK,MAAM,OAAO,KAAK,GAAG;AAAA,IAClC;AAAA;AACF;AAKO,SAAS,YACd,KACA,sBACgB;AAChB,SAAO,IAAI,YAAe,KAAK,oBAAoB;AACrD;","names":[]}
|
package/localStorageCache.d.ts
CHANGED
|
@@ -1,18 +1,48 @@
|
|
|
1
|
+
import { Duration } from "./duration";
|
|
2
|
+
export type StoredItem<T> = {
|
|
3
|
+
value: T;
|
|
4
|
+
expireMs: number;
|
|
5
|
+
};
|
|
1
6
|
/**
|
|
2
7
|
* Simple local storage cache with support for auto-expiration.
|
|
3
8
|
* Note that this works in the browser context only because nodejs does not
|
|
4
9
|
* have local storage.
|
|
10
|
+
*
|
|
11
|
+
* Create a cache item accessor object with auto-expiration. The value will
|
|
12
|
+
* always be stored as a string by applying JSON.stringify(), and will be
|
|
13
|
+
* returned in the same object type by applying JSON.parse().
|
|
14
|
+
*
|
|
15
|
+
* In order to provide proper type-checking, please always specify the T
|
|
16
|
+
* type parameter. E.g. const item = storeItem<string>("name", 10_000);
|
|
17
|
+
*
|
|
18
|
+
* @param key The store key in local storage.
|
|
19
|
+
* @param expires Either a number in milliseconds, or a Duration object
|
|
20
|
+
* @param logError Log an error if we found an invalid object in the store.
|
|
21
|
+
* The invalid object is usually a string that cannot be parsed as JSON.
|
|
22
|
+
* @param defaultValue Specify a default value to use for the object. Defaults
|
|
23
|
+
* to undefined.
|
|
5
24
|
*/
|
|
6
|
-
export declare
|
|
7
|
-
|
|
8
|
-
static getValue<T>(key: string, logError?: boolean): T | undefined;
|
|
9
|
-
}
|
|
10
|
-
/** Same as above, but saves some config for reuse. */
|
|
11
|
-
export declare class LocalStorageCacheItem<T> {
|
|
25
|
+
export declare function storeItem<T>(key: string, expires: number | Duration, logError?: boolean, defaultValue?: T): CacheItem<T>;
|
|
26
|
+
declare class CacheItem<T> {
|
|
12
27
|
readonly key: string;
|
|
13
28
|
readonly expireDeltaMs: number;
|
|
14
29
|
readonly logError: boolean;
|
|
15
|
-
|
|
30
|
+
readonly defaultValue: T | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* Create a cache item accessor object with auto-expiration.
|
|
33
|
+
*/
|
|
34
|
+
constructor(key: string, expireDeltaMs: number, logError: boolean, defaultValue: T | undefined);
|
|
35
|
+
/**
|
|
36
|
+
* Set the value of this item with auto-expiration.
|
|
37
|
+
*/
|
|
16
38
|
set(value: T): void;
|
|
39
|
+
/**
|
|
40
|
+
* Get the value of this item, or undefined if value is not set or expired.
|
|
41
|
+
*/
|
|
17
42
|
get(): T | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* Remove the value of this item.
|
|
45
|
+
*/
|
|
46
|
+
remove(): void;
|
|
18
47
|
}
|
|
48
|
+
export {};
|
package/localStorageCache.js
CHANGED
|
@@ -20,58 +20,86 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/localStorageCache.ts
|
|
21
21
|
var localStorageCache_exports = {};
|
|
22
22
|
__export(localStorageCache_exports, {
|
|
23
|
-
|
|
24
|
-
LocalStorageCacheItem: () => LocalStorageCacheItem
|
|
23
|
+
storeItem: () => storeItem
|
|
25
24
|
});
|
|
26
25
|
module.exports = __toCommonJS(localStorageCache_exports);
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
26
|
+
|
|
27
|
+
// src/timeConstants.ts
|
|
28
|
+
var MS_PER_SECOND = 1e3;
|
|
29
|
+
var MS_PER_MINUTE = 6e4;
|
|
30
|
+
var MS_PER_HOUR = 36e5;
|
|
31
|
+
var MS_PER_DAY = 864e5;
|
|
32
|
+
|
|
33
|
+
// src/duration.ts
|
|
34
|
+
function durationToMs(duration) {
|
|
35
|
+
var _a, _b, _c, _d, _e;
|
|
36
|
+
const daysMs = ((_a = duration.days) != null ? _a : 0) * MS_PER_DAY;
|
|
37
|
+
const hoursMs = ((_b = duration.hours) != null ? _b : 0) * MS_PER_HOUR;
|
|
38
|
+
const minsMs = ((_c = duration.minutes) != null ? _c : 0) * MS_PER_MINUTE;
|
|
39
|
+
const secsMs = ((_d = duration.seconds) != null ? _d : 0) * MS_PER_SECOND;
|
|
40
|
+
const msMs = (_e = duration.milliseconds) != null ? _e : 0;
|
|
41
|
+
return daysMs + hoursMs + minsMs + secsMs + msMs;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/localStorageCache.ts
|
|
45
|
+
function storeItem(key, expires, logError = true, defaultValue) {
|
|
46
|
+
const expireDeltaMs = typeof expires === "number" ? expires : durationToMs(expires);
|
|
47
|
+
return new CacheItem(key, expireDeltaMs, logError, defaultValue);
|
|
48
|
+
}
|
|
49
|
+
var CacheItem = class {
|
|
50
|
+
/**
|
|
51
|
+
* Create a cache item accessor object with auto-expiration.
|
|
52
|
+
*/
|
|
53
|
+
constructor(key, expireDeltaMs, logError, defaultValue) {
|
|
54
|
+
this.key = key;
|
|
55
|
+
this.expireDeltaMs = expireDeltaMs;
|
|
56
|
+
this.logError = logError;
|
|
57
|
+
this.defaultValue = defaultValue;
|
|
32
58
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
59
|
+
/**
|
|
60
|
+
* Set the value of this item with auto-expiration.
|
|
61
|
+
*/
|
|
62
|
+
set(value) {
|
|
63
|
+
const expireMs = Date.now() + this.expireDeltaMs;
|
|
64
|
+
const toStore = { value, expireMs };
|
|
65
|
+
const valueStr = JSON.stringify(toStore);
|
|
66
|
+
globalThis.localStorage.setItem(this.key, valueStr);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Get the value of this item, or undefined if value is not set or expired.
|
|
70
|
+
*/
|
|
71
|
+
get() {
|
|
72
|
+
const jsonStr = globalThis.localStorage.getItem(this.key);
|
|
73
|
+
if (!jsonStr) {
|
|
74
|
+
return this.defaultValue;
|
|
37
75
|
}
|
|
38
76
|
try {
|
|
39
77
|
const obj = JSON.parse(jsonStr);
|
|
40
78
|
if (!obj || typeof obj !== "object" || !("value" in obj) || !("expireMs" in obj) || typeof obj.expireMs !== "number" || Date.now() >= obj.expireMs) {
|
|
41
|
-
|
|
42
|
-
return
|
|
79
|
+
this.remove();
|
|
80
|
+
return this.defaultValue;
|
|
43
81
|
}
|
|
44
82
|
return obj.value;
|
|
45
83
|
} catch (e) {
|
|
46
|
-
if (logError) {
|
|
47
|
-
console.error(
|
|
84
|
+
if (this.logError) {
|
|
85
|
+
console.error(
|
|
86
|
+
`Found invalid storage value: ${this.key}=${jsonStr}:`,
|
|
87
|
+
e
|
|
88
|
+
);
|
|
48
89
|
}
|
|
49
|
-
|
|
50
|
-
return
|
|
90
|
+
this.remove();
|
|
91
|
+
return this.defaultValue;
|
|
51
92
|
}
|
|
52
93
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
this.
|
|
58
|
-
this.logError = logError;
|
|
59
|
-
if (defaultValue !== void 0) {
|
|
60
|
-
if (this.get() === void 0) {
|
|
61
|
-
this.set(defaultValue);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
set(value) {
|
|
66
|
-
LocalStorageCache.setValue(this.key, value, this.expireDeltaMs);
|
|
67
|
-
}
|
|
68
|
-
get() {
|
|
69
|
-
return LocalStorageCache.getValue(this.key, this.logError);
|
|
94
|
+
/**
|
|
95
|
+
* Remove the value of this item.
|
|
96
|
+
*/
|
|
97
|
+
remove() {
|
|
98
|
+
globalThis.localStorage.removeItem(this.key);
|
|
70
99
|
}
|
|
71
100
|
};
|
|
72
101
|
// Annotate the CommonJS export names for ESM import in node:
|
|
73
102
|
0 && (module.exports = {
|
|
74
|
-
|
|
75
|
-
LocalStorageCacheItem
|
|
103
|
+
storeItem
|
|
76
104
|
});
|
|
77
105
|
//# sourceMappingURL=localStorageCache.js.map
|
package/localStorageCache.js.map
CHANGED
|
@@ -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\nexport type StoredItem<T> = { value: T; expireMs: number };\n\n/**\n * Simple local storage cache with support for auto-expiration.\n * Note that this works in the browser context only because nodejs does not\n * have local storage.\n *\n * Create a cache item accessor object with auto-expiration. The value will\n * always be stored as a string by applying JSON.stringify(), and will be\n * returned in the same object type by applying JSON.parse().\n *\n * In order to provide proper type-checking, please always specify the T\n * type parameter. E.g. const item = storeItem<string>(\"name\", 10_000);\n *\n * @param key The store key in local storage.\n * @param expires Either a number in milliseconds, or a Duration object\n * @param logError Log an error if we found an invalid object in the store.\n * The invalid object is usually a string that cannot be parsed as JSON.\n * @param defaultValue Specify a default value to use for the object. Defaults\n * to undefined.\n */\nexport function storeItem<T>(\n key: string,\n expires: number | Duration,\n logError = true,\n defaultValue?: T,\n) {\n const expireDeltaMs =\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 public readonly defaultValue: T | undefined,\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 toStore: StoredItem<T> = { value, expireMs };\n const valueStr = JSON.stringify(toStore);\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) {\n return this.defaultValue;\n }\n\n try {\n const obj: StoredItem<T> | undefined = JSON.parse(jsonStr);\n\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"value\" in obj) ||\n !(\"expireMs\" in obj) ||\n typeof obj.expireMs !== \"number\" ||\n Date.now() >= obj.expireMs\n ) {\n this.remove();\n return this.defaultValue;\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 this.remove();\n return this.defaultValue;\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. Weeks have fixed durations, but are excluded because we\n * use days as the max duration supported.\n */\n\nimport {\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\n/**\n * One of: days, hours, minutes, seconds, milliseconds\n */\nexport type DurationType = keyof Duration;\n\n/**\n * Order in which the duration type appears in the duration string.\n */\nexport const DURATION_TYPE_SEQUENCE: DurationType[] = [\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\n/**\n * Follows the same format as Intl.DurationFormat.prototype.format().\n *\n * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\n * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,\n * 7 milliseconds, 8 microseconds, 9 nanoseconds\n * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\n */\nexport type DurationStyle = \"short\" | \"long\" | \"narrow\";\n\nexport type DurationSuffixMap = {\n short: string;\n shorts: string;\n long: string;\n longs: string;\n narrow: string;\n};\n\nexport type DurationSuffixType = keyof DurationSuffixMap;\n\nexport const DURATION_STYLE_SUFFIX_MAP: Record<\n DurationType,\n DurationSuffixMap\n> = {\n days: {\n short: \"day\",\n shorts: \"days\",\n long: \"day\",\n longs: \"days\",\n narrow: \"d\",\n },\n hours: {\n short: \"hr\",\n shorts: \"hrs\",\n long: \"hour\",\n longs: \"hours\",\n narrow: \"h\",\n },\n minutes: {\n short: \"min\",\n shorts: \"mins\",\n long: \"minute\",\n longs: \"minutes\",\n narrow: \"m\",\n },\n seconds: {\n short: \"sec\",\n shorts: \"secs\",\n long: \"second\",\n longs: \"seconds\",\n narrow: \"s\",\n },\n milliseconds: {\n short: \"ms\",\n shorts: \"ms\",\n long: \"millisecond\",\n longs: \"milliseconds\",\n narrow: \"ms\",\n },\n};\n\nfunction getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {\n return style == \"short\" ? \"shorts\" : style === \"long\" ? \"longs\" : style;\n}\n\nfunction getValueAndUnitSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \"\" : \" \";\n}\n\nfunction getDurationTypeSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \" \" : \", \";\n}\n\n/**\n * Convert a milliseconds duration into a Duration object. If the given ms is\n * zero, then return an object with a single field of zero with duration type\n * of durationTypeForZero.\n *\n * @param durationTypeForZero Defaults to 'milliseconds'\n */\nexport function msToDuration(\n ms: number,\n durationTypeForZero?: DurationType,\n): Duration {\n if (ms === 0) {\n durationTypeForZero = durationTypeForZero ?? \"milliseconds\";\n return { [durationTypeForZero]: 0 };\n }\n\n const duration: Duration = {};\n\n for (let i = 0; i < 1; i++) {\n let seconds = Math.floor(ms / MS_PER_SECOND);\n const millis = ms - seconds * MS_PER_SECOND;\n\n if (millis > 0) {\n duration[\"milliseconds\"] = millis;\n }\n\n if (seconds === 0) {\n break;\n }\n\n let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);\n seconds -= minutes * SECONDS_PER_MINUTE;\n\n if (seconds > 0) {\n duration[\"seconds\"] = seconds;\n }\n\n if (minutes === 0) {\n break;\n }\n\n let hours = Math.floor(minutes / MINUTES_PER_HOUR);\n minutes -= hours * MINUTES_PER_HOUR;\n\n if (minutes > 0) {\n duration[\"minutes\"] = minutes;\n }\n\n if (hours === 0) {\n break;\n }\n\n const days = Math.floor(hours / HOURS_PER_DAY);\n hours -= days * HOURS_PER_DAY;\n\n if (hours > 0) {\n duration[\"hours\"] = hours;\n }\n\n if (days > 0) {\n duration[\"days\"] = days;\n }\n }\n\n return duration;\n}\n\n/**\n * Returns the number of milliseconds for the given duration.\n */\nexport function durationToMs(duration: Duration): number {\n const daysMs = (duration.days ?? 0) * MS_PER_DAY;\n const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;\n const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;\n const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;\n const msMs = duration.milliseconds ?? 0;\n\n return daysMs + hoursMs + minsMs + secsMs + msMs;\n}\n\n/**\n * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,aAAa;;;ACkLnB,SAAS,aAAa,UAA4B;AA1LzD;AA2LE,QAAM,WAAU,cAAS,SAAT,YAAiB,KAAK;AACtC,QAAM,YAAW,cAAS,UAAT,YAAkB,KAAK;AACxC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,QAAO,cAAS,iBAAT,YAAyB;AAEtC,SAAO,SAAS,UAAU,SAAS,SAAS;AAC9C;;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2
|
* Type asserts that `t` is truthy.
|
|
3
3
|
* Throws an error if `t` is null or undefined.
|
|
4
|
+
*
|
|
5
|
+
* @param varName The variable name to include in the error to throw when t is
|
|
6
|
+
* empty. Defaults to 'value'.
|
|
4
7
|
*/
|
|
5
8
|
export declare function nonEmpty<T>(t: T | null | undefined | "" | 0 | -0 | 0n | false | typeof NaN, varName?: string): T;
|
package/nonEmpty.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nonEmpty.ts","../src/isEmpty.ts"],"sourcesContent":["import { isEmpty } from \"./isEmpty\";\n\n/**\n * Type asserts that `t` is truthy.\n * Throws an error if `t` is null or undefined.\n */\nexport function nonEmpty<T>(\n t: T | null | undefined | \"\" | 0 | -0 | 0n | false | typeof NaN,\n varName = \"value\",\n): T {\n if (isEmpty(t)) {\n throw new Error(`Empty ${varName}: ${t}`);\n }\n return t as T;\n}\n","/**\n * Returns true if `t` is empty.\n */\nexport function isEmpty(t: unknown): boolean {\n // Anything falsy is considered empty.\n if (!t) {\n return true;\n }\n\n // Arrays are also of type `object`.\n if (typeof t !== \"object\") {\n return false;\n }\n\n // `length` includes arrays as well.\n if (\"length\" in t) {\n return t.length === 0;\n }\n\n // `size` is for Set, Map, Blob etc.\n if (\"size\" in t) {\n return t.size === 0;\n }\n\n // Super fast check for object emptiness.\n // https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object\n for (const k in t) {\n return false;\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,SAAS,QAAQ,GAAqB;AAE3C,MAAI,CAAC,GAAG;AACN,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,MAAM,UAAU;AACzB,WAAO;AAAA,EACT;AAGA,MAAI,YAAY,GAAG;AACjB,WAAO,EAAE,WAAW;AAAA,EACtB;AAGA,MAAI,UAAU,GAAG;AACf,WAAO,EAAE,SAAS;AAAA,EACpB;AAIA,aAAW,KAAK,GAAG;AACjB,WAAO;AAAA,EACT;AAEA,SAAO;AACT;;;
|
|
1
|
+
{"version":3,"sources":["../src/nonEmpty.ts","../src/isEmpty.ts"],"sourcesContent":["import { isEmpty } from \"./isEmpty\";\n\n/**\n * Type asserts that `t` is truthy.\n * Throws an error if `t` is null or undefined.\n *\n * @param varName The variable name to include in the error to throw when t is\n * empty. Defaults to 'value'.\n */\nexport function nonEmpty<T>(\n t: T | null | undefined | \"\" | 0 | -0 | 0n | false | typeof NaN,\n varName = \"value\",\n): T {\n if (isEmpty(t)) {\n throw new Error(`Empty ${varName}: ${t}`);\n }\n return t as T;\n}\n","/**\n * Returns true if `t` is empty.\n */\nexport function isEmpty(t: unknown): boolean {\n // Anything falsy is considered empty.\n if (!t) {\n return true;\n }\n\n // Arrays are also of type `object`.\n if (typeof t !== \"object\") {\n return false;\n }\n\n // `length` includes arrays as well.\n if (\"length\" in t) {\n return t.length === 0;\n }\n\n // `size` is for Set, Map, Blob etc.\n if (\"size\" in t) {\n return t.size === 0;\n }\n\n // Super fast check for object emptiness.\n // https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object\n for (const k in t) {\n return false;\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,SAAS,QAAQ,GAAqB;AAE3C,MAAI,CAAC,GAAG;AACN,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,MAAM,UAAU;AACzB,WAAO;AAAA,EACT;AAGA,MAAI,YAAY,GAAG;AACjB,WAAO,EAAE,WAAW;AAAA,EACtB;AAGA,MAAI,UAAU,GAAG;AACf,WAAO,EAAE,SAAS;AAAA,EACpB;AAIA,aAAW,KAAK,GAAG;AACjB,WAAO;AAAA,EACT;AAEA,SAAO;AACT;;;ADtBO,SAAS,SACd,GACA,UAAU,SACP;AACH,MAAI,QAAQ,CAAC,GAAG;AACd,UAAM,IAAI,MAAM,SAAS,OAAO,KAAK,CAAC,EAAE;AAAA,EAC1C;AACA,SAAO;AACT;","names":[]}
|
package/nonNil.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Type asserts that `t` is neither null nor undefined.
|
|
3
3
|
* Throws an error if `t` is null or undefined.
|
|
4
|
+
*
|
|
5
|
+
* @param varName The variable name to include in the error to throw when t is
|
|
6
|
+
* nil. Defaults to 'value'.
|
|
4
7
|
*/
|
|
5
8
|
export declare function nonNil<T>(t: T | null | undefined, varName?: string): T;
|
package/nonNil.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nonNil.ts"],"sourcesContent":["/**\n * Type asserts that `t` is neither null nor undefined.\n * Throws an error if `t` is null or undefined.\n */\nexport function nonNil<T>(t: T | null | undefined, varName = \"value\"): T {\n if (t === null || t === undefined) {\n throw new Error(`Missing ${varName}: ${t}`);\n }\n return t;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
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 *\n * @param varName The variable name to include in the error to throw when t is\n * nil. Defaults to 'value'.\n */\nexport function nonNil<T>(t: T | null | undefined, varName = \"value\"): T {\n if (t === null || t === undefined) {\n throw new Error(`Missing ${varName}: ${t}`);\n }\n return t;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOO,SAAS,OAAU,GAAyB,UAAU,SAAY;AACvE,MAAI,MAAM,QAAQ,MAAM,QAAW;AACjC,UAAM,IAAI,MAAM,WAAW,OAAO,KAAK,CAAC,EAAE;AAAA,EAC5C;AACA,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
package/safeParseInt.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Returns 0 if the string is not a valid number.
|
|
3
|
+
*
|
|
4
|
+
* @param logError Log a console error if the given string is not a valid
|
|
5
|
+
* number. Defaults to false (don't log anything).
|
|
3
6
|
*/
|
|
4
7
|
export declare function safeParseInt(s: string, logError?: boolean): number;
|
package/safeParseInt.js.map
CHANGED
|
@@ -1 +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;
|
|
1
|
+
{"version":3,"sources":["../src/safeParseInt.ts"],"sourcesContent":["/**\n * Returns 0 if the string is not a valid number.\n *\n * @param logError Log a console error if the given string is not a valid\n * number. Defaults to false (don't log anything).\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;AAMO,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/sleep.d.ts
CHANGED
package/sleep.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sleep.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../src/sleep.ts"],"sourcesContent":["/**\n * Sleep for a given number of milliseconds. Note that this method is async,\n * so please remember to call it with await, like `await sleep(1000);`.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,SAAS,MAAM,IAA2B;AAC/C,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;","names":[]}
|
package/src/dateTimeStr.ts
CHANGED
|
@@ -1,83 +1,155 @@
|
|
|
1
|
-
export
|
|
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 type AnyDateTime = number | Date | string;
|
|
6
2
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
);
|
|
3
|
+
/**
|
|
4
|
+
* Convert a number (epoch milliseconds), string (parseable date/time), or
|
|
5
|
+
* Date object (no conversion) into a Date object.
|
|
6
|
+
*/
|
|
7
|
+
export function toDate(ts: AnyDateTime): Date {
|
|
8
|
+
if (typeof ts === "number" || typeof ts === "string") {
|
|
9
|
+
return new Date(ts);
|
|
14
10
|
}
|
|
15
11
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const min = dt.getMinutes();
|
|
19
|
-
const sec = dt.getSeconds();
|
|
12
|
+
return ts;
|
|
13
|
+
}
|
|
20
14
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Returns a date in yyyy-MM-dd format. E.g. '2000-01-02'.
|
|
17
|
+
*
|
|
18
|
+
* @param dt Specify a date object or default to the current date.
|
|
19
|
+
* @param separator Defaults to '-'.
|
|
20
|
+
*/
|
|
21
|
+
export function yyyyMmDd(dt = new Date(), separator = "-"): string {
|
|
22
|
+
const yr = dt.getFullYear();
|
|
23
|
+
const mth = dt.getMonth() + 1;
|
|
24
|
+
const day = dt.getDate();
|
|
29
25
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
26
|
+
return (
|
|
27
|
+
yr +
|
|
28
|
+
separator +
|
|
29
|
+
(mth < 10 ? "0" + mth : mth) +
|
|
30
|
+
separator +
|
|
31
|
+
(day < 10 ? "0" + day : day)
|
|
32
|
+
);
|
|
33
|
+
}
|
|
36
34
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Returns a date in hh:mm:ss format. E.g. '01:02:03'.
|
|
37
|
+
*
|
|
38
|
+
* @param dt Specify a date object or default to the current date/time.
|
|
39
|
+
* @param separator Defaults to ':'.
|
|
40
|
+
*/
|
|
41
|
+
export function hhMmSs(dt = new Date(), separator = ":"): string {
|
|
42
|
+
const hr = dt.getHours();
|
|
43
|
+
const min = dt.getMinutes();
|
|
44
|
+
const sec = dt.getSeconds();
|
|
43
45
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
return (
|
|
47
|
+
(hr < 10 ? "0" + hr : hr) +
|
|
48
|
+
separator +
|
|
49
|
+
(min < 10 ? "0" + min : min) +
|
|
50
|
+
separator +
|
|
51
|
+
(sec < 10 ? "0" + sec : sec)
|
|
52
|
+
);
|
|
53
|
+
}
|
|
48
54
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
55
|
+
/**
|
|
56
|
+
* Returns a date in hh:mm:ss.SSS format. E.g. '01:02:03.004'.
|
|
57
|
+
*
|
|
58
|
+
* @param dt Specify a date object or default to the current date/time.
|
|
59
|
+
* @param timeSeparator Separator for hh/mm/ss. Defaults to ':'.
|
|
60
|
+
* @param msSeparator Separator before SSS. Defaults to '.'.
|
|
61
|
+
*/
|
|
62
|
+
export function hhMmSsMs(
|
|
63
|
+
dt = new Date(),
|
|
64
|
+
timeSeparator = ":",
|
|
65
|
+
msSeparator = ".",
|
|
66
|
+
): string {
|
|
67
|
+
const ms = dt.getMilliseconds();
|
|
52
68
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
}
|
|
69
|
+
return (
|
|
70
|
+
hhMmSs(dt, timeSeparator) +
|
|
71
|
+
msSeparator +
|
|
72
|
+
(ms < 10 ? "00" + ms : ms < 100 ? "0" + ms : ms)
|
|
73
|
+
);
|
|
74
|
+
}
|
|
68
75
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
76
|
+
/**
|
|
77
|
+
* Returns the timezone string for the given date. E.g. '+8', '-3.5'.
|
|
78
|
+
* Returns 'Z' for UTC.
|
|
79
|
+
*
|
|
80
|
+
* @param dt Specify a date object or default to the current date/time.
|
|
81
|
+
*/
|
|
82
|
+
export function tzShort(dt = new Date()): string {
|
|
83
|
+
if (dt.getTimezoneOffset() === 0) {
|
|
84
|
+
return "Z";
|
|
72
85
|
}
|
|
73
86
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
87
|
+
const tzHours = dt.getTimezoneOffset() / 60;
|
|
88
|
+
return tzHours >= 0 ? "+" + tzHours : String(tzHours);
|
|
89
|
+
}
|
|
78
90
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
91
|
+
/**
|
|
92
|
+
* Returns the long month name, zero-indexed. E.g. 0 for 'January'.
|
|
93
|
+
*
|
|
94
|
+
* @param month Zero-indexed month.
|
|
95
|
+
* @param locales Specify the locale, e.g. 'en-US', new Intl.Locale("en-US").
|
|
96
|
+
*/
|
|
97
|
+
export function getLongMonthNameZeroIndexed(
|
|
98
|
+
month: number,
|
|
99
|
+
locales: Intl.LocalesArgument = "default",
|
|
100
|
+
): string {
|
|
101
|
+
return new Date(2024, month, 15).toLocaleString(locales, {
|
|
102
|
+
month: "long",
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Returns the long month name, one-indexed. E.g. 1 for 'January'.
|
|
108
|
+
*
|
|
109
|
+
* @param month One-indexed month.
|
|
110
|
+
* @param locales Specify the locale, e.g. 'en-US', new Intl.Locale("en-US").
|
|
111
|
+
*/
|
|
112
|
+
export function getLongMonthNameOneIndexed(
|
|
113
|
+
month: number,
|
|
114
|
+
locales: Intl.LocalesArgument = "default",
|
|
115
|
+
): string {
|
|
116
|
+
return getLongMonthNameZeroIndexed(month - 1, locales);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Returns the short month name, zero-indexed. E.g. 0 for 'Jan'.
|
|
121
|
+
*
|
|
122
|
+
* @param month Zero-indexed month.
|
|
123
|
+
* @param locales Specify the locale, e.g. 'en-US', new Intl.Locale("en-US").
|
|
124
|
+
*/
|
|
125
|
+
export function getShortMonthNameZeroIndexed(
|
|
126
|
+
month: number,
|
|
127
|
+
locales: Intl.LocalesArgument = "default",
|
|
128
|
+
): string {
|
|
129
|
+
return new Date(2000, month, 15).toLocaleString(locales, {
|
|
130
|
+
month: "short",
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Returns the short month name, one-indexed. E.g. 1 for 'Jan'.
|
|
136
|
+
*
|
|
137
|
+
* @param month One-indexed month.
|
|
138
|
+
* @param locales Specify the locale, e.g. 'en-US', new Intl.Locale("en-US").
|
|
139
|
+
*/
|
|
140
|
+
export function getShortMonthNameOneIndexed(
|
|
141
|
+
month: number,
|
|
142
|
+
locales: Intl.LocalesArgument = "default",
|
|
143
|
+
): string {
|
|
144
|
+
return getShortMonthNameZeroIndexed(month - 1, locales);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Returns a human-readable string date/time like '2025-01-01 22:31:16Z'.
|
|
149
|
+
* Excludes the milliseconds assuming it is not necessary for display.
|
|
150
|
+
*/
|
|
151
|
+
export function getDisplayDateTime(ts: AnyDateTime) {
|
|
152
|
+
const iso = toDate(ts).toISOString();
|
|
153
|
+
const noMs = iso.slice(0, 19) + "Z";
|
|
154
|
+
return noMs.replace("T", " ");
|
|
83
155
|
}
|