@vielzeug/toolkit 1.0.13 → 1.1.2
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/dist/array/{sortBy.cjs → arrange.cjs} +2 -2
- package/dist/array/arrange.cjs.map +1 -0
- package/dist/array/arrange.js +6 -0
- package/dist/array/arrange.js.map +1 -0
- package/dist/array/chunk.cjs.map +1 -1
- package/dist/array/chunk.js.map +1 -1
- package/dist/array/list.cjs +1 -1
- package/dist/array/list.cjs.map +1 -1
- package/dist/array/list.js +86 -53
- package/dist/array/list.js.map +1 -1
- package/dist/array/remoteList.cjs +2 -0
- package/dist/array/remoteList.cjs.map +1 -0
- package/dist/array/remoteList.js +123 -0
- package/dist/array/remoteList.js.map +1 -0
- package/dist/async/attempt.cjs.map +1 -0
- package/dist/async/attempt.js.map +1 -0
- package/dist/async/defer.cjs +2 -0
- package/dist/async/defer.cjs.map +1 -0
- package/dist/async/defer.js +10 -0
- package/dist/async/defer.js.map +1 -0
- package/dist/async/delay.cjs.map +1 -0
- package/dist/async/delay.js.map +1 -0
- package/dist/async/parallel.cjs +2 -0
- package/dist/async/parallel.cjs.map +1 -0
- package/dist/async/parallel.js +28 -0
- package/dist/async/parallel.js.map +1 -0
- package/dist/async/pool.cjs +2 -0
- package/dist/async/pool.cjs.map +1 -0
- package/dist/async/pool.js +22 -0
- package/dist/async/pool.js.map +1 -0
- package/dist/async/predict.cjs.map +1 -0
- package/dist/async/predict.js.map +1 -0
- package/dist/async/queue.cjs +2 -0
- package/dist/async/queue.cjs.map +1 -0
- package/dist/async/queue.js +57 -0
- package/dist/async/queue.js.map +1 -0
- package/dist/async/race.cjs +2 -0
- package/dist/async/race.cjs.map +1 -0
- package/dist/async/race.js +8 -0
- package/dist/async/race.js.map +1 -0
- package/dist/async/retry.cjs.map +1 -0
- package/dist/{function → async}/retry.js +4 -4
- package/dist/async/retry.js.map +1 -0
- package/dist/async/sleep.cjs +2 -0
- package/dist/async/sleep.cjs.map +1 -0
- package/dist/{function → async}/sleep.js +1 -1
- package/dist/async/sleep.js.map +1 -0
- package/dist/async/waitFor.cjs +2 -0
- package/dist/async/waitFor.cjs.map +1 -0
- package/dist/async/waitFor.js +37 -0
- package/dist/async/waitFor.js.map +1 -0
- package/dist/date/expires.cjs.map +1 -1
- package/dist/date/expires.js.map +1 -1
- package/dist/date/interval.cjs.map +1 -1
- package/dist/date/interval.js.map +1 -1
- package/dist/date/timeDiff.cjs.map +1 -1
- package/dist/date/timeDiff.js.map +1 -1
- package/dist/function/memo.cjs.map +1 -1
- package/dist/function/memo.js.map +1 -1
- package/dist/function/proxy.cjs.map +1 -1
- package/dist/function/proxy.js.map +1 -1
- package/dist/function/prune.cjs +2 -0
- package/dist/function/prune.cjs.map +1 -0
- package/dist/function/prune.js +30 -0
- package/dist/function/prune.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +575 -51
- package/dist/index.js +242 -206
- package/dist/index.js.map +1 -1
- package/dist/logit/dist/logit.cjs +1 -1
- package/dist/logit/dist/logit.cjs.map +1 -1
- package/dist/logit/dist/logit.js +147 -64
- package/dist/logit/dist/logit.js.map +1 -1
- package/dist/math/abs.cjs +2 -0
- package/dist/math/abs.cjs.map +1 -0
- package/dist/math/abs.js +7 -0
- package/dist/math/abs.js.map +1 -0
- package/dist/math/add.cjs +2 -0
- package/dist/math/add.cjs.map +1 -0
- package/dist/math/add.js +9 -0
- package/dist/math/add.js.map +1 -0
- package/dist/math/allocate.cjs +2 -0
- package/dist/math/allocate.cjs.map +1 -0
- package/dist/math/allocate.js +29 -0
- package/dist/math/allocate.js.map +1 -0
- package/dist/math/distribute.cjs +2 -0
- package/dist/math/distribute.cjs.map +1 -0
- package/dist/math/distribute.js +18 -0
- package/dist/math/distribute.js.map +1 -0
- package/dist/math/divide.cjs +2 -0
- package/dist/math/divide.cjs.map +1 -0
- package/dist/math/divide.js +11 -0
- package/dist/math/divide.js.map +1 -0
- package/dist/math/multiply.cjs +2 -0
- package/dist/math/multiply.cjs.map +1 -0
- package/dist/math/multiply.js +9 -0
- package/dist/math/multiply.js.map +1 -0
- package/dist/math/subtract.cjs +2 -0
- package/dist/math/subtract.cjs.map +1 -0
- package/dist/math/subtract.js +9 -0
- package/dist/math/subtract.js.map +1 -0
- package/dist/money/currency.cjs +2 -0
- package/dist/money/currency.cjs.map +1 -0
- package/dist/money/currency.js +49 -0
- package/dist/money/currency.js.map +1 -0
- package/dist/money/exchange.cjs +2 -0
- package/dist/money/exchange.cjs.map +1 -0
- package/dist/money/exchange.js +13 -0
- package/dist/money/exchange.js.map +1 -0
- package/dist/object/cache.cjs +2 -0
- package/dist/object/cache.cjs.map +1 -0
- package/dist/object/cache.js +63 -0
- package/dist/object/cache.js.map +1 -0
- package/dist/object/merge.cjs.map +1 -1
- package/dist/object/merge.js.map +1 -1
- package/dist/object/parseJSON.cjs.map +1 -1
- package/dist/object/parseJSON.js.map +1 -1
- package/dist/object/path.cjs.map +1 -1
- package/dist/object/path.js.map +1 -1
- package/package.json +1 -1
- package/dist/array/sortBy.cjs.map +0 -1
- package/dist/array/sortBy.js +0 -6
- package/dist/array/sortBy.js.map +0 -1
- package/dist/function/attempt.cjs.map +0 -1
- package/dist/function/attempt.js.map +0 -1
- package/dist/function/delay.cjs.map +0 -1
- package/dist/function/delay.js.map +0 -1
- package/dist/function/predict.cjs.map +0 -1
- package/dist/function/predict.js.map +0 -1
- package/dist/function/retry.cjs.map +0 -1
- package/dist/function/retry.js.map +0 -1
- package/dist/function/sleep.cjs +0 -2
- package/dist/function/sleep.cjs.map +0 -1
- package/dist/function/sleep.js.map +0 -1
- /package/dist/{function → async}/attempt.cjs +0 -0
- /package/dist/{function → async}/attempt.js +0 -0
- /package/dist/{function → async}/delay.cjs +0 -0
- /package/dist/{function → async}/delay.js +0 -0
- /package/dist/{function → async}/predict.cjs +0 -0
- /package/dist/{function → async}/predict.js +0 -0
- /package/dist/{function → async}/retry.cjs +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parallel.cjs","sources":["../../src/async/parallel.ts"],"sourcesContent":["/**\n * Processes an array with an async callback with controlled parallelism.\n * Similar to Promise.all, but limits how many items are processed concurrently.\n * Returns an ordered array of results.\n *\n * @example\n * ```ts\n * // Process 3 items at a time\n * const results = await parallel(3, [1, 2, 3, 4, 5], async (n) => {\n * await delay(100);\n * return n * 2;\n * });\n * // [2, 4, 6, 8, 10]\n *\n * // With abort signal\n * const controller = new AbortController();\n * const results = await parallel(2, items, async (item) => {\n * return processItem(item);\n * }, controller.signal);\n * ```\n *\n * @param limit - Maximum number of concurrent operations (must be >= 1)\n * @param array - Array of items to process\n * @param callback - Async function to process each item\n * @param signal - Optional AbortSignal to cancel processing\n * @returns Promise resolving to an ordered array of results\n * @throws {Error} If limit is less than 1\n * @throws {DOMException} If aborted via signal\n */\nexport async function parallel<T, R>(\n limit: number,\n array: T[],\n callback: (item: T, index: number, array: T[]) => Promise<R>,\n signal?: AbortSignal,\n): Promise<R[]> {\n if (limit < 1) {\n throw new Error('Limit must be at least 1');\n }\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n const results: R[] = new Array(array.length);\n let currentIndex = 0;\n let hasError = false;\n let error: unknown;\n\n // Check for abort\n const checkAbort = () => {\n if (signal?.aborted) {\n hasError = true;\n error = new DOMException('Aborted', 'AbortError');\n return true;\n }\n return false;\n };\n\n // Worker function that processes items from the queue\n const worker = async (): Promise<void> => {\n while (currentIndex < array.length && !hasError) {\n if (checkAbort()) {\n break;\n }\n\n const index = currentIndex++;\n\n try {\n results[index] = await callback(array[index], index, array);\n } catch (err) {\n hasError = true;\n error = err;\n break;\n }\n }\n };\n\n // Create workers up to the limit\n const workers: Promise<void>[] = [];\n const workerCount = Math.min(limit, array.length);\n\n for (let i = 0; i < workerCount; i++) {\n workers.push(worker());\n }\n\n // Wait for all workers to complete\n await Promise.all(workers);\n\n // If there was an error, throw it\n if (hasError) {\n throw error;\n }\n\n return results;\n}\n"],"names":["parallel","limit","array","callback","signal","results","currentIndex","hasError","error","checkAbort","worker","index","err","workers","workerCount","i"],"mappings":"gFA6BA,eAAsBA,EACpBC,EACAC,EACAC,EACAC,EACc,CACd,GAAIH,EAAQ,EACV,MAAM,IAAI,MAAM,0BAA0B,EAG5C,GAAIG,GAAQ,QACV,MAAM,IAAI,aAAa,UAAW,YAAY,EAGhD,MAAMC,EAAe,IAAI,MAAMH,EAAM,MAAM,EAC3C,IAAII,EAAe,EACfC,EAAW,GACXC,EAGJ,MAAMC,EAAa,IACbL,GAAQ,SACVG,EAAW,GACXC,EAAQ,IAAI,aAAa,UAAW,YAAY,EACzC,IAEF,GAIHE,EAAS,SAA2B,CACxC,KAAOJ,EAAeJ,EAAM,QAAU,CAACK,GACjC,CAAAE,KAD2C,CAK/C,MAAME,EAAQL,IAEd,GAAI,CACFD,EAAQM,CAAK,EAAI,MAAMR,EAASD,EAAMS,CAAK,EAAGA,EAAOT,CAAK,CAC5D,OAASU,EAAK,CACZL,EAAW,GACXC,EAAQI,EACR,KACF,CACF,CACF,EAGMC,EAA2B,CAAA,EAC3BC,EAAc,KAAK,IAAIb,EAAOC,EAAM,MAAM,EAEhD,QAASa,EAAI,EAAGA,EAAID,EAAaC,IAC/BF,EAAQ,KAAKH,GAAQ,EAOvB,GAHA,MAAM,QAAQ,IAAIG,CAAO,EAGrBN,EACF,MAAMC,EAGR,OAAOH,CACT"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
async function f(n, t, w, s) {
|
|
2
|
+
if (n < 1)
|
|
3
|
+
throw new Error("Limit must be at least 1");
|
|
4
|
+
if (s?.aborted)
|
|
5
|
+
throw new DOMException("Aborted", "AbortError");
|
|
6
|
+
const c = new Array(t.length);
|
|
7
|
+
let l = 0, e = !1, o;
|
|
8
|
+
const a = () => s?.aborted ? (e = !0, o = new DOMException("Aborted", "AbortError"), !0) : !1, h = async () => {
|
|
9
|
+
for (; l < t.length && !e && !a(); ) {
|
|
10
|
+
const r = l++;
|
|
11
|
+
try {
|
|
12
|
+
c[r] = await w(t[r], r, t);
|
|
13
|
+
} catch (b) {
|
|
14
|
+
e = !0, o = b;
|
|
15
|
+
break;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}, i = [], u = Math.min(n, t.length);
|
|
19
|
+
for (let r = 0; r < u; r++)
|
|
20
|
+
i.push(h());
|
|
21
|
+
if (await Promise.all(i), e)
|
|
22
|
+
throw o;
|
|
23
|
+
return c;
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
f as parallel
|
|
27
|
+
};
|
|
28
|
+
//# sourceMappingURL=parallel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parallel.js","sources":["../../src/async/parallel.ts"],"sourcesContent":["/**\n * Processes an array with an async callback with controlled parallelism.\n * Similar to Promise.all, but limits how many items are processed concurrently.\n * Returns an ordered array of results.\n *\n * @example\n * ```ts\n * // Process 3 items at a time\n * const results = await parallel(3, [1, 2, 3, 4, 5], async (n) => {\n * await delay(100);\n * return n * 2;\n * });\n * // [2, 4, 6, 8, 10]\n *\n * // With abort signal\n * const controller = new AbortController();\n * const results = await parallel(2, items, async (item) => {\n * return processItem(item);\n * }, controller.signal);\n * ```\n *\n * @param limit - Maximum number of concurrent operations (must be >= 1)\n * @param array - Array of items to process\n * @param callback - Async function to process each item\n * @param signal - Optional AbortSignal to cancel processing\n * @returns Promise resolving to an ordered array of results\n * @throws {Error} If limit is less than 1\n * @throws {DOMException} If aborted via signal\n */\nexport async function parallel<T, R>(\n limit: number,\n array: T[],\n callback: (item: T, index: number, array: T[]) => Promise<R>,\n signal?: AbortSignal,\n): Promise<R[]> {\n if (limit < 1) {\n throw new Error('Limit must be at least 1');\n }\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n const results: R[] = new Array(array.length);\n let currentIndex = 0;\n let hasError = false;\n let error: unknown;\n\n // Check for abort\n const checkAbort = () => {\n if (signal?.aborted) {\n hasError = true;\n error = new DOMException('Aborted', 'AbortError');\n return true;\n }\n return false;\n };\n\n // Worker function that processes items from the queue\n const worker = async (): Promise<void> => {\n while (currentIndex < array.length && !hasError) {\n if (checkAbort()) {\n break;\n }\n\n const index = currentIndex++;\n\n try {\n results[index] = await callback(array[index], index, array);\n } catch (err) {\n hasError = true;\n error = err;\n break;\n }\n }\n };\n\n // Create workers up to the limit\n const workers: Promise<void>[] = [];\n const workerCount = Math.min(limit, array.length);\n\n for (let i = 0; i < workerCount; i++) {\n workers.push(worker());\n }\n\n // Wait for all workers to complete\n await Promise.all(workers);\n\n // If there was an error, throw it\n if (hasError) {\n throw error;\n }\n\n return results;\n}\n"],"names":["parallel","limit","array","callback","signal","results","currentIndex","hasError","error","checkAbort","worker","index","err","workers","workerCount","i"],"mappings":"AA6BA,eAAsBA,EACpBC,GACAC,GACAC,GACAC,GACc;AACd,MAAIH,IAAQ;AACV,UAAM,IAAI,MAAM,0BAA0B;AAG5C,MAAIG,GAAQ;AACV,UAAM,IAAI,aAAa,WAAW,YAAY;AAGhD,QAAMC,IAAe,IAAI,MAAMH,EAAM,MAAM;AAC3C,MAAII,IAAe,GACfC,IAAW,IACXC;AAGJ,QAAMC,IAAa,MACbL,GAAQ,WACVG,IAAW,IACXC,IAAQ,IAAI,aAAa,WAAW,YAAY,GACzC,MAEF,IAIHE,IAAS,YAA2B;AACxC,WAAOJ,IAAeJ,EAAM,UAAU,CAACK,KACjC,CAAAE,OAD2C;AAK/C,YAAME,IAAQL;AAEd,UAAI;AACF,QAAAD,EAAQM,CAAK,IAAI,MAAMR,EAASD,EAAMS,CAAK,GAAGA,GAAOT,CAAK;AAAA,MAC5D,SAASU,GAAK;AACZ,QAAAL,IAAW,IACXC,IAAQI;AACR;AAAA,MACF;AAAA,IACF;AAAA,EACF,GAGMC,IAA2B,CAAA,GAC3BC,IAAc,KAAK,IAAIb,GAAOC,EAAM,MAAM;AAEhD,WAASa,IAAI,GAAGA,IAAID,GAAaC;AAC/B,IAAAF,EAAQ,KAAKH,GAAQ;AAOvB,MAHA,MAAM,QAAQ,IAAIG,CAAO,GAGrBN;AACF,UAAMC;AAGR,SAAOH;AACT;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../function/assert.cjs");function u(e){a.assert(e>=1,"Pool limit must be at least 1",{args:{limit:e},type:RangeError});let t=0;const n=[],r=()=>{n.length>0&&t<e&&n.shift()?.()};return async o=>{for(;t>=e;)await new Promise(s=>n.push(s));t++;try{return await o()}finally{t--,r()}}}exports.pool=u;
|
|
2
|
+
//# sourceMappingURL=pool.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pool.cjs","sources":["../../src/async/pool.ts"],"sourcesContent":["import { assert } from '../function/assert';\n\n/**\n * Creates a promise pool that limits the number of concurrent promises.\n * Useful for rate limiting API calls or controlling resource usage.\n *\n * @example\n * ```ts\n * const requestPool = pool(3);\n *\n * const results = await Promise.all([\n * requestPool(() => fetch('/api/1')),\n * requestPool(() => fetch('/api/2')),\n * requestPool(() => fetch('/api/3')),\n * requestPool(() => fetch('/api/4')), // Will wait for one of the above to finish\n * ]);\n * ```\n *\n * @param limit - Maximum number of concurrent promises\n * @returns Function that accepts a promise-returning function and executes it when a slot is available\n */\nexport function pool(limit: number): <T>(fn: () => Promise<T>) => Promise<T> {\n assert(limit >= 1, 'Pool limit must be at least 1', { args: { limit }, type: RangeError });\n\n let activeCount = 0;\n const queue: Array<() => void> = [];\n\n const dequeue = (): void => {\n if (queue.length > 0 && activeCount < limit) {\n const next = queue.shift();\n next?.();\n }\n };\n\n return async <T>(fn: () => Promise<T>): Promise<T> => {\n while (activeCount >= limit) {\n await new Promise<void>((resolve) => queue.push(resolve));\n }\n\n activeCount++;\n\n try {\n return await fn();\n } finally {\n activeCount--;\n dequeue();\n }\n };\n}\n"],"names":["pool","limit","assert","activeCount","queue","dequeue","fn","resolve"],"mappings":"0HAqBO,SAASA,EAAKC,EAAwD,CAC3EC,SAAOD,GAAS,EAAG,gCAAiC,CAAE,KAAM,CAAE,MAAAA,CAAA,EAAS,KAAM,WAAY,EAEzF,IAAIE,EAAc,EAClB,MAAMC,EAA2B,CAAA,EAE3BC,EAAU,IAAY,CACtBD,EAAM,OAAS,GAAKD,EAAcF,GACvBG,EAAM,MAAA,IACnB,CAEJ,EAEA,MAAO,OAAUE,GAAqC,CACpD,KAAOH,GAAeF,GACpB,MAAM,IAAI,QAAeM,GAAYH,EAAM,KAAKG,CAAO,CAAC,EAG1DJ,IAEA,GAAI,CACF,OAAO,MAAMG,EAAA,CACf,QAAA,CACEH,IACAE,EAAA,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { assert as s } from "../function/assert.js";
|
|
2
|
+
function c(e) {
|
|
3
|
+
s(e >= 1, "Pool limit must be at least 1", { args: { limit: e }, type: RangeError });
|
|
4
|
+
let t = 0;
|
|
5
|
+
const n = [], r = () => {
|
|
6
|
+
n.length > 0 && t < e && n.shift()?.();
|
|
7
|
+
};
|
|
8
|
+
return async (o) => {
|
|
9
|
+
for (; t >= e; )
|
|
10
|
+
await new Promise((a) => n.push(a));
|
|
11
|
+
t++;
|
|
12
|
+
try {
|
|
13
|
+
return await o();
|
|
14
|
+
} finally {
|
|
15
|
+
t--, r();
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export {
|
|
20
|
+
c as pool
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=pool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pool.js","sources":["../../src/async/pool.ts"],"sourcesContent":["import { assert } from '../function/assert';\n\n/**\n * Creates a promise pool that limits the number of concurrent promises.\n * Useful for rate limiting API calls or controlling resource usage.\n *\n * @example\n * ```ts\n * const requestPool = pool(3);\n *\n * const results = await Promise.all([\n * requestPool(() => fetch('/api/1')),\n * requestPool(() => fetch('/api/2')),\n * requestPool(() => fetch('/api/3')),\n * requestPool(() => fetch('/api/4')), // Will wait for one of the above to finish\n * ]);\n * ```\n *\n * @param limit - Maximum number of concurrent promises\n * @returns Function that accepts a promise-returning function and executes it when a slot is available\n */\nexport function pool(limit: number): <T>(fn: () => Promise<T>) => Promise<T> {\n assert(limit >= 1, 'Pool limit must be at least 1', { args: { limit }, type: RangeError });\n\n let activeCount = 0;\n const queue: Array<() => void> = [];\n\n const dequeue = (): void => {\n if (queue.length > 0 && activeCount < limit) {\n const next = queue.shift();\n next?.();\n }\n };\n\n return async <T>(fn: () => Promise<T>): Promise<T> => {\n while (activeCount >= limit) {\n await new Promise<void>((resolve) => queue.push(resolve));\n }\n\n activeCount++;\n\n try {\n return await fn();\n } finally {\n activeCount--;\n dequeue();\n }\n };\n}\n"],"names":["pool","limit","assert","activeCount","queue","dequeue","fn","resolve"],"mappings":";AAqBO,SAASA,EAAKC,GAAwD;AAC3E,EAAAC,EAAOD,KAAS,GAAG,iCAAiC,EAAE,MAAM,EAAE,OAAAA,EAAA,GAAS,MAAM,YAAY;AAEzF,MAAIE,IAAc;AAClB,QAAMC,IAA2B,CAAA,GAE3BC,IAAU,MAAY;AAC1B,IAAID,EAAM,SAAS,KAAKD,IAAcF,KACvBG,EAAM,MAAA,IACnB;AAAA,EAEJ;AAEA,SAAO,OAAUE,MAAqC;AACpD,WAAOH,KAAeF;AACpB,YAAM,IAAI,QAAc,CAACM,MAAYH,EAAM,KAAKG,CAAO,CAAC;AAG1D,IAAAJ;AAEA,QAAI;AACF,aAAO,MAAMG,EAAA;AAAA,IACf,UAAA;AACE,MAAAH,KACAE,EAAA;AAAA,IACF;AAAA,EACF;AACF;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"predict.cjs","sources":["../../src/async/predict.ts"],"sourcesContent":["/**\n * Creates a Promise that can be aborted using an AbortController.\n *\n * @example\n * ```ts\n * const slowFn = () => new Promise(resolve => setTimeout(() => resolve('slow'), 10000));\n * const fastFn = () => new Promise(resolve => setTimeout(() => resolve('fast'), 5000));\n *\n * predict(slowFn); // rejects after 7 seconds\n * predict(fastFn); // resolves with 'fast' after 5 seconds\n * ```\n *\n * @param fn - The function to execute, which receives an AbortSignal.\n * @param options - The options for the abortable function.\n * @param [options.signal] - The AbortSignal to use for aborting the Promise.\n * @param [options.timeout=7000] - The timeout in milliseconds after which the Promise will be aborted.\n *\n * @returns - A Promise that resolves with the result of the callback or rejects if aborted.\n */\nexport function predict<T>(\n fn: (signal: AbortSignal) => Promise<T>,\n options: { signal?: AbortSignal; timeout?: number } = {},\n): Promise<T> {\n const { signal, timeout = 7000 } = options;\n const abortSignal = signal ? AbortSignal.any([AbortSignal.timeout(timeout), signal]) : AbortSignal.timeout(timeout);\n\n return Promise.race([\n fn(abortSignal),\n new Promise<never>((_, reject) => {\n abortSignal.addEventListener('abort', () => reject(new Error('Operation aborted')), { once: true });\n }),\n ]);\n}\n"],"names":["predict","fn","options","signal","timeout","abortSignal","_","reject"],"mappings":"gFAmBO,SAASA,EACdC,EACAC,EAAsD,GAC1C,CACZ,KAAM,CAAE,OAAAC,EAAQ,QAAAC,EAAU,GAAA,EAASF,EAC7BG,EAAcF,EAAS,YAAY,IAAI,CAAC,YAAY,QAAQC,CAAO,EAAGD,CAAM,CAAC,EAAI,YAAY,QAAQC,CAAO,EAElH,OAAO,QAAQ,KAAK,CAClBH,EAAGI,CAAW,EACd,IAAI,QAAe,CAACC,EAAGC,IAAW,CAChCF,EAAY,iBAAiB,QAAS,IAAME,EAAO,IAAI,MAAM,mBAAmB,CAAC,EAAG,CAAE,KAAM,EAAA,CAAM,CACpG,CAAC,CAAA,CACF,CACH"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"predict.js","sources":["../../src/async/predict.ts"],"sourcesContent":["/**\n * Creates a Promise that can be aborted using an AbortController.\n *\n * @example\n * ```ts\n * const slowFn = () => new Promise(resolve => setTimeout(() => resolve('slow'), 10000));\n * const fastFn = () => new Promise(resolve => setTimeout(() => resolve('fast'), 5000));\n *\n * predict(slowFn); // rejects after 7 seconds\n * predict(fastFn); // resolves with 'fast' after 5 seconds\n * ```\n *\n * @param fn - The function to execute, which receives an AbortSignal.\n * @param options - The options for the abortable function.\n * @param [options.signal] - The AbortSignal to use for aborting the Promise.\n * @param [options.timeout=7000] - The timeout in milliseconds after which the Promise will be aborted.\n *\n * @returns - A Promise that resolves with the result of the callback or rejects if aborted.\n */\nexport function predict<T>(\n fn: (signal: AbortSignal) => Promise<T>,\n options: { signal?: AbortSignal; timeout?: number } = {},\n): Promise<T> {\n const { signal, timeout = 7000 } = options;\n const abortSignal = signal ? AbortSignal.any([AbortSignal.timeout(timeout), signal]) : AbortSignal.timeout(timeout);\n\n return Promise.race([\n fn(abortSignal),\n new Promise<never>((_, reject) => {\n abortSignal.addEventListener('abort', () => reject(new Error('Operation aborted')), { once: true });\n }),\n ]);\n}\n"],"names":["predict","fn","options","signal","timeout","abortSignal","_","reject"],"mappings":"AAmBO,SAASA,EACdC,GACAC,IAAsD,IAC1C;AACZ,QAAM,EAAE,QAAAC,GAAQ,SAAAC,IAAU,IAAA,IAASF,GAC7BG,IAAcF,IAAS,YAAY,IAAI,CAAC,YAAY,QAAQC,CAAO,GAAGD,CAAM,CAAC,IAAI,YAAY,QAAQC,CAAO;AAElH,SAAO,QAAQ,KAAK;AAAA,IAClBH,EAAGI,CAAW;AAAA,IACd,IAAI,QAAe,CAACC,GAAGC,MAAW;AAChC,MAAAF,EAAY,iBAAiB,SAAS,MAAME,EAAO,IAAI,MAAM,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAA,CAAM;AAAA,IACpG,CAAC;AAAA,EAAA,CACF;AACH;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("../function/assert.cjs");function g(o={}){const{concurrency:u=1}=o;a.assert(u>=1,"Concurrency must be at least 1",{args:{concurrency:u},type:RangeError});let n=0,r=null,l=null;const e=[],s=()=>{if(n<u&&e.length>0){const t=e.shift();n++,t.fn().then(t.resolve).catch(t.reject).finally(()=>{n--,s(),n===0&&e.length===0&&l&&(l(),r=null,l=null)})}};return{add:t=>new Promise((i,c)=>{e.push({fn:t,reject:c,resolve:i}),s()}),clear:()=>{e.length=0},onIdle:()=>n===0&&e.length===0?Promise.resolve():(r||(r=new Promise(t=>{l=t})),r),get pending(){return n},get size(){return e.length}}}exports.queue=g;
|
|
2
|
+
//# sourceMappingURL=queue.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue.cjs","sources":["../../src/async/queue.ts"],"sourcesContent":["import { assert } from '../function/assert';\n\n/**\n * Creates a promise queue that processes promises sequentially with optional concurrency limit.\n *\n * @example\n * ```ts\n * const requestQueue = queue({ concurrency: 2 });\n *\n * requestQueue.add(() => fetch('/api/1'));\n * requestQueue.add(() => fetch('/api/2'));\n * requestQueue.add(() => fetch('/api/3'));\n *\n * await requestQueue.onIdle(); // Wait for all tasks to complete\n * ```\n *\n * @param options - Queue configuration\n * @param options.concurrency - Maximum number of concurrent promises (default: 1)\n * @returns Queue instance with add, onIdle, and clear methods\n */\nexport function queue(options: { concurrency?: number } = {}) {\n const { concurrency = 1 } = options;\n\n assert(concurrency >= 1, 'Concurrency must be at least 1', {\n args: { concurrency },\n type: RangeError,\n });\n\n let activeCount = 0;\n let idlePromise: Promise<void> | null = null;\n let idleResolve: (() => void) | null = null;\n\n const queue: Array<{\n fn: () => Promise<unknown>;\n resolve: (value: unknown) => void;\n reject: (error: unknown) => void;\n }> = [];\n\n const next = (): void => {\n if (activeCount < concurrency && queue.length > 0) {\n const task = queue.shift()!;\n activeCount++;\n\n task\n .fn()\n .then(task.resolve)\n .catch(task.reject)\n .finally(() => {\n activeCount--;\n next();\n\n if (activeCount === 0 && queue.length === 0 && idleResolve) {\n idleResolve();\n idlePromise = null;\n idleResolve = null;\n }\n });\n }\n };\n\n return {\n /**\n * Adds a promise-returning function to the queue\n */\n add: <T>(fn: () => Promise<T>): Promise<T> => {\n return new Promise<T>((resolve, reject) => {\n queue.push({\n fn: fn as () => Promise<unknown>,\n reject,\n resolve: resolve as (value: unknown) => void,\n });\n next();\n });\n },\n\n /**\n * Clears all pending tasks from the queue\n */\n clear: (): void => {\n queue.length = 0;\n },\n\n /**\n * Returns a promise that resolves when the queue becomes idle\n */\n onIdle: (): Promise<void> => {\n if (activeCount === 0 && queue.length === 0) {\n return Promise.resolve();\n }\n\n if (!idlePromise) {\n idlePromise = new Promise<void>((resolve) => {\n idleResolve = resolve;\n });\n }\n\n return idlePromise;\n },\n\n /**\n * Returns the number of currently active promises\n */\n get pending(): number {\n return activeCount;\n },\n\n /**\n * Returns the current size of the queue\n */\n get size(): number {\n return queue.length;\n },\n };\n}\n"],"names":["queue","options","concurrency","assert","activeCount","idlePromise","idleResolve","next","task","fn","resolve","reject"],"mappings":"0HAoBO,SAASA,EAAMC,EAAoC,GAAI,CAC5D,KAAM,CAAE,YAAAC,EAAc,CAAA,EAAMD,EAE5BE,SAAOD,GAAe,EAAG,iCAAkC,CACzD,KAAM,CAAE,YAAAA,CAAA,EACR,KAAM,UAAA,CACP,EAED,IAAIE,EAAc,EACdC,EAAoC,KACpCC,EAAmC,KAEvC,MAAMN,EAID,CAAA,EAECO,EAAO,IAAY,CACvB,GAAIH,EAAcF,GAAeF,EAAM,OAAS,EAAG,CACjD,MAAMQ,EAAOR,EAAM,MAAA,EACnBI,IAEAI,EACG,GAAA,EACA,KAAKA,EAAK,OAAO,EACjB,MAAMA,EAAK,MAAM,EACjB,QAAQ,IAAM,CACbJ,IACAG,EAAA,EAEIH,IAAgB,GAAKJ,EAAM,SAAW,GAAKM,IAC7CA,EAAA,EACAD,EAAc,KACdC,EAAc,KAElB,CAAC,CACL,CACF,EAEA,MAAO,CAIL,IAASG,GACA,IAAI,QAAW,CAACC,EAASC,IAAW,CACzCX,EAAM,KAAK,CACT,GAAAS,EACA,OAAAE,EACA,QAAAD,CAAA,CACD,EACDH,EAAA,CACF,CAAC,EAMH,MAAO,IAAY,CACjBP,EAAM,OAAS,CACjB,EAKA,OAAQ,IACFI,IAAgB,GAAKJ,EAAM,SAAW,EACjC,QAAQ,QAAA,GAGZK,IACHA,EAAc,IAAI,QAAeK,GAAY,CAC3CJ,EAAcI,CAChB,CAAC,GAGIL,GAMT,IAAI,SAAkB,CACpB,OAAOD,CACT,EAKA,IAAI,MAAe,CACjB,OAAOJ,EAAM,MACf,CAAA,CAEJ"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { assert as a } from "../function/assert.js";
|
|
2
|
+
function f(u = {}) {
|
|
3
|
+
const { concurrency: o = 1 } = u;
|
|
4
|
+
a(o >= 1, "Concurrency must be at least 1", {
|
|
5
|
+
args: { concurrency: o },
|
|
6
|
+
type: RangeError
|
|
7
|
+
});
|
|
8
|
+
let t = 0, r = null, l = null;
|
|
9
|
+
const e = [], s = () => {
|
|
10
|
+
if (t < o && e.length > 0) {
|
|
11
|
+
const n = e.shift();
|
|
12
|
+
t++, n.fn().then(n.resolve).catch(n.reject).finally(() => {
|
|
13
|
+
t--, s(), t === 0 && e.length === 0 && l && (l(), r = null, l = null);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
/**
|
|
19
|
+
* Adds a promise-returning function to the queue
|
|
20
|
+
*/
|
|
21
|
+
add: (n) => new Promise((i, c) => {
|
|
22
|
+
e.push({
|
|
23
|
+
fn: n,
|
|
24
|
+
reject: c,
|
|
25
|
+
resolve: i
|
|
26
|
+
}), s();
|
|
27
|
+
}),
|
|
28
|
+
/**
|
|
29
|
+
* Clears all pending tasks from the queue
|
|
30
|
+
*/
|
|
31
|
+
clear: () => {
|
|
32
|
+
e.length = 0;
|
|
33
|
+
},
|
|
34
|
+
/**
|
|
35
|
+
* Returns a promise that resolves when the queue becomes idle
|
|
36
|
+
*/
|
|
37
|
+
onIdle: () => t === 0 && e.length === 0 ? Promise.resolve() : (r || (r = new Promise((n) => {
|
|
38
|
+
l = n;
|
|
39
|
+
})), r),
|
|
40
|
+
/**
|
|
41
|
+
* Returns the number of currently active promises
|
|
42
|
+
*/
|
|
43
|
+
get pending() {
|
|
44
|
+
return t;
|
|
45
|
+
},
|
|
46
|
+
/**
|
|
47
|
+
* Returns the current size of the queue
|
|
48
|
+
*/
|
|
49
|
+
get size() {
|
|
50
|
+
return e.length;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export {
|
|
55
|
+
f as queue
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=queue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue.js","sources":["../../src/async/queue.ts"],"sourcesContent":["import { assert } from '../function/assert';\n\n/**\n * Creates a promise queue that processes promises sequentially with optional concurrency limit.\n *\n * @example\n * ```ts\n * const requestQueue = queue({ concurrency: 2 });\n *\n * requestQueue.add(() => fetch('/api/1'));\n * requestQueue.add(() => fetch('/api/2'));\n * requestQueue.add(() => fetch('/api/3'));\n *\n * await requestQueue.onIdle(); // Wait for all tasks to complete\n * ```\n *\n * @param options - Queue configuration\n * @param options.concurrency - Maximum number of concurrent promises (default: 1)\n * @returns Queue instance with add, onIdle, and clear methods\n */\nexport function queue(options: { concurrency?: number } = {}) {\n const { concurrency = 1 } = options;\n\n assert(concurrency >= 1, 'Concurrency must be at least 1', {\n args: { concurrency },\n type: RangeError,\n });\n\n let activeCount = 0;\n let idlePromise: Promise<void> | null = null;\n let idleResolve: (() => void) | null = null;\n\n const queue: Array<{\n fn: () => Promise<unknown>;\n resolve: (value: unknown) => void;\n reject: (error: unknown) => void;\n }> = [];\n\n const next = (): void => {\n if (activeCount < concurrency && queue.length > 0) {\n const task = queue.shift()!;\n activeCount++;\n\n task\n .fn()\n .then(task.resolve)\n .catch(task.reject)\n .finally(() => {\n activeCount--;\n next();\n\n if (activeCount === 0 && queue.length === 0 && idleResolve) {\n idleResolve();\n idlePromise = null;\n idleResolve = null;\n }\n });\n }\n };\n\n return {\n /**\n * Adds a promise-returning function to the queue\n */\n add: <T>(fn: () => Promise<T>): Promise<T> => {\n return new Promise<T>((resolve, reject) => {\n queue.push({\n fn: fn as () => Promise<unknown>,\n reject,\n resolve: resolve as (value: unknown) => void,\n });\n next();\n });\n },\n\n /**\n * Clears all pending tasks from the queue\n */\n clear: (): void => {\n queue.length = 0;\n },\n\n /**\n * Returns a promise that resolves when the queue becomes idle\n */\n onIdle: (): Promise<void> => {\n if (activeCount === 0 && queue.length === 0) {\n return Promise.resolve();\n }\n\n if (!idlePromise) {\n idlePromise = new Promise<void>((resolve) => {\n idleResolve = resolve;\n });\n }\n\n return idlePromise;\n },\n\n /**\n * Returns the number of currently active promises\n */\n get pending(): number {\n return activeCount;\n },\n\n /**\n * Returns the current size of the queue\n */\n get size(): number {\n return queue.length;\n },\n };\n}\n"],"names":["queue","options","concurrency","assert","activeCount","idlePromise","idleResolve","next","task","fn","resolve","reject"],"mappings":";AAoBO,SAASA,EAAMC,IAAoC,IAAI;AAC5D,QAAM,EAAE,aAAAC,IAAc,EAAA,IAAMD;AAE5B,EAAAE,EAAOD,KAAe,GAAG,kCAAkC;AAAA,IACzD,MAAM,EAAE,aAAAA,EAAA;AAAA,IACR,MAAM;AAAA,EAAA,CACP;AAED,MAAIE,IAAc,GACdC,IAAoC,MACpCC,IAAmC;AAEvC,QAAMN,IAID,CAAA,GAECO,IAAO,MAAY;AACvB,QAAIH,IAAcF,KAAeF,EAAM,SAAS,GAAG;AACjD,YAAMQ,IAAOR,EAAM,MAAA;AACnB,MAAAI,KAEAI,EACG,GAAA,EACA,KAAKA,EAAK,OAAO,EACjB,MAAMA,EAAK,MAAM,EACjB,QAAQ,MAAM;AACb,QAAAJ,KACAG,EAAA,GAEIH,MAAgB,KAAKJ,EAAM,WAAW,KAAKM,MAC7CA,EAAA,GACAD,IAAc,MACdC,IAAc;AAAA,MAElB,CAAC;AAAA,IACL;AAAA,EACF;AAEA,SAAO;AAAA;AAAA;AAAA;AAAA,IAIL,KAAK,CAAIG,MACA,IAAI,QAAW,CAACC,GAASC,MAAW;AACzCX,MAAAA,EAAM,KAAK;AAAA,QACT,IAAAS;AAAA,QACA,QAAAE;AAAA,QACA,SAAAD;AAAA,MAAA,CACD,GACDH,EAAA;AAAA,IACF,CAAC;AAAA;AAAA;AAAA;AAAA,IAMH,OAAO,MAAY;AACjBP,MAAAA,EAAM,SAAS;AAAA,IACjB;AAAA;AAAA;AAAA;AAAA,IAKA,QAAQ,MACFI,MAAgB,KAAKJ,EAAM,WAAW,IACjC,QAAQ,QAAA,KAGZK,MACHA,IAAc,IAAI,QAAc,CAACK,MAAY;AAC3C,MAAAJ,IAAcI;AAAA,IAChB,CAAC,IAGIL;AAAA;AAAA;AAAA;AAAA,IAMT,IAAI,UAAkB;AACpB,aAAOD;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAKA,IAAI,OAAe;AACjB,aAAOJ,EAAM;AAAA,IACf;AAAA,EAAA;AAEJ;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"race.cjs","sources":["../../src/async/race.ts"],"sourcesContent":["/**\n * Race multiple promises but with a guaranteed minimum delay.\n * Useful for showing loading states for at least a minimum duration.\n *\n * @example\n * ```ts\n * // Show loading spinner for at least 500ms\n * const result = await race(\n * fetchData(),\n * 500\n * );\n *\n * // With multiple promises\n * const result = await race(\n * [fetch('/api/1'), fetch('/api/2')],\n * 1000\n * );\n * ```\n *\n * @param promises - Single promise or array of promises to race\n * @param minDelay - Minimum delay in milliseconds before resolving\n * @returns Promise that resolves with the first result after the minimum delay\n */\nexport async function race<T>(promises: Promise<T> | Promise<T>[], minDelay: number): Promise<T> {\n const promiseArray = Array.isArray(promises) ? promises : [promises];\n const minDelayPromise = new Promise<void>((resolve) => setTimeout(resolve, minDelay));\n\n const result = await Promise.race(promiseArray);\n await minDelayPromise;\n\n return result;\n}\n"],"names":["race","promises","minDelay","promiseArray","minDelayPromise","resolve","result"],"mappings":"gFAuBA,eAAsBA,EAAQC,EAAqCC,EAA8B,CAC/F,MAAMC,EAAe,MAAM,QAAQF,CAAQ,EAAIA,EAAW,CAACA,CAAQ,EAC7DG,EAAkB,IAAI,QAAeC,GAAY,WAAWA,EAASH,CAAQ,CAAC,EAE9EI,EAAS,MAAM,QAAQ,KAAKH,CAAY,EAC9C,aAAMC,EAECE,CACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"race.js","sources":["../../src/async/race.ts"],"sourcesContent":["/**\n * Race multiple promises but with a guaranteed minimum delay.\n * Useful for showing loading states for at least a minimum duration.\n *\n * @example\n * ```ts\n * // Show loading spinner for at least 500ms\n * const result = await race(\n * fetchData(),\n * 500\n * );\n *\n * // With multiple promises\n * const result = await race(\n * [fetch('/api/1'), fetch('/api/2')],\n * 1000\n * );\n * ```\n *\n * @param promises - Single promise or array of promises to race\n * @param minDelay - Minimum delay in milliseconds before resolving\n * @returns Promise that resolves with the first result after the minimum delay\n */\nexport async function race<T>(promises: Promise<T> | Promise<T>[], minDelay: number): Promise<T> {\n const promiseArray = Array.isArray(promises) ? promises : [promises];\n const minDelayPromise = new Promise<void>((resolve) => setTimeout(resolve, minDelay));\n\n const result = await Promise.race(promiseArray);\n await minDelayPromise;\n\n return result;\n}\n"],"names":["race","promises","minDelay","promiseArray","minDelayPromise","resolve","result"],"mappings":"AAuBA,eAAsBA,EAAQC,GAAqCC,GAA8B;AAC/F,QAAMC,IAAe,MAAM,QAAQF,CAAQ,IAAIA,IAAW,CAACA,CAAQ,GAC7DG,IAAkB,IAAI,QAAc,CAACC,MAAY,WAAWA,GAASH,CAAQ,CAAC,GAE9EI,IAAS,MAAM,QAAQ,KAAKH,CAAY;AAC9C,eAAMC,GAECE;AACT;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry.cjs","sources":["../../src/async/retry.ts"],"sourcesContent":["import { Logit } from '@vielzeug/logit';\nimport { sleep } from './sleep';\n\n/**\n * Retries an asynchronous function a specified number of times with delay and optional exponential backoff.\n *\n * @example\n * ```ts\n * retry(() => fetchData(), { times: 3, delay: 1000, backoff: 2, signal: abortSignal })\n * .then(result => console.log(result))\n * .catch(error => console.error(error));\n * ```\n *\n * @param fn - The asynchronous function to retry.\n * @param options - (optional) Options for retrying the function.\n * @param [options.times=3] - The number of retry attempts.\n * @param [options.delay=250] - The delay in milliseconds between retries.\n * @param [options.backoff=1] - Exponential backoff factor (default: 1 → no backoff).\n * @param [options.signal] - `AbortSignal` to allow canceling retries.\n *\n * @returns The result of the asynchronous function.\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n {\n times = 3,\n delay = 250,\n backoff = 1,\n signal,\n }: {\n times?: number;\n delay?: number;\n backoff?: number | ((attempt: number, delay: number) => number);\n signal?: AbortSignal;\n } = {},\n): Promise<T> {\n let currentDelay = delay;\n\n for (let attempt = 1; attempt <= times; attempt++) {\n if (signal?.aborted) {\n Logit.warn(`retry() -> Aborted after ${attempt - 1} attempts`);\n throw new Error('Retry aborted');\n }\n\n try {\n return await fn();\n } catch (err) {\n if (attempt === times) throw err;\n\n Logit.warn(`retry() -> ${err}, attempt ${attempt}/${times}, retrying in ${currentDelay}ms`);\n if (currentDelay > 0) await sleep(currentDelay);\n\n currentDelay = typeof backoff === 'function' ? backoff(attempt, currentDelay) : currentDelay * backoff;\n }\n }\n\n throw new Error('Retry failed unexpectedly');\n}\n"],"names":["retry","fn","times","delay","backoff","signal","currentDelay","attempt","Logit","err","sleep"],"mappings":"oJAsBA,eAAsBA,EACpBC,EACA,CACE,MAAAC,EAAQ,EACR,MAAAC,EAAQ,IACR,QAAAC,EAAU,EACV,OAAAC,CACF,EAKI,GACQ,CACZ,IAAIC,EAAeH,EAEnB,QAASI,EAAU,EAAGA,GAAWL,EAAOK,IAAW,CACjD,GAAIF,GAAQ,QACVG,MAAAA,EAAAA,MAAM,KAAK,4BAA4BD,EAAU,CAAC,WAAW,EACvD,IAAI,MAAM,eAAe,EAGjC,GAAI,CACF,OAAO,MAAMN,EAAA,CACf,OAASQ,EAAK,CACZ,GAAIF,IAAYL,EAAO,MAAMO,EAE7BD,EAAAA,MAAM,KAAK,cAAcC,CAAG,aAAaF,CAAO,IAAIL,CAAK,iBAAiBI,CAAY,IAAI,EACtFA,EAAe,GAAG,MAAMI,EAAAA,MAAMJ,CAAY,EAE9CA,EAAe,OAAOF,GAAY,WAAaA,EAAQG,EAASD,CAAY,EAAIA,EAAeF,CACjG,CACF,CAEA,MAAM,IAAI,MAAM,2BAA2B,CAC7C"}
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { Logit as n } from "../logit/dist/logit.js";
|
|
2
2
|
import { sleep as w } from "./sleep.js";
|
|
3
|
-
async function m(
|
|
3
|
+
async function m(i, {
|
|
4
4
|
times: e = 3,
|
|
5
|
-
delay:
|
|
5
|
+
delay: y = 250,
|
|
6
6
|
backoff: o = 1,
|
|
7
7
|
signal: p
|
|
8
8
|
} = {}) {
|
|
9
|
-
let r =
|
|
9
|
+
let r = y;
|
|
10
10
|
for (let t = 1; t <= e; t++) {
|
|
11
11
|
if (p?.aborted)
|
|
12
12
|
throw n.warn(`retry() -> Aborted after ${t - 1} attempts`), new Error("Retry aborted");
|
|
13
13
|
try {
|
|
14
|
-
return await
|
|
14
|
+
return await i();
|
|
15
15
|
} catch (a) {
|
|
16
16
|
if (t === e) throw a;
|
|
17
17
|
n.warn(`retry() -> ${a}, attempt ${t}/${e}, retrying in ${r}ms`), r > 0 && await w(r), r = typeof o == "function" ? o(t, r) : r * o;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry.js","sources":["../../src/async/retry.ts"],"sourcesContent":["import { Logit } from '@vielzeug/logit';\nimport { sleep } from './sleep';\n\n/**\n * Retries an asynchronous function a specified number of times with delay and optional exponential backoff.\n *\n * @example\n * ```ts\n * retry(() => fetchData(), { times: 3, delay: 1000, backoff: 2, signal: abortSignal })\n * .then(result => console.log(result))\n * .catch(error => console.error(error));\n * ```\n *\n * @param fn - The asynchronous function to retry.\n * @param options - (optional) Options for retrying the function.\n * @param [options.times=3] - The number of retry attempts.\n * @param [options.delay=250] - The delay in milliseconds between retries.\n * @param [options.backoff=1] - Exponential backoff factor (default: 1 → no backoff).\n * @param [options.signal] - `AbortSignal` to allow canceling retries.\n *\n * @returns The result of the asynchronous function.\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n {\n times = 3,\n delay = 250,\n backoff = 1,\n signal,\n }: {\n times?: number;\n delay?: number;\n backoff?: number | ((attempt: number, delay: number) => number);\n signal?: AbortSignal;\n } = {},\n): Promise<T> {\n let currentDelay = delay;\n\n for (let attempt = 1; attempt <= times; attempt++) {\n if (signal?.aborted) {\n Logit.warn(`retry() -> Aborted after ${attempt - 1} attempts`);\n throw new Error('Retry aborted');\n }\n\n try {\n return await fn();\n } catch (err) {\n if (attempt === times) throw err;\n\n Logit.warn(`retry() -> ${err}, attempt ${attempt}/${times}, retrying in ${currentDelay}ms`);\n if (currentDelay > 0) await sleep(currentDelay);\n\n currentDelay = typeof backoff === 'function' ? backoff(attempt, currentDelay) : currentDelay * backoff;\n }\n }\n\n throw new Error('Retry failed unexpectedly');\n}\n"],"names":["retry","fn","times","delay","backoff","signal","currentDelay","attempt","Logit","err","sleep"],"mappings":";;AAsBA,eAAsBA,EACpBC,GACA;AAAA,EACE,OAAAC,IAAQ;AAAA,EACR,OAAAC,IAAQ;AAAA,EACR,SAAAC,IAAU;AAAA,EACV,QAAAC;AACF,IAKI,IACQ;AACZ,MAAIC,IAAeH;AAEnB,WAASI,IAAU,GAAGA,KAAWL,GAAOK,KAAW;AACjD,QAAIF,GAAQ;AACVG,YAAAA,EAAM,KAAK,4BAA4BD,IAAU,CAAC,WAAW,GACvD,IAAI,MAAM,eAAe;AAGjC,QAAI;AACF,aAAO,MAAMN,EAAA;AAAA,IACf,SAASQ,GAAK;AACZ,UAAIF,MAAYL,EAAO,OAAMO;AAE7BD,MAAAA,EAAM,KAAK,cAAcC,CAAG,aAAaF,CAAO,IAAIL,CAAK,iBAAiBI,CAAY,IAAI,GACtFA,IAAe,KAAG,MAAMI,EAAMJ,CAAY,GAE9CA,IAAe,OAAOF,KAAY,aAAaA,EAAQG,GAASD,CAAY,IAAIA,IAAeF;AAAA,IACjG;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,2BAA2B;AAC7C;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../function/assert.cjs");async function s(e){return n.assert(typeof e=="number"&&e>=0&&Number.isFinite(e),"Timeout must be a non-negative finite number",{args:{timeout:e},type:TypeError}),new Promise(r=>setTimeout(r,e))}exports.sleep=s;
|
|
2
|
+
//# sourceMappingURL=sleep.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sleep.cjs","sources":["../../src/async/sleep.ts"],"sourcesContent":["import { assert } from '../function/assert';\n\n/**\n * Creates a Promise that resolves after a specified amount of time.\n *\n * @example\n * ```ts\n * sleep(1000).then(() => console.log('Hello, world!')); // logs 'Hello, world!' after 1 second\n * ```\n *\n * @param timeout - The number of milliseconds to wait before resolving the Promise.\n *\n * @returns A Promise that resolves after the specified time.\n *\n * @throws {TypeError} If timeout is not a non-negative number.\n */\nexport async function sleep(timeout: number): Promise<void> {\n assert(\n typeof timeout === 'number' && timeout >= 0 && Number.isFinite(timeout),\n 'Timeout must be a non-negative finite number',\n { args: { timeout }, type: TypeError },\n );\n return new Promise((resolve) => setTimeout(resolve, timeout));\n}\n"],"names":["sleep","timeout","assert","resolve"],"mappings":"0HAgBA,eAAsBA,EAAMC,EAAgC,CAC1DC,OAAAA,EAAAA,OACE,OAAOD,GAAY,UAAYA,GAAW,GAAK,OAAO,SAASA,CAAO,EACtE,+CACA,CAAE,KAAM,CAAE,QAAAA,CAAA,EAAW,KAAM,SAAA,CAAU,EAEhC,IAAI,QAASE,GAAY,WAAWA,EAASF,CAAO,CAAC,CAC9D"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sleep.js","sources":["../../src/async/sleep.ts"],"sourcesContent":["import { assert } from '../function/assert';\n\n/**\n * Creates a Promise that resolves after a specified amount of time.\n *\n * @example\n * ```ts\n * sleep(1000).then(() => console.log('Hello, world!')); // logs 'Hello, world!' after 1 second\n * ```\n *\n * @param timeout - The number of milliseconds to wait before resolving the Promise.\n *\n * @returns A Promise that resolves after the specified time.\n *\n * @throws {TypeError} If timeout is not a non-negative number.\n */\nexport async function sleep(timeout: number): Promise<void> {\n assert(\n typeof timeout === 'number' && timeout >= 0 && Number.isFinite(timeout),\n 'Timeout must be a non-negative finite number',\n { args: { timeout }, type: TypeError },\n );\n return new Promise((resolve) => setTimeout(resolve, timeout));\n}\n"],"names":["sleep","timeout","assert","resolve"],"mappings":";AAgBA,eAAsBA,EAAMC,GAAgC;AAC1D,SAAAC;AAAA,IACE,OAAOD,KAAY,YAAYA,KAAW,KAAK,OAAO,SAASA,CAAO;AAAA,IACtE;AAAA,IACA,EAAE,MAAM,EAAE,SAAAA,EAAA,GAAW,MAAM,UAAA;AAAA,EAAU,GAEhC,IAAI,QAAQ,CAACE,MAAY,WAAWA,GAASF,CAAO,CAAC;AAC9D;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});async function d(u,c={}){const{timeout:n=5e3,interval:l=100,signal:t}=c;if(t?.aborted)throw new DOMException("Aborted","AbortError");return new Promise((b,e)=>{const w=Date.now();let o=null;const r=()=>{o!==null&&(clearTimeout(o),o=null),t?.removeEventListener("abort",i)},i=()=>{r(),e(new DOMException("Aborted","AbortError"))},a=async()=>{try{if(t?.aborted){r(),e(new DOMException("Aborted","AbortError"));return}if(await u()){r(),b();return}if(Date.now()-w>=n){r(),e(new Error(`waitFor timed out after ${n}ms`));return}o=setTimeout(a,l)}catch(s){r(),e(s)}};t&&t.addEventListener("abort",i,{once:!0}),a()})}exports.waitFor=d;
|
|
2
|
+
//# sourceMappingURL=waitFor.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"waitFor.cjs","sources":["../../src/async/waitFor.ts"],"sourcesContent":["/**\n * Waits for a condition to become true by polling.\n * Useful for waiting for DOM elements, API states, or other conditions.\n *\n * @example\n * ```ts\n * // Wait for an element to appear\n * await waitFor(() => document.querySelector('#myElement') !== null);\n *\n * // Wait for API to be ready\n * await waitFor(\n * async () => {\n * const res = await fetch('/api/health');\n * return res.ok;\n * },\n * { timeout: 30000, interval: 1000 }\n * );\n * ```\n *\n * @param condition - Function that returns true when condition is met\n * @param options - Configuration options\n * @param options.timeout - Maximum time to wait in ms (default: 5000)\n * @param options.interval - Polling interval in ms (default: 100)\n * @param options.signal - AbortSignal to cancel waiting\n * @returns Promise that resolves when condition becomes true\n * @throws {Error} If timeout is reached\n * @throws {DOMException} If aborted via signal\n */\nexport async function waitFor(\n condition: () => boolean | Promise<boolean>,\n options: {\n timeout?: number;\n interval?: number;\n signal?: AbortSignal;\n } = {},\n): Promise<void> {\n const { timeout: timeoutMs = 5000, interval = 100, signal } = options;\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n return new Promise<void>((resolve, reject) => {\n const startTime = Date.now();\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let intervalId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (intervalId !== null) {\n clearTimeout(intervalId);\n intervalId = null;\n }\n signal?.removeEventListener('abort', onAbort);\n };\n\n const onAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const check = async () => {\n try {\n // Check if aborted\n if (signal?.aborted) {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n // Check condition\n const result = await condition();\n\n if (result) {\n cleanup();\n resolve();\n return;\n }\n\n // Check timeout\n if (Date.now() - startTime >= timeoutMs) {\n cleanup();\n reject(new Error(`waitFor timed out after ${timeoutMs}ms`));\n return;\n }\n\n // Schedule next check\n intervalId = setTimeout(check, interval);\n } catch (error) {\n // If the condition throws, clean up and reject\n cleanup();\n reject(error);\n }\n };\n\n // Set up abort listener\n if (signal) {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n\n // Start checking\n check();\n });\n}\n"],"names":["waitFor","condition","options","timeoutMs","interval","signal","resolve","reject","startTime","intervalId","cleanup","onAbort","check","error"],"mappings":"gFA4BA,eAAsBA,EACpBC,EACAC,EAII,GACW,CACf,KAAM,CAAE,QAASC,EAAY,IAAM,SAAAC,EAAW,IAAK,OAAAC,GAAWH,EAE9D,GAAIG,GAAQ,QACV,MAAM,IAAI,aAAa,UAAW,YAAY,EAGhD,OAAO,IAAI,QAAc,CAACC,EAASC,IAAW,CAC5C,MAAMC,EAAY,KAAK,IAAA,EAEvB,IAAIC,EAAmD,KAEvD,MAAMC,EAAU,IAAM,CAKhBD,IAAe,OACjB,aAAaA,CAAU,EACvBA,EAAa,MAEfJ,GAAQ,oBAAoB,QAASM,CAAO,CAC9C,EAEMA,EAAU,IAAM,CACpBD,EAAA,EACAH,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,CAClD,EAEMK,EAAQ,SAAY,CACxB,GAAI,CAEF,GAAIP,GAAQ,QAAS,CACnBK,EAAA,EACAH,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,MACF,CAKA,GAFe,MAAMN,EAAA,EAET,CACVS,EAAA,EACAJ,EAAA,EACA,MACF,CAGA,GAAI,KAAK,MAAQE,GAAaL,EAAW,CACvCO,EAAA,EACAH,EAAO,IAAI,MAAM,2BAA2BJ,CAAS,IAAI,CAAC,EAC1D,MACF,CAGAM,EAAa,WAAWG,EAAOR,CAAQ,CACzC,OAASS,EAAO,CAEdH,EAAA,EACAH,EAAOM,CAAK,CACd,CACF,EAGIR,GACFA,EAAO,iBAAiB,QAASM,EAAS,CAAE,KAAM,GAAM,EAI1DC,EAAA,CACF,CAAC,CACH"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
async function d(u, c = {}) {
|
|
2
|
+
const { timeout: n = 5e3, interval: l = 100, signal: t } = c;
|
|
3
|
+
if (t?.aborted)
|
|
4
|
+
throw new DOMException("Aborted", "AbortError");
|
|
5
|
+
return new Promise((b, e) => {
|
|
6
|
+
const w = Date.now();
|
|
7
|
+
let o = null;
|
|
8
|
+
const r = () => {
|
|
9
|
+
o !== null && (clearTimeout(o), o = null), t?.removeEventListener("abort", i);
|
|
10
|
+
}, i = () => {
|
|
11
|
+
r(), e(new DOMException("Aborted", "AbortError"));
|
|
12
|
+
}, a = async () => {
|
|
13
|
+
try {
|
|
14
|
+
if (t?.aborted) {
|
|
15
|
+
r(), e(new DOMException("Aborted", "AbortError"));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (await u()) {
|
|
19
|
+
r(), b();
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (Date.now() - w >= n) {
|
|
23
|
+
r(), e(new Error(`waitFor timed out after ${n}ms`));
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
o = setTimeout(a, l);
|
|
27
|
+
} catch (s) {
|
|
28
|
+
r(), e(s);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
t && t.addEventListener("abort", i, { once: !0 }), a();
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
d as waitFor
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=waitFor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"waitFor.js","sources":["../../src/async/waitFor.ts"],"sourcesContent":["/**\n * Waits for a condition to become true by polling.\n * Useful for waiting for DOM elements, API states, or other conditions.\n *\n * @example\n * ```ts\n * // Wait for an element to appear\n * await waitFor(() => document.querySelector('#myElement') !== null);\n *\n * // Wait for API to be ready\n * await waitFor(\n * async () => {\n * const res = await fetch('/api/health');\n * return res.ok;\n * },\n * { timeout: 30000, interval: 1000 }\n * );\n * ```\n *\n * @param condition - Function that returns true when condition is met\n * @param options - Configuration options\n * @param options.timeout - Maximum time to wait in ms (default: 5000)\n * @param options.interval - Polling interval in ms (default: 100)\n * @param options.signal - AbortSignal to cancel waiting\n * @returns Promise that resolves when condition becomes true\n * @throws {Error} If timeout is reached\n * @throws {DOMException} If aborted via signal\n */\nexport async function waitFor(\n condition: () => boolean | Promise<boolean>,\n options: {\n timeout?: number;\n interval?: number;\n signal?: AbortSignal;\n } = {},\n): Promise<void> {\n const { timeout: timeoutMs = 5000, interval = 100, signal } = options;\n\n if (signal?.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n\n return new Promise<void>((resolve, reject) => {\n const startTime = Date.now();\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let intervalId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (intervalId !== null) {\n clearTimeout(intervalId);\n intervalId = null;\n }\n signal?.removeEventListener('abort', onAbort);\n };\n\n const onAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const check = async () => {\n try {\n // Check if aborted\n if (signal?.aborted) {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n // Check condition\n const result = await condition();\n\n if (result) {\n cleanup();\n resolve();\n return;\n }\n\n // Check timeout\n if (Date.now() - startTime >= timeoutMs) {\n cleanup();\n reject(new Error(`waitFor timed out after ${timeoutMs}ms`));\n return;\n }\n\n // Schedule next check\n intervalId = setTimeout(check, interval);\n } catch (error) {\n // If the condition throws, clean up and reject\n cleanup();\n reject(error);\n }\n };\n\n // Set up abort listener\n if (signal) {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n\n // Start checking\n check();\n });\n}\n"],"names":["waitFor","condition","options","timeoutMs","interval","signal","resolve","reject","startTime","intervalId","cleanup","onAbort","check","error"],"mappings":"AA4BA,eAAsBA,EACpBC,GACAC,IAII,IACW;AACf,QAAM,EAAE,SAASC,IAAY,KAAM,UAAAC,IAAW,KAAK,QAAAC,MAAWH;AAE9D,MAAIG,GAAQ;AACV,UAAM,IAAI,aAAa,WAAW,YAAY;AAGhD,SAAO,IAAI,QAAc,CAACC,GAASC,MAAW;AAC5C,UAAMC,IAAY,KAAK,IAAA;AAEvB,QAAIC,IAAmD;AAEvD,UAAMC,IAAU,MAAM;AAKpB,MAAID,MAAe,SACjB,aAAaA,CAAU,GACvBA,IAAa,OAEfJ,GAAQ,oBAAoB,SAASM,CAAO;AAAA,IAC9C,GAEMA,IAAU,MAAM;AACpB,MAAAD,EAAA,GACAH,EAAO,IAAI,aAAa,WAAW,YAAY,CAAC;AAAA,IAClD,GAEMK,IAAQ,YAAY;AACxB,UAAI;AAEF,YAAIP,GAAQ,SAAS;AACnB,UAAAK,EAAA,GACAH,EAAO,IAAI,aAAa,WAAW,YAAY,CAAC;AAChD;AAAA,QACF;AAKA,YAFe,MAAMN,EAAA,GAET;AACV,UAAAS,EAAA,GACAJ,EAAA;AACA;AAAA,QACF;AAGA,YAAI,KAAK,QAAQE,KAAaL,GAAW;AACvC,UAAAO,EAAA,GACAH,EAAO,IAAI,MAAM,2BAA2BJ,CAAS,IAAI,CAAC;AAC1D;AAAA,QACF;AAGA,QAAAM,IAAa,WAAWG,GAAOR,CAAQ;AAAA,MACzC,SAASS,GAAO;AAEd,QAAAH,EAAA,GACAH,EAAOM,CAAK;AAAA,MACd;AAAA,IACF;AAGA,IAAIR,KACFA,EAAO,iBAAiB,SAASM,GAAS,EAAE,MAAM,IAAM,GAI1DC,EAAA;AAAA,EACF,CAAC;AACH;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expires.cjs","sources":["../../src/date/expires.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"expires.cjs","sources":["../../src/date/expires.ts"],"sourcesContent":["// #region Expires\nexport type Expires = 'EXPIRED' | 'SOON' | 'LATER' | 'NEVER' | 'UNKNOWN';\n// #endregion Expires\n\n/**\n * Determines the expiry status of a given date.\n *\n * @param date - The date to check, as a string or Date object.\n * @param days - Number of days before expiry to be considered \"SOON\" (default: 7).\n * @returns\n * - 'EXPIRED' if the date is in the past,\n * - 'SOON' if the date is within the next `days`,\n * - 'LATER' if the date is further in the future,\n * - 'NEVER' if the year is >= 9999,\n * - 'UNKNOWN' if the date is invalid.\n */\nexport function expires(date: string | Date, days = 7): Expires {\n const target = typeof date === 'string' ? new Date(date) : date;\n const targetTime = target.getTime();\n\n if (Number.isNaN(targetTime)) return 'UNKNOWN';\n if (target.getFullYear() >= 9999) return 'NEVER';\n\n const now = Date.now();\n const diff = targetTime - now;\n\n if (diff <= 0) return 'EXPIRED';\n if (diff <= days * 24 * 60 * 60 * 1000) return 'SOON';\n\n return 'LATER';\n}\n"],"names":["expires","date","days","target","targetTime","now","diff"],"mappings":"gFAgBO,SAASA,EAAQC,EAAqBC,EAAO,EAAY,CAC9D,MAAMC,EAAS,OAAOF,GAAS,SAAW,IAAI,KAAKA,CAAI,EAAIA,EACrDG,EAAaD,EAAO,QAAA,EAE1B,GAAI,OAAO,MAAMC,CAAU,EAAG,MAAO,UACrC,GAAID,EAAO,eAAiB,KAAM,MAAO,QAEzC,MAAME,EAAM,KAAK,IAAA,EACXC,EAAOF,EAAaC,EAE1B,OAAIC,GAAQ,EAAU,UAClBA,GAAQJ,EAAO,GAAK,GAAK,GAAK,IAAa,OAExC,OACT"}
|
package/dist/date/expires.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expires.js","sources":["../../src/date/expires.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"expires.js","sources":["../../src/date/expires.ts"],"sourcesContent":["// #region Expires\nexport type Expires = 'EXPIRED' | 'SOON' | 'LATER' | 'NEVER' | 'UNKNOWN';\n// #endregion Expires\n\n/**\n * Determines the expiry status of a given date.\n *\n * @param date - The date to check, as a string or Date object.\n * @param days - Number of days before expiry to be considered \"SOON\" (default: 7).\n * @returns\n * - 'EXPIRED' if the date is in the past,\n * - 'SOON' if the date is within the next `days`,\n * - 'LATER' if the date is further in the future,\n * - 'NEVER' if the year is >= 9999,\n * - 'UNKNOWN' if the date is invalid.\n */\nexport function expires(date: string | Date, days = 7): Expires {\n const target = typeof date === 'string' ? new Date(date) : date;\n const targetTime = target.getTime();\n\n if (Number.isNaN(targetTime)) return 'UNKNOWN';\n if (target.getFullYear() >= 9999) return 'NEVER';\n\n const now = Date.now();\n const diff = targetTime - now;\n\n if (diff <= 0) return 'EXPIRED';\n if (diff <= days * 24 * 60 * 60 * 1000) return 'SOON';\n\n return 'LATER';\n}\n"],"names":["expires","date","days","target","targetTime","now","diff"],"mappings":"AAgBO,SAASA,EAAQC,GAAqBC,IAAO,GAAY;AAC9D,QAAMC,IAAS,OAAOF,KAAS,WAAW,IAAI,KAAKA,CAAI,IAAIA,GACrDG,IAAaD,EAAO,QAAA;AAE1B,MAAI,OAAO,MAAMC,CAAU,EAAG,QAAO;AACrC,MAAID,EAAO,iBAAiB,KAAM,QAAO;AAEzC,QAAME,IAAM,KAAK,IAAA,GACXC,IAAOF,IAAaC;AAE1B,SAAIC,KAAQ,IAAU,YAClBA,KAAQJ,IAAO,KAAK,KAAK,KAAK,MAAa,SAExC;AACT;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interval.cjs","sources":["../../src/date/interval.ts"],"sourcesContent":["import { assert } from '../function/assert';\nimport { isDate } from '../typed/isDate';\n\ntype IntervalType = 'D' | 'W' | 'M' | 'MS' | 'ME' | 'Y' | 'YS' | 'YE';\ntype IntervalOptions = {\n interval?: IntervalType;\n steps?: number;\n latest?: boolean;\n};\n\n/**\n * Generates an array of dates between a start and end date, with a specified interval and step size.\n *\n * @example\n * ```ts\n * const options = { interval: 'D', steps: 1, latest: false };\n *\n * interval('2022-01-01', '2022-01-31', options); // Returns an array of dates for every day in January 2022\n * ```\n *\n * @param start - The start date (Date object or ISO string).\n * @param end - The end date (Date object or ISO string).\n * @param options - Options for an interval and steps.\n *\n * @returns An array of generated dates.\n */\nexport function interval(\n start: Date | string,\n end: Date | string,\n { interval = 'D', steps = 1, latest = false }: IntervalOptions = {},\n): Date[] {\n const startDate = new Date(start);\n const endDate = new Date(end);\n\n assert([isDate(startDate), isDate(endDate)], 'Invalid date format. Use a valid Date object or ISO string.', {\n args: { end, start },\n type: TypeError,\n });\n\n const dateArray: Date[] = [];\n let currentDate = new Date(incrementDate(startDate, interval, 0));\n\n while (currentDate <= endDate) {\n dateArray.push(currentDate);\n currentDate = new Date(incrementDate(currentDate, interval, steps));\n }\n\n if (latest && dateArray.length > 0 && dateArray[dateArray.length - 1] < endDate) {\n dateArray.push(endDate);\n }\n\n return dateArray;\n}\n\nfunction incrementDate(date: Date, interval: IntervalType, steps: number): Date {\n const year = date.getFullYear();\n const month = date.getMonth();\n const day = date.getDate();\n\n switch (interval) {\n case 'D':\n return new Date(Date.UTC(year, month, day + steps));\n case 'W':\n return new Date(Date.UTC(year, month, day + 7 * steps));\n case 'M':\n return new Date(Date.UTC(year, month + steps, day));\n case 'MS':\n return new Date(Date.UTC(year, month + steps, 1));\n case 'ME':\n return new Date(Date.UTC(year, month + steps + 1, 0));\n case 'Y':\n return new Date(Date.UTC(year + steps, month, day));\n case 'YS':\n return new Date(Date.UTC(year + steps, 0, 1));\n case 'YE':\n return new Date(Date.UTC(year + steps, 11, 31));\n }\n}\n"],"names":["interval","start","end","steps","latest","startDate","endDate","assert","isDate","dateArray","currentDate","incrementDate","date","year","month","day"],"mappings":"
|
|
1
|
+
{"version":3,"file":"interval.cjs","sources":["../../src/date/interval.ts"],"sourcesContent":["import { assert } from '../function/assert';\nimport { isDate } from '../typed/isDate';\n\n// #region IntervalTypes\ntype IntervalType = 'D' | 'W' | 'M' | 'MS' | 'ME' | 'Y' | 'YS' | 'YE';\ntype IntervalOptions = {\n interval?: IntervalType;\n steps?: number;\n latest?: boolean;\n};\n// #endregion IntervalTypes\n\n/**\n * Generates an array of dates between a start and end date, with a specified interval and step size.\n *\n * @example\n * ```ts\n * const options = { interval: 'D', steps: 1, latest: false };\n *\n * interval('2022-01-01', '2022-01-31', options); // Returns an array of dates for every day in January 2022\n * ```\n *\n * @param start - The start date (Date object or ISO string).\n * @param end - The end date (Date object or ISO string).\n * @param options - Options for an interval and steps.\n *\n * @returns An array of generated dates.\n */\nexport function interval(\n start: Date | string,\n end: Date | string,\n { interval = 'D', steps = 1, latest = false }: IntervalOptions = {},\n): Date[] {\n const startDate = new Date(start);\n const endDate = new Date(end);\n\n assert([isDate(startDate), isDate(endDate)], 'Invalid date format. Use a valid Date object or ISO string.', {\n args: { end, start },\n type: TypeError,\n });\n\n const dateArray: Date[] = [];\n let currentDate = new Date(incrementDate(startDate, interval, 0));\n\n while (currentDate <= endDate) {\n dateArray.push(currentDate);\n currentDate = new Date(incrementDate(currentDate, interval, steps));\n }\n\n if (latest && dateArray.length > 0 && dateArray[dateArray.length - 1] < endDate) {\n dateArray.push(endDate);\n }\n\n return dateArray;\n}\n\nfunction incrementDate(date: Date, interval: IntervalType, steps: number): Date {\n const year = date.getFullYear();\n const month = date.getMonth();\n const day = date.getDate();\n\n switch (interval) {\n case 'D':\n return new Date(Date.UTC(year, month, day + steps));\n case 'W':\n return new Date(Date.UTC(year, month, day + 7 * steps));\n case 'M':\n return new Date(Date.UTC(year, month + steps, day));\n case 'MS':\n return new Date(Date.UTC(year, month + steps, 1));\n case 'ME':\n return new Date(Date.UTC(year, month + steps + 1, 0));\n case 'Y':\n return new Date(Date.UTC(year + steps, month, day));\n case 'YS':\n return new Date(Date.UTC(year + steps, 0, 1));\n case 'YE':\n return new Date(Date.UTC(year + steps, 11, 31));\n }\n}\n"],"names":["interval","start","end","steps","latest","startDate","endDate","assert","isDate","dateArray","currentDate","incrementDate","date","year","month","day"],"mappings":"2JA4BO,SAASA,EACdC,EACAC,EACA,CAAE,SAAAF,EAAW,IAAK,MAAAG,EAAQ,EAAG,OAAAC,EAAS,EAAA,EAA2B,CAAA,EACzD,CACR,MAAMC,EAAY,IAAI,KAAKJ,CAAK,EAC1BK,EAAU,IAAI,KAAKJ,CAAG,EAE5BK,EAAAA,OAAO,CAACC,EAAAA,OAAOH,CAAS,EAAGG,EAAAA,OAAOF,CAAO,CAAC,EAAG,8DAA+D,CAC1G,KAAM,CAAE,IAAAJ,EAAK,MAAAD,CAAA,EACb,KAAM,SAAA,CACP,EAED,MAAMQ,EAAoB,CAAA,EAC1B,IAAIC,EAAc,IAAI,KAAKC,EAAcN,EAAWL,EAAU,CAAC,CAAC,EAEhE,KAAOU,GAAeJ,GACpBG,EAAU,KAAKC,CAAW,EAC1BA,EAAc,IAAI,KAAKC,EAAcD,EAAaV,EAAUG,CAAK,CAAC,EAGpE,OAAIC,GAAUK,EAAU,OAAS,GAAKA,EAAUA,EAAU,OAAS,CAAC,EAAIH,GACtEG,EAAU,KAAKH,CAAO,EAGjBG,CACT,CAEA,SAASE,EAAcC,EAAYZ,EAAwBG,EAAqB,CAC9E,MAAMU,EAAOD,EAAK,YAAA,EACZE,EAAQF,EAAK,SAAA,EACbG,EAAMH,EAAK,QAAA,EAEjB,OAAQZ,EAAAA,CACN,IAAK,IACH,OAAO,IAAI,KAAK,KAAK,IAAIa,EAAMC,EAAOC,EAAMZ,CAAK,CAAC,EACpD,IAAK,IACH,OAAO,IAAI,KAAK,KAAK,IAAIU,EAAMC,EAAOC,EAAM,EAAIZ,CAAK,CAAC,EACxD,IAAK,IACH,OAAO,IAAI,KAAK,KAAK,IAAIU,EAAMC,EAAQX,EAAOY,CAAG,CAAC,EACpD,IAAK,KACH,OAAO,IAAI,KAAK,KAAK,IAAIF,EAAMC,EAAQX,EAAO,CAAC,CAAC,EAClD,IAAK,KACH,OAAO,IAAI,KAAK,KAAK,IAAIU,EAAMC,EAAQX,EAAQ,EAAG,CAAC,CAAC,EACtD,IAAK,IACH,OAAO,IAAI,KAAK,KAAK,IAAIU,EAAOV,EAAOW,EAAOC,CAAG,CAAC,EACpD,IAAK,KACH,OAAO,IAAI,KAAK,KAAK,IAAIF,EAAOV,EAAO,EAAG,CAAC,CAAC,EAC9C,IAAK,KACH,OAAO,IAAI,KAAK,KAAK,IAAIU,EAAOV,EAAO,GAAI,EAAE,CAAC,CAAA,CAEpD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interval.js","sources":["../../src/date/interval.ts"],"sourcesContent":["import { assert } from '../function/assert';\nimport { isDate } from '../typed/isDate';\n\ntype IntervalType = 'D' | 'W' | 'M' | 'MS' | 'ME' | 'Y' | 'YS' | 'YE';\ntype IntervalOptions = {\n interval?: IntervalType;\n steps?: number;\n latest?: boolean;\n};\n\n/**\n * Generates an array of dates between a start and end date, with a specified interval and step size.\n *\n * @example\n * ```ts\n * const options = { interval: 'D', steps: 1, latest: false };\n *\n * interval('2022-01-01', '2022-01-31', options); // Returns an array of dates for every day in January 2022\n * ```\n *\n * @param start - The start date (Date object or ISO string).\n * @param end - The end date (Date object or ISO string).\n * @param options - Options for an interval and steps.\n *\n * @returns An array of generated dates.\n */\nexport function interval(\n start: Date | string,\n end: Date | string,\n { interval = 'D', steps = 1, latest = false }: IntervalOptions = {},\n): Date[] {\n const startDate = new Date(start);\n const endDate = new Date(end);\n\n assert([isDate(startDate), isDate(endDate)], 'Invalid date format. Use a valid Date object or ISO string.', {\n args: { end, start },\n type: TypeError,\n });\n\n const dateArray: Date[] = [];\n let currentDate = new Date(incrementDate(startDate, interval, 0));\n\n while (currentDate <= endDate) {\n dateArray.push(currentDate);\n currentDate = new Date(incrementDate(currentDate, interval, steps));\n }\n\n if (latest && dateArray.length > 0 && dateArray[dateArray.length - 1] < endDate) {\n dateArray.push(endDate);\n }\n\n return dateArray;\n}\n\nfunction incrementDate(date: Date, interval: IntervalType, steps: number): Date {\n const year = date.getFullYear();\n const month = date.getMonth();\n const day = date.getDate();\n\n switch (interval) {\n case 'D':\n return new Date(Date.UTC(year, month, day + steps));\n case 'W':\n return new Date(Date.UTC(year, month, day + 7 * steps));\n case 'M':\n return new Date(Date.UTC(year, month + steps, day));\n case 'MS':\n return new Date(Date.UTC(year, month + steps, 1));\n case 'ME':\n return new Date(Date.UTC(year, month + steps + 1, 0));\n case 'Y':\n return new Date(Date.UTC(year + steps, month, day));\n case 'YS':\n return new Date(Date.UTC(year + steps, 0, 1));\n case 'YE':\n return new Date(Date.UTC(year + steps, 11, 31));\n }\n}\n"],"names":["interval","start","end","steps","latest","startDate","endDate","assert","isDate","dateArray","currentDate","incrementDate","date","year","month","day"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"interval.js","sources":["../../src/date/interval.ts"],"sourcesContent":["import { assert } from '../function/assert';\nimport { isDate } from '../typed/isDate';\n\n// #region IntervalTypes\ntype IntervalType = 'D' | 'W' | 'M' | 'MS' | 'ME' | 'Y' | 'YS' | 'YE';\ntype IntervalOptions = {\n interval?: IntervalType;\n steps?: number;\n latest?: boolean;\n};\n// #endregion IntervalTypes\n\n/**\n * Generates an array of dates between a start and end date, with a specified interval and step size.\n *\n * @example\n * ```ts\n * const options = { interval: 'D', steps: 1, latest: false };\n *\n * interval('2022-01-01', '2022-01-31', options); // Returns an array of dates for every day in January 2022\n * ```\n *\n * @param start - The start date (Date object or ISO string).\n * @param end - The end date (Date object or ISO string).\n * @param options - Options for an interval and steps.\n *\n * @returns An array of generated dates.\n */\nexport function interval(\n start: Date | string,\n end: Date | string,\n { interval = 'D', steps = 1, latest = false }: IntervalOptions = {},\n): Date[] {\n const startDate = new Date(start);\n const endDate = new Date(end);\n\n assert([isDate(startDate), isDate(endDate)], 'Invalid date format. Use a valid Date object or ISO string.', {\n args: { end, start },\n type: TypeError,\n });\n\n const dateArray: Date[] = [];\n let currentDate = new Date(incrementDate(startDate, interval, 0));\n\n while (currentDate <= endDate) {\n dateArray.push(currentDate);\n currentDate = new Date(incrementDate(currentDate, interval, steps));\n }\n\n if (latest && dateArray.length > 0 && dateArray[dateArray.length - 1] < endDate) {\n dateArray.push(endDate);\n }\n\n return dateArray;\n}\n\nfunction incrementDate(date: Date, interval: IntervalType, steps: number): Date {\n const year = date.getFullYear();\n const month = date.getMonth();\n const day = date.getDate();\n\n switch (interval) {\n case 'D':\n return new Date(Date.UTC(year, month, day + steps));\n case 'W':\n return new Date(Date.UTC(year, month, day + 7 * steps));\n case 'M':\n return new Date(Date.UTC(year, month + steps, day));\n case 'MS':\n return new Date(Date.UTC(year, month + steps, 1));\n case 'ME':\n return new Date(Date.UTC(year, month + steps + 1, 0));\n case 'Y':\n return new Date(Date.UTC(year + steps, month, day));\n case 'YS':\n return new Date(Date.UTC(year + steps, 0, 1));\n case 'YE':\n return new Date(Date.UTC(year + steps, 11, 31));\n }\n}\n"],"names":["interval","start","end","steps","latest","startDate","endDate","assert","isDate","dateArray","currentDate","incrementDate","date","year","month","day"],"mappings":";;AA4BO,SAASA,EACdC,GACAC,GACA,EAAE,UAAAF,IAAW,KAAK,OAAAG,IAAQ,GAAG,QAAAC,IAAS,GAAA,IAA2B,CAAA,GACzD;AACR,QAAMC,IAAY,IAAI,KAAKJ,CAAK,GAC1BK,IAAU,IAAI,KAAKJ,CAAG;AAE5B,EAAAK,EAAO,CAACC,EAAOH,CAAS,GAAGG,EAAOF,CAAO,CAAC,GAAG,+DAA+D;AAAA,IAC1G,MAAM,EAAE,KAAAJ,GAAK,OAAAD,EAAA;AAAA,IACb,MAAM;AAAA,EAAA,CACP;AAED,QAAMQ,IAAoB,CAAA;AAC1B,MAAIC,IAAc,IAAI,KAAKC,EAAcN,GAAWL,GAAU,CAAC,CAAC;AAEhE,SAAOU,KAAeJ;AACpB,IAAAG,EAAU,KAAKC,CAAW,GAC1BA,IAAc,IAAI,KAAKC,EAAcD,GAAaV,GAAUG,CAAK,CAAC;AAGpE,SAAIC,KAAUK,EAAU,SAAS,KAAKA,EAAUA,EAAU,SAAS,CAAC,IAAIH,KACtEG,EAAU,KAAKH,CAAO,GAGjBG;AACT;AAEA,SAASE,EAAcC,GAAYZ,GAAwBG,GAAqB;AAC9E,QAAMU,IAAOD,EAAK,YAAA,GACZE,IAAQF,EAAK,SAAA,GACbG,IAAMH,EAAK,QAAA;AAEjB,UAAQZ,GAAAA;AAAAA,IACN,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIa,GAAMC,GAAOC,IAAMZ,CAAK,CAAC;AAAA,IACpD,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIU,GAAMC,GAAOC,IAAM,IAAIZ,CAAK,CAAC;AAAA,IACxD,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIU,GAAMC,IAAQX,GAAOY,CAAG,CAAC;AAAA,IACpD,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIF,GAAMC,IAAQX,GAAO,CAAC,CAAC;AAAA,IAClD,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIU,GAAMC,IAAQX,IAAQ,GAAG,CAAC,CAAC;AAAA,IACtD,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIU,IAAOV,GAAOW,GAAOC,CAAG,CAAC;AAAA,IACpD,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIF,IAAOV,GAAO,GAAG,CAAC,CAAC;AAAA,IAC9C,KAAK;AACH,aAAO,IAAI,KAAK,KAAK,IAAIU,IAAOV,GAAO,IAAI,EAAE,CAAC;AAAA,EAAA;AAEpD;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timeDiff.cjs","sources":["../../src/date/timeDiff.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"timeDiff.cjs","sources":["../../src/date/timeDiff.ts"],"sourcesContent":["// #region TimeDiffTypes\nexport type TimeUnit = 'YEAR' | 'MONTH' | 'WEEK' | 'DAY' | 'HOUR' | 'MINUTE' | 'SECOND' | 'INVALID_DATE';\nexport type TimeDirection = 'FUTURE' | 'PAST';\nexport type TimeResult = { unit: TimeUnit; value: number };\n// #endregion TimeDiffTypes\n\nlet defaultUnits: TimeUnit[] = ['YEAR', 'MONTH', 'WEEK', 'DAY', 'HOUR', 'MINUTE', 'SECOND'];\n\nconst MS_PER_SECOND = 1000;\nconst MS_PER_MINUTE = 60 * MS_PER_SECOND;\nconst MS_PER_HOUR = 60 * MS_PER_MINUTE;\nconst MS_PER_DAY = 24 * MS_PER_HOUR;\nconst MS_PER_WEEK = 7 * MS_PER_DAY;\nconst MS_PER_MONTH = 30 * MS_PER_DAY;\nconst MS_PER_YEAR = 365 * MS_PER_DAY;\n\nconst TIME_UNITS = [\n { ms: MS_PER_YEAR, unit: 'YEAR' as const },\n { ms: MS_PER_MONTH, unit: 'MONTH' as const },\n { ms: MS_PER_WEEK, unit: 'WEEK' as const },\n { ms: MS_PER_DAY, unit: 'DAY' as const },\n { ms: MS_PER_HOUR, unit: 'HOUR' as const },\n { ms: MS_PER_MINUTE, unit: 'MINUTE' as const },\n { ms: MS_PER_SECOND, unit: 'SECOND' as const },\n];\n\n/**\n * Calculates the remaining time until a target date.\n *\n * @example\n * ```ts\n * timeDiff(new Date(Date.now() + 1000 * 60 * 60 * 24 * 5)); // { value: 5, unit: 'DAY' }\n * timeDiff(new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), 'past'); // { value: 3, unit: 'DAY' }\n * timeDiff(new Date(Date.now() + 1000 * 60 * 60 * 24 * 31)); // { value: 1, unit: 'MONTH' }\n * timeDiff(new Date(Date.now() + 1000 * 60 * 60 * 24 * 365)); // { value: 1, unit: 'YEAR' }\n * ```\n *\n * @param a - The target date (Date object or ISO string).\n * @param b - The target date (Date object or ISO string).\n * @param allowedUnits - (optional) array of units to filter the result. If provided, only these units will be considered.\n *\n * @returns An object containing the remaining time and its unit ('DAY', 'HOUR', or 'MINUTE').\n */\nexport function timeDiff(\n a: Date | string,\n b: Date | string = new Date(),\n allowedUnits: TimeUnit[] = defaultUnits,\n): TimeResult {\n const aDate = typeof a === 'string' ? Date.parse(a) : a.getTime();\n const bDate = typeof b === 'string' ? Date.parse(b) : b.getTime();\n\n if (Number.isNaN(aDate) || Number.isNaN(bDate)) {\n return { unit: 'INVALID_DATE', value: 0 };\n }\n\n const units = TIME_UNITS.filter((u) => allowedUnits.includes(u.unit));\n const diff = Math.abs(aDate - bDate);\n const smallestUnit = units[units.length - 1]?.unit ?? 'SECOND';\n\n if (diff <= 0) {\n return { unit: smallestUnit, value: 0 };\n }\n\n // Find the largest unit that fits\n const bestUnit = units.find((u) => diff >= u.ms);\n\n if (bestUnit) {\n return { unit: bestUnit.unit, value: Math.floor(diff / bestUnit.ms) };\n }\n\n return { unit: smallestUnit, value: 0 };\n}\n\ntimeDiff.defaultUnits = (units: TimeUnit[]) => {\n defaultUnits = units;\n};\n"],"names":["defaultUnits","MS_PER_SECOND","MS_PER_MINUTE","MS_PER_HOUR","MS_PER_DAY","MS_PER_WEEK","MS_PER_MONTH","MS_PER_YEAR","TIME_UNITS","timeDiff","a","b","allowedUnits","aDate","bDate","units","u","diff","smallestUnit","bestUnit"],"mappings":"gFAMA,IAAIA,EAA2B,CAAC,OAAQ,QAAS,OAAQ,MAAO,OAAQ,SAAU,QAAQ,EAE1F,MAAMC,EAAgB,IAChBC,EAAgB,GAAKD,EACrBE,EAAc,GAAKD,EACnBE,EAAa,GAAKD,EAClBE,EAAc,EAAID,EAClBE,EAAe,GAAKF,EACpBG,EAAc,IAAMH,EAEpBI,EAAa,CACjB,CAAE,GAAID,EAAa,KAAM,MAAA,EACzB,CAAE,GAAID,EAAc,KAAM,OAAA,EAC1B,CAAE,GAAID,EAAa,KAAM,MAAA,EACzB,CAAE,GAAID,EAAY,KAAM,KAAA,EACxB,CAAE,GAAID,EAAa,KAAM,MAAA,EACzB,CAAE,GAAID,EAAe,KAAM,QAAA,EAC3B,CAAE,GAAID,EAAe,KAAM,QAAA,CAC7B,EAmBO,SAASQ,EACdC,EACAC,MAAuB,KACvBC,EAA2BZ,EACf,CACZ,MAAMa,EAAQ,OAAOH,GAAM,SAAW,KAAK,MAAMA,CAAC,EAAIA,EAAE,QAAA,EAClDI,EAAQ,OAAOH,GAAM,SAAW,KAAK,MAAMA,CAAC,EAAIA,EAAE,QAAA,EAExD,GAAI,OAAO,MAAME,CAAK,GAAK,OAAO,MAAMC,CAAK,EAC3C,MAAO,CAAE,KAAM,eAAgB,MAAO,CAAA,EAGxC,MAAMC,EAAQP,EAAW,OAAQQ,GAAMJ,EAAa,SAASI,EAAE,IAAI,CAAC,EAC9DC,EAAO,KAAK,IAAIJ,EAAQC,CAAK,EAC7BI,EAAeH,EAAMA,EAAM,OAAS,CAAC,GAAG,MAAQ,SAEtD,GAAIE,GAAQ,EACV,MAAO,CAAE,KAAMC,EAAc,MAAO,CAAA,EAItC,MAAMC,EAAWJ,EAAM,KAAMC,GAAMC,GAAQD,EAAE,EAAE,EAE/C,OAAIG,EACK,CAAE,KAAMA,EAAS,KAAM,MAAO,KAAK,MAAMF,EAAOE,EAAS,EAAE,CAAA,EAG7D,CAAE,KAAMD,EAAc,MAAO,CAAA,CACtC,CAEAT,EAAS,aAAgBM,GAAsB,CAC7Cf,EAAee,CACjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timeDiff.js","sources":["../../src/date/timeDiff.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"timeDiff.js","sources":["../../src/date/timeDiff.ts"],"sourcesContent":["// #region TimeDiffTypes\nexport type TimeUnit = 'YEAR' | 'MONTH' | 'WEEK' | 'DAY' | 'HOUR' | 'MINUTE' | 'SECOND' | 'INVALID_DATE';\nexport type TimeDirection = 'FUTURE' | 'PAST';\nexport type TimeResult = { unit: TimeUnit; value: number };\n// #endregion TimeDiffTypes\n\nlet defaultUnits: TimeUnit[] = ['YEAR', 'MONTH', 'WEEK', 'DAY', 'HOUR', 'MINUTE', 'SECOND'];\n\nconst MS_PER_SECOND = 1000;\nconst MS_PER_MINUTE = 60 * MS_PER_SECOND;\nconst MS_PER_HOUR = 60 * MS_PER_MINUTE;\nconst MS_PER_DAY = 24 * MS_PER_HOUR;\nconst MS_PER_WEEK = 7 * MS_PER_DAY;\nconst MS_PER_MONTH = 30 * MS_PER_DAY;\nconst MS_PER_YEAR = 365 * MS_PER_DAY;\n\nconst TIME_UNITS = [\n { ms: MS_PER_YEAR, unit: 'YEAR' as const },\n { ms: MS_PER_MONTH, unit: 'MONTH' as const },\n { ms: MS_PER_WEEK, unit: 'WEEK' as const },\n { ms: MS_PER_DAY, unit: 'DAY' as const },\n { ms: MS_PER_HOUR, unit: 'HOUR' as const },\n { ms: MS_PER_MINUTE, unit: 'MINUTE' as const },\n { ms: MS_PER_SECOND, unit: 'SECOND' as const },\n];\n\n/**\n * Calculates the remaining time until a target date.\n *\n * @example\n * ```ts\n * timeDiff(new Date(Date.now() + 1000 * 60 * 60 * 24 * 5)); // { value: 5, unit: 'DAY' }\n * timeDiff(new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), 'past'); // { value: 3, unit: 'DAY' }\n * timeDiff(new Date(Date.now() + 1000 * 60 * 60 * 24 * 31)); // { value: 1, unit: 'MONTH' }\n * timeDiff(new Date(Date.now() + 1000 * 60 * 60 * 24 * 365)); // { value: 1, unit: 'YEAR' }\n * ```\n *\n * @param a - The target date (Date object or ISO string).\n * @param b - The target date (Date object or ISO string).\n * @param allowedUnits - (optional) array of units to filter the result. If provided, only these units will be considered.\n *\n * @returns An object containing the remaining time and its unit ('DAY', 'HOUR', or 'MINUTE').\n */\nexport function timeDiff(\n a: Date | string,\n b: Date | string = new Date(),\n allowedUnits: TimeUnit[] = defaultUnits,\n): TimeResult {\n const aDate = typeof a === 'string' ? Date.parse(a) : a.getTime();\n const bDate = typeof b === 'string' ? Date.parse(b) : b.getTime();\n\n if (Number.isNaN(aDate) || Number.isNaN(bDate)) {\n return { unit: 'INVALID_DATE', value: 0 };\n }\n\n const units = TIME_UNITS.filter((u) => allowedUnits.includes(u.unit));\n const diff = Math.abs(aDate - bDate);\n const smallestUnit = units[units.length - 1]?.unit ?? 'SECOND';\n\n if (diff <= 0) {\n return { unit: smallestUnit, value: 0 };\n }\n\n // Find the largest unit that fits\n const bestUnit = units.find((u) => diff >= u.ms);\n\n if (bestUnit) {\n return { unit: bestUnit.unit, value: Math.floor(diff / bestUnit.ms) };\n }\n\n return { unit: smallestUnit, value: 0 };\n}\n\ntimeDiff.defaultUnits = (units: TimeUnit[]) => {\n defaultUnits = units;\n};\n"],"names":["defaultUnits","TIME_UNITS","timeDiff","a","b","allowedUnits","aDate","bDate","units","u","diff","smallestUnit","bestUnit"],"mappings":"AAMA,IAAIA,IAA2B,CAAC,QAAQ,SAAS,QAAQ,OAAO,QAAQ,UAAU,QAAQ;AAU1F,MAAMC,IAAa;AAAA,EACjB,EAAE,IAAI,SAAa,MAAM,OAAA;AAAA,EACzB,EAAE,IAAI,QAAc,MAAM,QAAA;AAAA,EAC1B,EAAE,IAAI,QAAa,MAAM,OAAA;AAAA,EACzB,EAAE,IAAI,OAAY,MAAM,MAAA;AAAA,EACxB,EAAE,IAAI,MAAa,MAAM,OAAA;AAAA,EACzB,EAAE,IAAI,KAAe,MAAM,SAAA;AAAA,EAC3B,EAAE,IAAI,KAAe,MAAM,SAAA;AAC7B;AAmBO,SAASC,EACdC,GACAC,wBAAuB,KAAA,GACvBC,IAA2BL,GACf;AACZ,QAAMM,IAAQ,OAAOH,KAAM,WAAW,KAAK,MAAMA,CAAC,IAAIA,EAAE,QAAA,GAClDI,IAAQ,OAAOH,KAAM,WAAW,KAAK,MAAMA,CAAC,IAAIA,EAAE,QAAA;AAExD,MAAI,OAAO,MAAME,CAAK,KAAK,OAAO,MAAMC,CAAK;AAC3C,WAAO,EAAE,MAAM,gBAAgB,OAAO,EAAA;AAGxC,QAAMC,IAAQP,EAAW,OAAO,CAACQ,MAAMJ,EAAa,SAASI,EAAE,IAAI,CAAC,GAC9DC,IAAO,KAAK,IAAIJ,IAAQC,CAAK,GAC7BI,IAAeH,EAAMA,EAAM,SAAS,CAAC,GAAG,QAAQ;AAEtD,MAAIE,KAAQ;AACV,WAAO,EAAE,MAAMC,GAAc,OAAO,EAAA;AAItC,QAAMC,IAAWJ,EAAM,KAAK,CAACC,MAAMC,KAAQD,EAAE,EAAE;AAE/C,SAAIG,IACK,EAAE,MAAMA,EAAS,MAAM,OAAO,KAAK,MAAMF,IAAOE,EAAS,EAAE,EAAA,IAG7D,EAAE,MAAMD,GAAc,OAAO,EAAA;AACtC;AAEAT,EAAS,eAAe,CAACM,MAAsB;AAC7C,EAAAR,IAAeQ;AACjB;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memo.cjs","sources":["../../src/function/memo.ts"],"sourcesContent":["/** biome-ignore-all lint/suspicious/noExplicitAny: - */\nimport type { Fn } from '../types';\n\ntype MemoizeOptions<T extends Fn> = {\n ttl?: number; // Time-to-live in milliseconds\n maxSize?: number; // Maximum number of items in cache\n resolver?: (...args: Parameters<T>) => string; // Custom key generator\n};\n\ntype CacheEntry<T extends Fn> = {\n value: ReturnType<T>;\n timestamp: number;\n};\n\n/**\n * Creates a function that memorizes the result of the provided function.\n * Supports expiration (TTL) and limited cache size (LRU).\n *\n * @example\n * ```ts\n * const add = (x, y) => x + y;\n * const memoizedAdd = memo(add, { ttl: 5000, maxSize: 10 });\n *\n * memoizedAdd(1, 2); // 3 (caches the result)\n * memoizedAdd(1, 2); // 3 (from cache)\n * ```\n *\n * @param fn - The function to memorize.\n * @param options - Memoization options.\n * @param [options.ttl] - (optional) time-to-live (TTL) for cache expiration (in milliseconds).\n * @param [options.maxSize] - (optional) maximum cache size (LRU eviction).\n * @param [options.resolver] - (optional) custom function to resolve the cache key.\n *\n * @returns A new function that memorizes the input function.\n */\nexport function memo<T extends Fn>(\n fn: T,\n { ttl, maxSize, resolver }: MemoizeOptions<T> = {},\n): (...args: Parameters<T>) => ReturnType<T> {\n const cache = new Map<string, CacheEntry<T>>();\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: -\n const keyGen = (args: Parameters<T>): string => {\n if (resolver) return resolver(...args);\n if (args.length === 0) return '__empty__';\n if (args.length === 1) {\n const arg = args[0];\n const argType = typeof arg;\n if (argType === 'string' || argType === 'number' || argType === 'boolean') {\n return `${argType}:${arg}`;\n }\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n }\n return JSON.stringify(args);\n };\n\n return (...args: Parameters<T>): ReturnType<T> => {\n const key = keyGen(args);\n const now = Date.now();\n const cached = cache.get(key);\n\n if (cached && (!ttl || now - cached.timestamp < ttl)) {\n cache.delete(key);\n cache.set(key, cached); // Move to end (most recently used)\n return cached.value;\n }\n\n const result = fn(...args);\n cache.set(key, { timestamp: now, value: result });\n\n if (maxSize && cache.size > maxSize) {\n cache.delete(cache.keys().next().value!); // Remove least recently used\n }\n\n return result;\n };\n}\n"],"names":["memo","fn","ttl","maxSize","resolver","cache","keyGen","args","arg","argType","key","now","cached","result"],"mappings":"
|
|
1
|
+
{"version":3,"file":"memo.cjs","sources":["../../src/function/memo.ts"],"sourcesContent":["/** biome-ignore-all lint/suspicious/noExplicitAny: - */\nimport type { Fn } from '../types';\n\n// #region MemoizeOptions\ntype MemoizeOptions<T extends Fn> = {\n ttl?: number; // Time-to-live in milliseconds\n maxSize?: number; // Maximum number of items in cache\n resolver?: (...args: Parameters<T>) => string; // Custom key generator\n};\n// #endregion MemoizeOptions\n\ntype CacheEntry<T extends Fn> = {\n value: ReturnType<T>;\n timestamp: number;\n};\n\n/**\n * Creates a function that memorizes the result of the provided function.\n * Supports expiration (TTL) and limited cache size (LRU).\n *\n * @example\n * ```ts\n * const add = (x, y) => x + y;\n * const memoizedAdd = memo(add, { ttl: 5000, maxSize: 10 });\n *\n * memoizedAdd(1, 2); // 3 (caches the result)\n * memoizedAdd(1, 2); // 3 (from cache)\n * ```\n *\n * @param fn - The function to memorize.\n * @param options - Memoization options.\n * @param [options.ttl] - (optional) time-to-live (TTL) for cache expiration (in milliseconds).\n * @param [options.maxSize] - (optional) maximum cache size (LRU eviction).\n * @param [options.resolver] - (optional) custom function to resolve the cache key.\n *\n * @returns A new function that memorizes the input function.\n */\nexport function memo<T extends Fn>(\n fn: T,\n { ttl, maxSize, resolver }: MemoizeOptions<T> = {},\n): (...args: Parameters<T>) => ReturnType<T> {\n const cache = new Map<string, CacheEntry<T>>();\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: -\n const keyGen = (args: Parameters<T>): string => {\n if (resolver) return resolver(...args);\n if (args.length === 0) return '__empty__';\n if (args.length === 1) {\n const arg = args[0];\n const argType = typeof arg;\n if (argType === 'string' || argType === 'number' || argType === 'boolean') {\n return `${argType}:${arg}`;\n }\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n }\n return JSON.stringify(args);\n };\n\n return (...args: Parameters<T>): ReturnType<T> => {\n const key = keyGen(args);\n const now = Date.now();\n const cached = cache.get(key);\n\n if (cached && (!ttl || now - cached.timestamp < ttl)) {\n cache.delete(key);\n cache.set(key, cached); // Move to end (most recently used)\n return cached.value;\n }\n\n const result = fn(...args);\n cache.set(key, { timestamp: now, value: result });\n\n if (maxSize && cache.size > maxSize) {\n cache.delete(cache.keys().next().value!); // Remove least recently used\n }\n\n return result;\n };\n}\n"],"names":["memo","fn","ttl","maxSize","resolver","cache","keyGen","args","arg","argType","key","now","cached","result"],"mappings":"gFAqCO,SAASA,EACdC,EACA,CAAE,IAAAC,EAAK,QAAAC,EAAS,SAAAC,CAAA,EAAgC,GACL,CAC3C,MAAMC,MAAY,IAGZC,EAAUC,GAAgC,CAC9C,GAAIH,EAAU,OAAOA,EAAS,GAAGG,CAAI,EACrC,GAAIA,EAAK,SAAW,EAAG,MAAO,YAC9B,GAAIA,EAAK,SAAW,EAAG,CACrB,MAAMC,EAAMD,EAAK,CAAC,EACZE,EAAU,OAAOD,EACvB,GAAIC,IAAY,UAAYA,IAAY,UAAYA,IAAY,UAC9D,MAAO,GAAGA,CAAO,IAAID,CAAG,GAE1B,GAAIA,IAAQ,KAAM,MAAO,OACzB,GAAIA,IAAQ,OAAW,MAAO,WAChC,CACA,OAAO,KAAK,UAAUD,CAAI,CAC5B,EAEA,MAAO,IAAIA,IAAuC,CAChD,MAAMG,EAAMJ,EAAOC,CAAI,EACjBI,EAAM,KAAK,IAAA,EACXC,EAASP,EAAM,IAAIK,CAAG,EAE5B,GAAIE,IAAW,CAACV,GAAOS,EAAMC,EAAO,UAAYV,GAC9C,OAAAG,EAAM,OAAOK,CAAG,EAChBL,EAAM,IAAIK,EAAKE,CAAM,EACdA,EAAO,MAGhB,MAAMC,EAASZ,EAAG,GAAGM,CAAI,EACzB,OAAAF,EAAM,IAAIK,EAAK,CAAE,UAAWC,EAAK,MAAOE,EAAQ,EAE5CV,GAAWE,EAAM,KAAOF,GAC1BE,EAAM,OAAOA,EAAM,KAAA,EAAO,KAAA,EAAO,KAAM,EAGlCQ,CACT,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memo.js","sources":["../../src/function/memo.ts"],"sourcesContent":["/** biome-ignore-all lint/suspicious/noExplicitAny: - */\nimport type { Fn } from '../types';\n\ntype MemoizeOptions<T extends Fn> = {\n ttl?: number; // Time-to-live in milliseconds\n maxSize?: number; // Maximum number of items in cache\n resolver?: (...args: Parameters<T>) => string; // Custom key generator\n};\n\ntype CacheEntry<T extends Fn> = {\n value: ReturnType<T>;\n timestamp: number;\n};\n\n/**\n * Creates a function that memorizes the result of the provided function.\n * Supports expiration (TTL) and limited cache size (LRU).\n *\n * @example\n * ```ts\n * const add = (x, y) => x + y;\n * const memoizedAdd = memo(add, { ttl: 5000, maxSize: 10 });\n *\n * memoizedAdd(1, 2); // 3 (caches the result)\n * memoizedAdd(1, 2); // 3 (from cache)\n * ```\n *\n * @param fn - The function to memorize.\n * @param options - Memoization options.\n * @param [options.ttl] - (optional) time-to-live (TTL) for cache expiration (in milliseconds).\n * @param [options.maxSize] - (optional) maximum cache size (LRU eviction).\n * @param [options.resolver] - (optional) custom function to resolve the cache key.\n *\n * @returns A new function that memorizes the input function.\n */\nexport function memo<T extends Fn>(\n fn: T,\n { ttl, maxSize, resolver }: MemoizeOptions<T> = {},\n): (...args: Parameters<T>) => ReturnType<T> {\n const cache = new Map<string, CacheEntry<T>>();\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: -\n const keyGen = (args: Parameters<T>): string => {\n if (resolver) return resolver(...args);\n if (args.length === 0) return '__empty__';\n if (args.length === 1) {\n const arg = args[0];\n const argType = typeof arg;\n if (argType === 'string' || argType === 'number' || argType === 'boolean') {\n return `${argType}:${arg}`;\n }\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n }\n return JSON.stringify(args);\n };\n\n return (...args: Parameters<T>): ReturnType<T> => {\n const key = keyGen(args);\n const now = Date.now();\n const cached = cache.get(key);\n\n if (cached && (!ttl || now - cached.timestamp < ttl)) {\n cache.delete(key);\n cache.set(key, cached); // Move to end (most recently used)\n return cached.value;\n }\n\n const result = fn(...args);\n cache.set(key, { timestamp: now, value: result });\n\n if (maxSize && cache.size > maxSize) {\n cache.delete(cache.keys().next().value!); // Remove least recently used\n }\n\n return result;\n };\n}\n"],"names":["memo","fn","ttl","maxSize","resolver","cache","keyGen","args","arg","argType","key","now","cached","result"],"mappings":"
|
|
1
|
+
{"version":3,"file":"memo.js","sources":["../../src/function/memo.ts"],"sourcesContent":["/** biome-ignore-all lint/suspicious/noExplicitAny: - */\nimport type { Fn } from '../types';\n\n// #region MemoizeOptions\ntype MemoizeOptions<T extends Fn> = {\n ttl?: number; // Time-to-live in milliseconds\n maxSize?: number; // Maximum number of items in cache\n resolver?: (...args: Parameters<T>) => string; // Custom key generator\n};\n// #endregion MemoizeOptions\n\ntype CacheEntry<T extends Fn> = {\n value: ReturnType<T>;\n timestamp: number;\n};\n\n/**\n * Creates a function that memorizes the result of the provided function.\n * Supports expiration (TTL) and limited cache size (LRU).\n *\n * @example\n * ```ts\n * const add = (x, y) => x + y;\n * const memoizedAdd = memo(add, { ttl: 5000, maxSize: 10 });\n *\n * memoizedAdd(1, 2); // 3 (caches the result)\n * memoizedAdd(1, 2); // 3 (from cache)\n * ```\n *\n * @param fn - The function to memorize.\n * @param options - Memoization options.\n * @param [options.ttl] - (optional) time-to-live (TTL) for cache expiration (in milliseconds).\n * @param [options.maxSize] - (optional) maximum cache size (LRU eviction).\n * @param [options.resolver] - (optional) custom function to resolve the cache key.\n *\n * @returns A new function that memorizes the input function.\n */\nexport function memo<T extends Fn>(\n fn: T,\n { ttl, maxSize, resolver }: MemoizeOptions<T> = {},\n): (...args: Parameters<T>) => ReturnType<T> {\n const cache = new Map<string, CacheEntry<T>>();\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: -\n const keyGen = (args: Parameters<T>): string => {\n if (resolver) return resolver(...args);\n if (args.length === 0) return '__empty__';\n if (args.length === 1) {\n const arg = args[0];\n const argType = typeof arg;\n if (argType === 'string' || argType === 'number' || argType === 'boolean') {\n return `${argType}:${arg}`;\n }\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n }\n return JSON.stringify(args);\n };\n\n return (...args: Parameters<T>): ReturnType<T> => {\n const key = keyGen(args);\n const now = Date.now();\n const cached = cache.get(key);\n\n if (cached && (!ttl || now - cached.timestamp < ttl)) {\n cache.delete(key);\n cache.set(key, cached); // Move to end (most recently used)\n return cached.value;\n }\n\n const result = fn(...args);\n cache.set(key, { timestamp: now, value: result });\n\n if (maxSize && cache.size > maxSize) {\n cache.delete(cache.keys().next().value!); // Remove least recently used\n }\n\n return result;\n };\n}\n"],"names":["memo","fn","ttl","maxSize","resolver","cache","keyGen","args","arg","argType","key","now","cached","result"],"mappings":"AAqCO,SAASA,EACdC,GACA,EAAE,KAAAC,GAAK,SAAAC,GAAS,UAAAC,EAAA,IAAgC,IACL;AAC3C,QAAMC,wBAAY,IAAA,GAGZC,IAAS,CAACC,MAAgC;AAC9C,QAAIH,EAAU,QAAOA,EAAS,GAAGG,CAAI;AACrC,QAAIA,EAAK,WAAW,EAAG,QAAO;AAC9B,QAAIA,EAAK,WAAW,GAAG;AACrB,YAAMC,IAAMD,EAAK,CAAC,GACZE,IAAU,OAAOD;AACvB,UAAIC,MAAY,YAAYA,MAAY,YAAYA,MAAY;AAC9D,eAAO,GAAGA,CAAO,IAAID,CAAG;AAE1B,UAAIA,MAAQ,KAAM,QAAO;AACzB,UAAIA,MAAQ,OAAW,QAAO;AAAA,IAChC;AACA,WAAO,KAAK,UAAUD,CAAI;AAAA,EAC5B;AAEA,SAAO,IAAIA,MAAuC;AAChD,UAAMG,IAAMJ,EAAOC,CAAI,GACjBI,IAAM,KAAK,IAAA,GACXC,IAASP,EAAM,IAAIK,CAAG;AAE5B,QAAIE,MAAW,CAACV,KAAOS,IAAMC,EAAO,YAAYV;AAC9C,aAAAG,EAAM,OAAOK,CAAG,GAChBL,EAAM,IAAIK,GAAKE,CAAM,GACdA,EAAO;AAGhB,UAAMC,IAASZ,EAAG,GAAGM,CAAI;AACzB,WAAAF,EAAM,IAAIK,GAAK,EAAE,WAAWC,GAAK,OAAOE,GAAQ,GAE5CV,KAAWE,EAAM,OAAOF,KAC1BE,EAAM,OAAOA,EAAM,KAAA,EAAO,KAAA,EAAO,KAAM,GAGlCQ;AAAA,EACT;AACF;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.cjs","sources":["../../src/function/proxy.ts"],"sourcesContent":["import { isObject } from '../typed/isObject';\nimport type { Obj } from '../types';\n\ntype ProxyOptions<T> = {\n set?: <K extends PropertyKey>(prop: K, curr: unknown, prev: unknown, target: T) => unknown;\n get?: <K extends PropertyKey>(prop: K, val: unknown, target: T) => unknown;\n deep?: boolean;\n watch?: (keyof T)[];\n};\n\n/**\n * Creates a new Proxy for the given object that invokes functions when properties are accessed or modified.\n\n * @example\n * ```ts\n * const obj = { a: 1, b: 2 };\n * const log = (prop, curr, prev, target) => console.log(`Property '${prop}' changed from ${prev} to ${curr}`);\n * const proxyObj = proxy(obj, { set: log });\n * proxyObj.a = 3; // logs 'Property 'a' changed from 1 to 3'\n * ```\n *\n * @param item - The object to observe.\n * @param options - Configuration options for the proxy.\n * @param [options.set] - A function to call when a property is set. It receives the property name, current value, previous value, and the target object.\n * @param [options.get] - A function to call when a property is accessed. It receives the property name, value, and the target object.\n * @param [options.deep] - If true, the proxy will also apply to nested objects.\n * @param [options.watch] - An array of property names to watch. If provided, only these properties will trigger the set and get functions.\n *\n * @returns A new Proxy for the given object.\n */\nexport function proxy<T extends Obj>(item: T, options: ProxyOptions<T>): T {\n const { set, get, deep = false, watch } = options;\n\n const handler: ProxyHandler<T> = {\n get(target, prop, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.get(target, prop, receiver);\n }\n\n let value = Reflect.get(target, prop, receiver);\n\n if (get) {\n // biome-ignore lint/suspicious/noExplicitAny: -\n value = get(prop, value, target) as any;\n }\n\n if (deep && isObject(value)) {\n return proxy(value as T[keyof T], options);\n }\n\n return value;\n },\n set(target, prop, val, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.set(target, prop, val, receiver);\n }\n\n const prev = target[prop as keyof T];\n const value = set ? set(prop, val, prev, target) : val;\n\n if (deep && isObject(value)) {\n return Reflect.set(target, prop, proxy(value as T[keyof T], options), receiver);\n }\n\n return Reflect.set(target, prop, value, receiver);\n },\n };\n\n return new Proxy(item, handler);\n}\n"],"names":["proxy","item","options","set","get","deep","watch","handler","target","prop","receiver","value","isObject","val","prev"],"mappings":"
|
|
1
|
+
{"version":3,"file":"proxy.cjs","sources":["../../src/function/proxy.ts"],"sourcesContent":["import { isObject } from '../typed/isObject';\nimport type { Obj } from '../types';\n\n// #region ProxyOptions\ntype ProxyOptions<T> = {\n set?: <K extends PropertyKey>(prop: K, curr: unknown, prev: unknown, target: T) => unknown;\n get?: <K extends PropertyKey>(prop: K, val: unknown, target: T) => unknown;\n deep?: boolean;\n watch?: (keyof T)[];\n};\n// #endregion ProxyOptions\n\n/**\n * Creates a new Proxy for the given object that invokes functions when properties are accessed or modified.\n\n * @example\n * ```ts\n * const obj = { a: 1, b: 2 };\n * const log = (prop, curr, prev, target) => console.log(`Property '${prop}' changed from ${prev} to ${curr}`);\n * const proxyObj = proxy(obj, { set: log });\n * proxyObj.a = 3; // logs 'Property 'a' changed from 1 to 3'\n * ```\n *\n * @param item - The object to observe.\n * @param options - Configuration options for the proxy.\n * @param [options.set] - A function to call when a property is set. It receives the property name, current value, previous value, and the target object.\n * @param [options.get] - A function to call when a property is accessed. It receives the property name, value, and the target object.\n * @param [options.deep] - If true, the proxy will also apply to nested objects.\n * @param [options.watch] - An array of property names to watch. If provided, only these properties will trigger the set and get functions.\n *\n * @returns A new Proxy for the given object.\n */\nexport function proxy<T extends Obj>(item: T, options: ProxyOptions<T>): T {\n const { set, get, deep = false, watch } = options;\n\n const handler: ProxyHandler<T> = {\n get(target, prop, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.get(target, prop, receiver);\n }\n\n let value = Reflect.get(target, prop, receiver);\n\n if (get) {\n // biome-ignore lint/suspicious/noExplicitAny: -\n value = get(prop, value, target) as any;\n }\n\n if (deep && isObject(value)) {\n return proxy(value as T[keyof T], options);\n }\n\n return value;\n },\n set(target, prop, val, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.set(target, prop, val, receiver);\n }\n\n const prev = target[prop as keyof T];\n const value = set ? set(prop, val, prev, target) : val;\n\n if (deep && isObject(value)) {\n return Reflect.set(target, prop, proxy(value as T[keyof T], options), receiver);\n }\n\n return Reflect.set(target, prop, value, receiver);\n },\n };\n\n return new Proxy(item, handler);\n}\n"],"names":["proxy","item","options","set","get","deep","watch","handler","target","prop","receiver","value","isObject","val","prev"],"mappings":"yHAgCO,SAASA,EAAqBC,EAASC,EAA6B,CACzE,KAAM,CAAE,IAAAC,EAAK,IAAAC,EAAK,KAAAC,EAAO,GAAO,MAAAC,GAAUJ,EAEpCK,EAA2B,CAC/B,IAAIC,EAAQC,EAAMC,EAAU,CAC1B,GAAIJ,GAAS,CAACA,EAAM,SAASG,CAAe,EAC1C,OAAO,QAAQ,IAAID,EAAQC,EAAMC,CAAQ,EAG3C,IAAIC,EAAQ,QAAQ,IAAIH,EAAQC,EAAMC,CAAQ,EAO9C,OALIN,IAEFO,EAAQP,EAAIK,EAAME,EAAOH,CAAM,GAG7BH,GAAQO,WAASD,CAAK,EACjBX,EAAMW,EAAqBT,CAAO,EAGpCS,CACT,EACA,IAAIH,EAAQC,EAAMI,EAAKH,EAAU,CAC/B,GAAIJ,GAAS,CAACA,EAAM,SAASG,CAAe,EAC1C,OAAO,QAAQ,IAAID,EAAQC,EAAMI,EAAKH,CAAQ,EAGhD,MAAMI,EAAON,EAAOC,CAAe,EAC7BE,EAAQR,EAAMA,EAAIM,EAAMI,EAAKC,EAAMN,CAAM,EAAIK,EAEnD,OAAIR,GAAQO,WAASD,CAAK,EACjB,QAAQ,IAAIH,EAAQC,EAAMT,EAAMW,EAAqBT,CAAO,EAAGQ,CAAQ,EAGzE,QAAQ,IAAIF,EAAQC,EAAME,EAAOD,CAAQ,CAClD,CAAA,EAGF,OAAO,IAAI,MAAMT,EAAMM,CAAO,CAChC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.js","sources":["../../src/function/proxy.ts"],"sourcesContent":["import { isObject } from '../typed/isObject';\nimport type { Obj } from '../types';\n\ntype ProxyOptions<T> = {\n set?: <K extends PropertyKey>(prop: K, curr: unknown, prev: unknown, target: T) => unknown;\n get?: <K extends PropertyKey>(prop: K, val: unknown, target: T) => unknown;\n deep?: boolean;\n watch?: (keyof T)[];\n};\n\n/**\n * Creates a new Proxy for the given object that invokes functions when properties are accessed or modified.\n\n * @example\n * ```ts\n * const obj = { a: 1, b: 2 };\n * const log = (prop, curr, prev, target) => console.log(`Property '${prop}' changed from ${prev} to ${curr}`);\n * const proxyObj = proxy(obj, { set: log });\n * proxyObj.a = 3; // logs 'Property 'a' changed from 1 to 3'\n * ```\n *\n * @param item - The object to observe.\n * @param options - Configuration options for the proxy.\n * @param [options.set] - A function to call when a property is set. It receives the property name, current value, previous value, and the target object.\n * @param [options.get] - A function to call when a property is accessed. It receives the property name, value, and the target object.\n * @param [options.deep] - If true, the proxy will also apply to nested objects.\n * @param [options.watch] - An array of property names to watch. If provided, only these properties will trigger the set and get functions.\n *\n * @returns A new Proxy for the given object.\n */\nexport function proxy<T extends Obj>(item: T, options: ProxyOptions<T>): T {\n const { set, get, deep = false, watch } = options;\n\n const handler: ProxyHandler<T> = {\n get(target, prop, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.get(target, prop, receiver);\n }\n\n let value = Reflect.get(target, prop, receiver);\n\n if (get) {\n // biome-ignore lint/suspicious/noExplicitAny: -\n value = get(prop, value, target) as any;\n }\n\n if (deep && isObject(value)) {\n return proxy(value as T[keyof T], options);\n }\n\n return value;\n },\n set(target, prop, val, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.set(target, prop, val, receiver);\n }\n\n const prev = target[prop as keyof T];\n const value = set ? set(prop, val, prev, target) : val;\n\n if (deep && isObject(value)) {\n return Reflect.set(target, prop, proxy(value as T[keyof T], options), receiver);\n }\n\n return Reflect.set(target, prop, value, receiver);\n },\n };\n\n return new Proxy(item, handler);\n}\n"],"names":["proxy","item","options","set","get","deep","watch","handler","target","prop","receiver","value","isObject","val","prev"],"mappings":";
|
|
1
|
+
{"version":3,"file":"proxy.js","sources":["../../src/function/proxy.ts"],"sourcesContent":["import { isObject } from '../typed/isObject';\nimport type { Obj } from '../types';\n\n// #region ProxyOptions\ntype ProxyOptions<T> = {\n set?: <K extends PropertyKey>(prop: K, curr: unknown, prev: unknown, target: T) => unknown;\n get?: <K extends PropertyKey>(prop: K, val: unknown, target: T) => unknown;\n deep?: boolean;\n watch?: (keyof T)[];\n};\n// #endregion ProxyOptions\n\n/**\n * Creates a new Proxy for the given object that invokes functions when properties are accessed or modified.\n\n * @example\n * ```ts\n * const obj = { a: 1, b: 2 };\n * const log = (prop, curr, prev, target) => console.log(`Property '${prop}' changed from ${prev} to ${curr}`);\n * const proxyObj = proxy(obj, { set: log });\n * proxyObj.a = 3; // logs 'Property 'a' changed from 1 to 3'\n * ```\n *\n * @param item - The object to observe.\n * @param options - Configuration options for the proxy.\n * @param [options.set] - A function to call when a property is set. It receives the property name, current value, previous value, and the target object.\n * @param [options.get] - A function to call when a property is accessed. It receives the property name, value, and the target object.\n * @param [options.deep] - If true, the proxy will also apply to nested objects.\n * @param [options.watch] - An array of property names to watch. If provided, only these properties will trigger the set and get functions.\n *\n * @returns A new Proxy for the given object.\n */\nexport function proxy<T extends Obj>(item: T, options: ProxyOptions<T>): T {\n const { set, get, deep = false, watch } = options;\n\n const handler: ProxyHandler<T> = {\n get(target, prop, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.get(target, prop, receiver);\n }\n\n let value = Reflect.get(target, prop, receiver);\n\n if (get) {\n // biome-ignore lint/suspicious/noExplicitAny: -\n value = get(prop, value, target) as any;\n }\n\n if (deep && isObject(value)) {\n return proxy(value as T[keyof T], options);\n }\n\n return value;\n },\n set(target, prop, val, receiver) {\n if (watch && !watch.includes(prop as keyof T)) {\n return Reflect.set(target, prop, val, receiver);\n }\n\n const prev = target[prop as keyof T];\n const value = set ? set(prop, val, prev, target) : val;\n\n if (deep && isObject(value)) {\n return Reflect.set(target, prop, proxy(value as T[keyof T], options), receiver);\n }\n\n return Reflect.set(target, prop, value, receiver);\n },\n };\n\n return new Proxy(item, handler);\n}\n"],"names":["proxy","item","options","set","get","deep","watch","handler","target","prop","receiver","value","isObject","val","prev"],"mappings":";AAgCO,SAASA,EAAqBC,GAASC,GAA6B;AACzE,QAAM,EAAE,KAAAC,GAAK,KAAAC,GAAK,MAAAC,IAAO,IAAO,OAAAC,MAAUJ,GAEpCK,IAA2B;AAAA,IAC/B,IAAIC,GAAQC,GAAMC,GAAU;AAC1B,UAAIJ,KAAS,CAACA,EAAM,SAASG,CAAe;AAC1C,eAAO,QAAQ,IAAID,GAAQC,GAAMC,CAAQ;AAG3C,UAAIC,IAAQ,QAAQ,IAAIH,GAAQC,GAAMC,CAAQ;AAO9C,aALIN,MAEFO,IAAQP,EAAIK,GAAME,GAAOH,CAAM,IAG7BH,KAAQO,EAASD,CAAK,IACjBX,EAAMW,GAAqBT,CAAO,IAGpCS;AAAA,IACT;AAAA,IACA,IAAIH,GAAQC,GAAMI,GAAKH,GAAU;AAC/B,UAAIJ,KAAS,CAACA,EAAM,SAASG,CAAe;AAC1C,eAAO,QAAQ,IAAID,GAAQC,GAAMI,GAAKH,CAAQ;AAGhD,YAAMI,IAAON,EAAOC,CAAe,GAC7BE,IAAQR,IAAMA,EAAIM,GAAMI,GAAKC,GAAMN,CAAM,IAAIK;AAEnD,aAAIR,KAAQO,EAASD,CAAK,IACjB,QAAQ,IAAIH,GAAQC,GAAMT,EAAMW,GAAqBT,CAAO,GAAGQ,CAAQ,IAGzE,QAAQ,IAAIF,GAAQC,GAAME,GAAOD,CAAQ;AAAA,IAClD;AAAA,EAAA;AAGF,SAAO,IAAI,MAAMT,GAAMM,CAAO;AAChC;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("../typed/isArray.cjs"),s=require("../typed/isEmpty.cjs"),d=require("../typed/isNil.cjs"),f=require("../typed/isObject.cjs"),u=require("../typed/isString.cjs");function e(r){if(!d.isNil(r)){if(u.isString(r)){const i=r.trim();return i===""?void 0:i}if(c.isArray(r)){const i=r.map(t=>e(t)).filter(t=>!s.isEmpty(t));return i.length===0?void 0:i}if(f.isObject(r)){const i={};for(const[t,o]of Object.entries(r)){const n=e(o);s.isEmpty(n)||(i[t]=n)}return Object.keys(i).length===0?void 0:i}return r}}exports.prune=e;
|
|
2
|
+
//# sourceMappingURL=prune.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prune.cjs","sources":["../../src/function/prune.ts"],"sourcesContent":["import { isArray } from '../typed/isArray';\nimport { isEmpty } from '../typed/isEmpty';\nimport { isNil } from '../typed/isNil';\nimport { isObject } from '../typed/isObject';\nimport { isString } from '../typed/isString';\n\n/**\n * Removes all nullable and empty values from strings, arrays, or objects.\n *\n * - For strings: Removes leading/trailing whitespace and returns undefined if empty\n * - For arrays: Recursively removes null, undefined, empty strings, and empty objects/arrays\n * - For objects: Recursively removes properties with null, undefined, empty strings, and empty objects/arrays\n *\n * @example\n * ```ts\n * prune(' hello '); // 'hello'\n * prune(' '); // undefined\n * prune([1, null, '', 2, undefined, 3]); // [1, 2, 3]\n * prune({ a: 1, b: null, c: '', d: 2 }); // { a: 1, d: 2 }\n * prune({ a: { b: null, c: '' }, d: 1 }); // { d: 1 }\n * ```\n *\n * @param value - The value to prune (can be string, array, object, or any other type)\n * @returns The pruned value, or undefined if the result would be empty\n */\nexport function prune<T>(value: T): T | undefined {\n // Handle null/undefined\n if (isNil(value)) {\n return undefined;\n }\n\n // Handle strings\n if (isString(value)) {\n const trimmed = value.trim();\n return (trimmed === '' ? undefined : trimmed) as T | undefined;\n }\n\n // Handle arrays\n if (isArray(value)) {\n const cleaned = value.map((item) => prune(item)).filter((item) => !isEmpty(item));\n\n return (cleaned.length === 0 ? undefined : cleaned) as T | undefined;\n }\n\n // Handle objects\n if (isObject(value)) {\n const cleaned: Record<string, unknown> = {};\n\n for (const [key, val] of Object.entries(value)) {\n const cleanedValue = prune(val);\n\n // Skip nil, empty strings, and empty arrays/objects\n if (!isEmpty(cleanedValue)) {\n cleaned[key] = cleanedValue;\n }\n }\n\n return (Object.keys(cleaned).length === 0 ? undefined : cleaned) as T | undefined;\n }\n\n // For other types (numbers, booleans, etc.), return as-is\n return value;\n}\n"],"names":["prune","value","isNil","isString","trimmed","isArray","cleaned","item","isEmpty","isObject","key","val","cleanedValue"],"mappings":"gQAyBO,SAASA,EAASC,EAAyB,CAEhD,GAAIC,CAAAA,EAAAA,MAAMD,CAAK,EAKf,IAAIE,EAAAA,SAASF,CAAK,EAAG,CACnB,MAAMG,EAAUH,EAAM,KAAA,EACtB,OAAQG,IAAY,GAAK,OAAYA,CACvC,CAGA,GAAIC,EAAAA,QAAQJ,CAAK,EAAG,CAClB,MAAMK,EAAUL,EAAM,IAAKM,GAASP,EAAMO,CAAI,CAAC,EAAE,OAAQA,GAAS,CAACC,EAAAA,QAAQD,CAAI,CAAC,EAEhF,OAAQD,EAAQ,SAAW,EAAI,OAAYA,CAC7C,CAGA,GAAIG,EAAAA,SAASR,CAAK,EAAG,CACnB,MAAMK,EAAmC,CAAA,EAEzC,SAAW,CAACI,EAAKC,CAAG,IAAK,OAAO,QAAQV,CAAK,EAAG,CAC9C,MAAMW,EAAeZ,EAAMW,CAAG,EAGzBH,EAAAA,QAAQI,CAAY,IACvBN,EAAQI,CAAG,EAAIE,EAEnB,CAEA,OAAQ,OAAO,KAAKN,CAAO,EAAE,SAAW,EAAI,OAAYA,CAC1D,CAGA,OAAOL,EACT"}
|