@oxog/utils 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/README.md +101 -43
- package/dist/chunk-25WW2FCA.js +34 -0
- package/dist/chunk-25WW2FCA.js.map +1 -0
- package/dist/chunk-DEVWOLUI.cjs +112 -0
- package/dist/chunk-DEVWOLUI.cjs.map +1 -0
- package/dist/chunk-IUDFQZIP.js +99 -0
- package/dist/chunk-IUDFQZIP.js.map +1 -0
- package/dist/chunk-PZ5AY32C.js +9 -0
- package/dist/chunk-PZ5AY32C.js.map +1 -0
- package/dist/chunk-Q7SFCCGT.cjs +11 -0
- package/dist/chunk-Q7SFCCGT.cjs.map +1 -0
- package/dist/chunk-SWG777R6.cjs +40 -0
- package/dist/chunk-SWG777R6.cjs.map +1 -0
- package/dist/index.cjs +482 -191
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +288 -15
- package/dist/index.d.ts +288 -15
- package/dist/index.js +428 -186
- package/dist/index.js.map +1 -1
- package/dist/plugins/async.cjs +90 -107
- package/dist/plugins/async.cjs.map +1 -1
- package/dist/plugins/async.d.cts +19 -6
- package/dist/plugins/async.d.ts +19 -6
- package/dist/plugins/async.js +89 -106
- package/dist/plugins/async.js.map +1 -1
- package/dist/plugins/deep.cjs +183 -59
- package/dist/plugins/deep.cjs.map +1 -1
- package/dist/plugins/deep.d.cts +25 -7
- package/dist/plugins/deep.d.ts +25 -7
- package/dist/plugins/deep.js +183 -59
- package/dist/plugins/deep.js.map +1 -1
- package/dist/plugins/guard.cjs +2 -0
- package/dist/plugins/guard.cjs.map +1 -1
- package/dist/plugins/guard.js +2 -0
- package/dist/plugins/guard.js.map +1 -1
- package/dist/plugins/transform.cjs +6 -3
- package/dist/plugins/transform.cjs.map +1 -1
- package/dist/plugins/transform.js +6 -3
- package/dist/plugins/transform.js.map +1 -1
- package/dist/{types-XmRC5wYO.d.cts → types-B-i5UbJo.d.cts} +24 -7
- package/dist/{types-XmRC5wYO.d.ts → types-B-i5UbJo.d.ts} +24 -7
- package/package.json +15 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/plugins/optional/async.ts"],"names":[],"mappings":";;;AAGO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA,EACpC,IAAA;AAAA,EAEA,WAAA,CAAY,SAAiB,IAAA,EAAc;AACzC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,KAAA,CAAM,iBAAA,CAAkB,IAAA,EAAM,IAAA,CAAK,WAAW,CAAA;AAAA,EAChD;AACF,CAAA;AAyBO,IAAM,YAAA,GAAN,cAA2B,UAAA,CAAW;AAAA,EAC3C,YAAY,EAAA,EAAY;AACtB,IAAA,KAAA,CAAM,CAAA,0BAAA,EAA6B,EAAE,CAAA,EAAA,CAAA,EAAM,SAAS,CAAA;AACpD,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AAAA,EACd;AACF,CAAA;AAmCO,IAAM,uBAAA,GAAN,cAAsC,UAAA,CAAW;AAAA,EACtD,YAAY,QAAA,EAAkB;AAC5B,IAAA,KAAA,CAAM,CAAA,wBAAA,EAA2B,QAAQ,CAAA,UAAA,CAAA,EAAc,sBAAsB,CAAA;AAC7E,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF,CAAA;;;ACvCO,SAAS,QAAA,CACd,EAAA,EACA,IAAA,EACA,OAAA,GAA2B,EAAC,EACN;AACtB,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI,MAAA;AAEJ,EAAA,MAAM,EAAE,OAAA,GAAU,KAAA,EAAO,QAAA,GAAW,MAAK,GAAI,OAAA;AAE7C,EAAA,MAAM,SA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oxog/utils errors.\n */\nexport class UtilsError extends Error {\n code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = 'UtilsError';\n this.code = code;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Error thrown when an invalid path is provided to get/set/has functions.\n */\nexport class InvalidPathError extends UtilsError {\n constructor(path: string) {\n super(`Invalid path: ${path}`, 'INVALID_PATH');\n this.name = 'InvalidPathError';\n }\n}\n\n/**\n * Error thrown when a circular reference is detected during deep operations.\n */\nexport class CircularReferenceError extends UtilsError {\n constructor() {\n super('Circular reference detected', 'CIRCULAR_REF');\n this.name = 'CircularReferenceError';\n }\n}\n\n/**\n * Error thrown when an operation times out.\n */\nexport class TimeoutError extends UtilsError {\n constructor(ms: number) {\n super(`Operation timed out after ${ms}ms`, 'TIMEOUT');\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Error thrown when a plugin is already registered.\n */\nexport class PluginAlreadyRegisteredError extends UtilsError {\n constructor(name: string) {\n super(`Plugin \"${name}\" already registered`, 'PLUGIN_ALREADY_REGISTERED');\n this.name = 'PluginAlreadyRegisteredError';\n }\n}\n\n/**\n * Error thrown when a requested plugin is not found.\n */\nexport class PluginNotFoundError extends UtilsError {\n constructor(name: string) {\n super(`Plugin \"${name}\" not found`, 'PLUGIN_NOT_FOUND');\n this.name = 'PluginNotFoundError';\n }\n}\n\n/**\n * Error thrown when a plugin dependency is missing.\n */\nexport class PluginDependencyMissingError extends UtilsError {\n constructor(plugin: string, dependency: string) {\n super(`Plugin \"${plugin}\" requires \"${dependency}\" to be registered first`, 'PLUGIN_DEPENDENCY_MISSING');\n this.name = 'PluginDependencyMissingError';\n }\n}\n\n/**\n * Error thrown when retry attempts are exhausted.\n */\nexport class MaxRetriesExceededError extends UtilsError {\n constructor(attempts: number) {\n super(`Maximum retry attempts (${attempts}) exceeded`, 'MAX_RETRIES_EXCEEDED');\n this.name = 'MaxRetriesExceededError';\n }\n}\n","import { DebounceOptions, RetryOptions } from '../../types.js';\nimport { TimeoutError, MaxRetriesExceededError } from '../../errors.js';\n\ninterface DebouncedFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n cancel: () => void;\n flush: () => ReturnType<T>;\n pending: () => boolean;\n}\n\n/**\n * Debounce function execution.\n *\n * Delays function execution until after `wait` milliseconds have elapsed\n * since the last time the debounced function was invoked.\n *\n * @param fn - Function to debounce\n * @param wait - Wait time in milliseconds\n * @param options - Debounce options\n * @returns Debounced function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * // save() will be called 300ms after last call\n * ```\n *\n * @example With control methods\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * debouncedSave.cancel(); // Cancel pending execution\n * debouncedSave.flush(); // Execute immediately\n * debouncedSave.pending(); // Check if pending\n * ```\n *\n * @example Leading edge\n * ```typescript\n * const debounced = debounce(fn, 300, { leading: true });\n * debounced(); // Executes immediately on first call\n * ```\n */\nexport function debounce<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: DebounceOptions = {}\n): DebouncedFunction<T> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let result: ReturnType<T>;\n\n const { leading = false, trailing = true } = options;\n\n const invoke = () => {\n if (lastArgs) {\n result = fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n };\n\n const debounced = function (this: any, ...args: Parameters<T>) {\n lastArgs = args;\n lastThis = this;\n\n const shouldCallLeading = leading && !timeoutId;\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (shouldCallLeading) {\n invoke();\n }\n\n timeoutId = setTimeout(() => {\n if (trailing && !shouldCallLeading) {\n invoke();\n }\n timeoutId = undefined;\n }, wait);\n } as DebouncedFunction<T>;\n\n debounced.cancel = () => {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n };\n\n debounced.flush = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n invoke();\n }\n return result;\n };\n\n debounced.pending = () => {\n return timeoutId !== undefined;\n };\n\n return debounced;\n}\n\n/**\n * Throttle function execution.\n *\n * Ensures function is called at most once every `wait` milliseconds.\n *\n * @param fn - Function to throttle\n * @param wait - Wait time in milliseconds\n * @param options - Throttle options\n * @returns Throttled function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const throttledScroll = throttle(onScroll, 100);\n * window.addEventListener('scroll', throttledScroll);\n * // onScroll will be called at most once every 100ms\n * ```\n *\n * @example With control methods\n * ```typescript\n * const throttled = throttle(fn, 100);\n * throttled.cancel(); // Cancel pending execution\n * throttled.pending(); // Check if pending\n * ```\n */\ninterface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n cancel: () => void;\n pending: () => boolean;\n}\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: { leading?: boolean; trailing?: boolean } = {}\n): ThrottledFunction<T> {\n const { leading = true, trailing = true } = options;\n let lastCallTime = Date.now(); // Initialize to current time\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let firstCall = true;\n\n const throttled = function (this: any, ...args: Parameters<T>) {\n const now = Date.now();\n const remaining = wait - (now - lastCallTime);\n\n lastArgs = args;\n lastThis = this;\n\n if (firstCall) {\n firstCall = false;\n if (leading) {\n // Execute immediately on first call\n lastCallTime = now;\n fn.apply(this, args);\n lastArgs = undefined;\n lastThis = undefined;\n } else if (trailing) {\n // Schedule trailing call\n timeoutId = setTimeout(() => {\n lastCallTime = Date.now();\n if (lastArgs) {\n fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n timeoutId = undefined;\n }, wait);\n }\n } else if (remaining <= 0 || remaining > wait) {\n // Leading edge after throttle period - execute immediately\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n\n lastCallTime = now;\n fn.apply(this, args);\n lastArgs = undefined;\n lastThis = undefined;\n } else if (!timeoutId && trailing) {\n // Trailing edge - schedule execution\n timeoutId = setTimeout(() => {\n lastCallTime = Date.now();\n if (lastArgs) {\n fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n timeoutId = undefined;\n }, remaining);\n }\n } as ThrottledFunction<T>;\n\n throttled.cancel = () => {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n };\n\n throttled.pending = () => {\n return timeoutId !== undefined;\n };\n\n return throttled;\n}\n\n/**\n * Sleep for specified milliseconds.\n *\n * Returns a promise that resolves after the specified delay.\n *\n * @param ms - Milliseconds to sleep\n * @returns Promise that resolves after delay\n *\n * @example Basic usage\n * ```typescript\n * await sleep(1000); // Wait 1 second\n * console.log('Done!');\n * ```\n *\n * @example In async function\n * ```typescript\n * async function process() {\n * console.log('Start');\n * await sleep(1000);\n * console.log('After 1 second');\n * }\n * ```\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff.\n *\n * Retries the function until it succeeds or max attempts are reached.\n *\n * @param options - Retry options\n * @returns Promise with function result\n *\n * @example Basic usage\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'exponential'\n * });\n * ```\n *\n * @example With retry condition\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 5,\n * retryIf: (error) => error.code === 'ECONNRESET'\n * });\n * ```\n *\n * @example Linear backoff\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'linear'\n * });\n * // Waits 1000ms, 2000ms, 3000ms between retries\n * ```\n */\nexport async function retry<T>(options: RetryOptions<T>): Promise<T> {\n const { fn, attempts = 3, delay = 1000, backoff = 'exponential', retryIf } = options;\n\n let lastError: Error | undefined;\n\n for (let i = 0; i < attempts; i++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n if (retryIf && !retryIf(lastError)) {\n throw lastError;\n }\n\n if (i < attempts - 1) {\n let waitTime = delay;\n\n if (backoff === 'exponential') {\n waitTime = delay * Math.pow(2, i);\n } else if (backoff === 'linear') {\n waitTime = delay * (i + 1);\n }\n\n await sleep(waitTime);\n }\n }\n }\n\n throw new MaxRetriesExceededError(attempts);\n}\n\n/**\n * Add timeout to a promise.\n *\n * Rejects with TimeoutError if promise doesn't resolve within specified time.\n *\n * @param promise - Promise to add timeout to\n * @param ms - Timeout in milliseconds\n * @returns Promise with timeout\n *\n * @example Basic usage\n * ```typescript\n * const data = await timeout(fetch('/api'), 5000);\n * // Throws TimeoutError if takes > 5 seconds\n * ```\n *\n * @example With error handling\n * ```typescript\n * try {\n * const data = await timeout(fetch('/api'), 5000);\n * } catch (error) {\n * if (error instanceof TimeoutError) {\n * console.error('Request timed out');\n * } else {\n * console.error('Request failed:', error);\n * }\n * }\n * ```\n */\nexport function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new TimeoutError(ms));\n }, ms);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/optional/async.ts"],"names":["MaxRetriesExceededError","TimeoutError"],"mappings":";;;;;;AAqDO,SAAS,QAAA,CACd,EAAA,EACA,IAAA,EACA,OAAA,GAA2B,EAAC,EACN;AACtB,EAAA,OAAO,eAAA,CAAgB,IAAI,IAAA,EAAM;AAAA,IAC/B,OAAA,EAAS,QAAQ,OAAA,IAAW,KAAA;AAAA,IAC5B,QAAA,EAAU,QAAQ,QAAA,IAAY,IAAA;AAAA,IAC9B,SAAS,OAAA,CAAQ;AAAA,GAClB,CAAA;AAC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,MAAM,QAAQ,CAAA;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAEA,EAAA,MAAM,IAAIA,yCAAA,CAAwB,QAAA,EAAU,SAAS,CAAA;AACvD;AA8BO,SAAS,OAAA,CAAW,SAAqB,EAAA,EAAwB;AACtE,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,MAAA,MAAA,CAAO,IAAIC,8BAAA,CAAa,EAAE,CAAC,CAAA;AAAA,IAC7B,GAAG,EAAE,CAAA;AAEL,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,OAAA,CAAQ,KAAK,CAAA;AAAA,MACf,CAAA;AAAA,MACA,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,MAAA,CAAO,KAAK,CAAA;AAAA,MACd;AAAA,KACF;AAAA,EACF,CAAC,CAAA;AACH","file":"async.cjs","sourcesContent":["import { DebounceOptions, RetryOptions, ThrottleOptions } from '../../types.js';\nimport { TimeoutError, MaxRetriesExceededError } from '../../errors.js';\n\nexport interface DebouncedFunction<T extends (...args: any[]) => any> {\n /** Calls `fn` (now or later) and returns the result of the most recent invocation. */\n (...args: Parameters<T>): ReturnType<T>;\n /** Cancel a pending trailing call. */\n cancel: () => void;\n /** Run a pending trailing call immediately and return its result. */\n flush: () => ReturnType<T>;\n /** True while a call is scheduled. */\n pending: () => boolean;\n}\n\n/**\n * Debounce function execution.\n *\n * Delays function execution until after `wait` milliseconds have elapsed\n * since the last time the debounced function was invoked.\n *\n * @param fn - Function to debounce\n * @param wait - Wait time in milliseconds\n * @param options - Debounce options\n * @returns Debounced function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * // save() will be called 300ms after last call\n * ```\n *\n * @example With control methods\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * debouncedSave.cancel(); // Cancel pending execution\n * debouncedSave.flush(); // Execute immediately\n * debouncedSave.pending(); // Check if pending\n * ```\n *\n * @example Leading edge\n * ```typescript\n * const debounced = debounce(fn, 300, { leading: true });\n * debounced(); // Executes immediately on first call\n * ```\n *\n * @example Maximum wait\n * ```typescript\n * // Runs at least once per second even if calls never pause for 300ms\n * const debounced = debounce(fn, 300, { maxWait: 1000 });\n * ```\n */\nexport function debounce<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: DebounceOptions = {}\n): DebouncedFunction<T> {\n return createDebounced(fn, wait, {\n leading: options.leading ?? false,\n trailing: options.trailing ?? true,\n maxWait: options.maxWait,\n });\n}\n\n/**\n * Shared implementation of debounce/throttle (lodash semantics, except that a\n * leading call never follows a trailing call within the same `wait`):\n * - the trailing call uses the latest arguments and only runs if the function\n * was called again after a leading call;\n * - with `maxWait`, the function runs at least once every `maxWait` ms while calls keep coming;\n * - the wrapper returns the result of the most recent invocation.\n */\nfunction createDebounced<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: { leading: boolean; trailing: boolean; maxWait?: number }\n): DebouncedFunction<T> {\n wait = Math.max(0, Number(wait) || 0);\n const { leading, trailing } = options;\n const maxing = options.maxWait !== undefined;\n const maxWait = maxing ? Math.max(Number(options.maxWait) || 0, wait) : 0;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let result: ReturnType<T>;\n let lastCallTime: number | undefined;\n let lastInvokeTime = 0;\n let hasInvoked = false;\n\n const invoke = (time: number): ReturnType<T> => {\n const args = lastArgs!;\n const thisArg = lastThis;\n lastArgs = undefined;\n lastThis = undefined;\n lastInvokeTime = time;\n hasInvoked = true;\n result = fn.apply(thisArg, args);\n return result;\n };\n\n const shouldInvoke = (time: number): boolean => {\n if (lastCallTime === undefined) return true;\n const sinceLastCall = time - lastCallTime;\n const sinceLastInvoke = time - lastInvokeTime;\n return (\n sinceLastCall >= wait || sinceLastCall < 0 || (maxing && sinceLastInvoke >= maxWait)\n );\n };\n\n const remainingWait = (time: number): number => {\n const waitLeft = wait - (time - lastCallTime!);\n return maxing ? Math.min(waitLeft, maxWait - (time - lastInvokeTime)) : waitLeft;\n };\n\n const trailingEdge = (time: number): ReturnType<T> => {\n timeoutId = undefined;\n if (trailing && lastArgs) {\n return invoke(time);\n }\n lastArgs = undefined;\n lastThis = undefined;\n return result;\n };\n\n const timerExpired = (): void => {\n const time = Date.now();\n if (shouldInvoke(time)) {\n trailingEdge(time);\n return;\n }\n timeoutId = setTimeout(timerExpired, remainingWait(time));\n };\n\n const leadingEdge = (time: number): ReturnType<T> => {\n // A trailing call that just ran counts as the leading call of this window,\n // so the function never runs twice within `wait`.\n const recentlyInvoked = hasInvoked && time - lastInvokeTime < wait;\n if (!recentlyInvoked) {\n lastInvokeTime = time;\n }\n timeoutId = setTimeout(timerExpired, wait);\n return leading && !recentlyInvoked ? invoke(time) : result;\n };\n\n const debounced = function (this: any, ...args: Parameters<T>): ReturnType<T> {\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n lastArgs = args;\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- forwarded to fn\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timeoutId === undefined) {\n return leadingEdge(time);\n }\n if (maxing) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(timerExpired, wait);\n return invoke(time);\n }\n }\n if (timeoutId === undefined) {\n timeoutId = setTimeout(timerExpired, wait);\n }\n return result;\n } as DebouncedFunction<T>;\n\n debounced.cancel = () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n lastCallTime = undefined;\n lastInvokeTime = 0;\n hasInvoked = false;\n };\n\n debounced.flush = () => {\n if (timeoutId === undefined) {\n return result;\n }\n clearTimeout(timeoutId);\n return trailingEdge(Date.now());\n };\n\n debounced.pending = () => timeoutId !== undefined;\n\n return debounced;\n}\n\n/**\n * Throttle function execution.\n *\n * Ensures function is called at most once every `wait` milliseconds.\n * By default the first call runs immediately (`leading`) and the latest\n * arguments of later calls in the window run at its end (`trailing`).\n *\n * @param fn - Function to throttle\n * @param wait - Wait time in milliseconds\n * @param options - Throttle options\n * @returns Throttled function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const throttledScroll = throttle(onScroll, 100);\n * window.addEventListener('scroll', throttledScroll);\n * // onScroll will be called at most once every 100ms\n * ```\n *\n * @example With control methods\n * ```typescript\n * const throttled = throttle(fn, 100);\n * throttled.cancel(); // Cancel pending execution\n * throttled.pending(); // Check if pending\n * ```\n */\nexport interface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n /** Cancel a pending trailing call and reset the throttle window. */\n cancel: () => void;\n /** Run a pending trailing call immediately and return its result. */\n flush: () => ReturnType<T>;\n /** True while a trailing call is scheduled or the throttle window is open. */\n pending: () => boolean;\n}\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: ThrottleOptions = {}\n): ThrottledFunction<T> {\n return createDebounced(fn, wait, {\n leading: options.leading ?? true,\n trailing: options.trailing ?? true,\n maxWait: wait,\n });\n}\n\n/**\n * Sleep for specified milliseconds.\n *\n * Returns a promise that resolves after the specified delay.\n *\n * @param ms - Milliseconds to sleep\n * @returns Promise that resolves after delay\n *\n * @example Basic usage\n * ```typescript\n * await sleep(1000); // Wait 1 second\n * console.log('Done!');\n * ```\n *\n * @example In async function\n * ```typescript\n * async function process() {\n * console.log('Start');\n * await sleep(1000);\n * console.log('After 1 second');\n * }\n * ```\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff.\n *\n * Retries the function until it succeeds or max attempts are reached.\n *\n * @param options - Retry options\n * @returns Promise with function result\n *\n * @example Basic usage\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'exponential'\n * });\n * ```\n *\n * @example With retry condition\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 5,\n * retryIf: (error) => error.code === 'ECONNRESET'\n * });\n * ```\n *\n * @example Linear backoff\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'linear'\n * });\n * // Waits 1000ms, 2000ms, 3000ms between retries\n * ```\n */\nexport async function retry<T>(options: RetryOptions<T>): Promise<T> {\n const { fn, attempts = 3, delay = 1000, backoff = 'exponential', retryIf } = options;\n\n let lastError: Error | undefined;\n\n for (let i = 0; i < attempts; i++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n if (retryIf && !retryIf(lastError)) {\n throw lastError;\n }\n\n if (i < attempts - 1) {\n let waitTime = delay;\n\n if (backoff === 'exponential') {\n waitTime = delay * Math.pow(2, i);\n } else if (backoff === 'linear') {\n waitTime = delay * (i + 1);\n }\n\n await sleep(waitTime);\n }\n }\n }\n\n throw new MaxRetriesExceededError(attempts, lastError);\n}\n\n/**\n * Add timeout to a promise.\n *\n * Rejects with TimeoutError if promise doesn't resolve within specified time.\n *\n * @param promise - Promise to add timeout to\n * @param ms - Timeout in milliseconds\n * @returns Promise with timeout\n *\n * @example Basic usage\n * ```typescript\n * const data = await timeout(fetch('/api'), 5000);\n * // Throws TimeoutError if takes > 5 seconds\n * ```\n *\n * @example With error handling\n * ```typescript\n * try {\n * const data = await timeout(fetch('/api'), 5000);\n * } catch (error) {\n * if (error instanceof TimeoutError) {\n * console.error('Request timed out');\n * } else {\n * console.error('Request failed:', error);\n * }\n * }\n * ```\n */\nexport function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new TimeoutError(ms));\n }, ms);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n}\n"]}
|
package/dist/plugins/async.d.cts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { D as DebounceOptions, R as RetryOptions } from '../types-
|
|
1
|
+
import { D as DebounceOptions, T as ThrottleOptions, R as RetryOptions } from '../types-B-i5UbJo.cjs';
|
|
2
2
|
|
|
3
3
|
interface DebouncedFunction<T extends (...args: any[]) => any> {
|
|
4
|
+
/** Calls `fn` (now or later) and returns the result of the most recent invocation. */
|
|
4
5
|
(...args: Parameters<T>): ReturnType<T>;
|
|
6
|
+
/** Cancel a pending trailing call. */
|
|
5
7
|
cancel: () => void;
|
|
8
|
+
/** Run a pending trailing call immediately and return its result. */
|
|
6
9
|
flush: () => ReturnType<T>;
|
|
10
|
+
/** True while a call is scheduled. */
|
|
7
11
|
pending: () => boolean;
|
|
8
12
|
}
|
|
9
13
|
/**
|
|
@@ -38,12 +42,20 @@ interface DebouncedFunction<T extends (...args: any[]) => any> {
|
|
|
38
42
|
* const debounced = debounce(fn, 300, { leading: true });
|
|
39
43
|
* debounced(); // Executes immediately on first call
|
|
40
44
|
* ```
|
|
45
|
+
*
|
|
46
|
+
* @example Maximum wait
|
|
47
|
+
* ```typescript
|
|
48
|
+
* // Runs at least once per second even if calls never pause for 300ms
|
|
49
|
+
* const debounced = debounce(fn, 300, { maxWait: 1000 });
|
|
50
|
+
* ```
|
|
41
51
|
*/
|
|
42
52
|
declare function debounce<T extends (...args: any[]) => any>(fn: T, wait: number, options?: DebounceOptions): DebouncedFunction<T>;
|
|
43
53
|
/**
|
|
44
54
|
* Throttle function execution.
|
|
45
55
|
*
|
|
46
56
|
* Ensures function is called at most once every `wait` milliseconds.
|
|
57
|
+
* By default the first call runs immediately (`leading`) and the latest
|
|
58
|
+
* arguments of later calls in the window run at its end (`trailing`).
|
|
47
59
|
*
|
|
48
60
|
* @param fn - Function to throttle
|
|
49
61
|
* @param wait - Wait time in milliseconds
|
|
@@ -66,13 +78,14 @@ declare function debounce<T extends (...args: any[]) => any>(fn: T, wait: number
|
|
|
66
78
|
*/
|
|
67
79
|
interface ThrottledFunction<T extends (...args: any[]) => any> {
|
|
68
80
|
(...args: Parameters<T>): ReturnType<T>;
|
|
81
|
+
/** Cancel a pending trailing call and reset the throttle window. */
|
|
69
82
|
cancel: () => void;
|
|
83
|
+
/** Run a pending trailing call immediately and return its result. */
|
|
84
|
+
flush: () => ReturnType<T>;
|
|
85
|
+
/** True while a trailing call is scheduled or the throttle window is open. */
|
|
70
86
|
pending: () => boolean;
|
|
71
87
|
}
|
|
72
|
-
declare function throttle<T extends (...args: any[]) => any>(fn: T, wait: number, options?:
|
|
73
|
-
leading?: boolean;
|
|
74
|
-
trailing?: boolean;
|
|
75
|
-
}): ThrottledFunction<T>;
|
|
88
|
+
declare function throttle<T extends (...args: any[]) => any>(fn: T, wait: number, options?: ThrottleOptions): ThrottledFunction<T>;
|
|
76
89
|
/**
|
|
77
90
|
* Sleep for specified milliseconds.
|
|
78
91
|
*
|
|
@@ -166,4 +179,4 @@ declare function retry<T>(options: RetryOptions<T>): Promise<T>;
|
|
|
166
179
|
*/
|
|
167
180
|
declare function timeout<T>(promise: Promise<T>, ms: number): Promise<T>;
|
|
168
181
|
|
|
169
|
-
export { debounce, retry, sleep, throttle, timeout };
|
|
182
|
+
export { type DebouncedFunction, type ThrottledFunction, debounce, retry, sleep, throttle, timeout };
|
package/dist/plugins/async.d.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { D as DebounceOptions, R as RetryOptions } from '../types-
|
|
1
|
+
import { D as DebounceOptions, T as ThrottleOptions, R as RetryOptions } from '../types-B-i5UbJo.js';
|
|
2
2
|
|
|
3
3
|
interface DebouncedFunction<T extends (...args: any[]) => any> {
|
|
4
|
+
/** Calls `fn` (now or later) and returns the result of the most recent invocation. */
|
|
4
5
|
(...args: Parameters<T>): ReturnType<T>;
|
|
6
|
+
/** Cancel a pending trailing call. */
|
|
5
7
|
cancel: () => void;
|
|
8
|
+
/** Run a pending trailing call immediately and return its result. */
|
|
6
9
|
flush: () => ReturnType<T>;
|
|
10
|
+
/** True while a call is scheduled. */
|
|
7
11
|
pending: () => boolean;
|
|
8
12
|
}
|
|
9
13
|
/**
|
|
@@ -38,12 +42,20 @@ interface DebouncedFunction<T extends (...args: any[]) => any> {
|
|
|
38
42
|
* const debounced = debounce(fn, 300, { leading: true });
|
|
39
43
|
* debounced(); // Executes immediately on first call
|
|
40
44
|
* ```
|
|
45
|
+
*
|
|
46
|
+
* @example Maximum wait
|
|
47
|
+
* ```typescript
|
|
48
|
+
* // Runs at least once per second even if calls never pause for 300ms
|
|
49
|
+
* const debounced = debounce(fn, 300, { maxWait: 1000 });
|
|
50
|
+
* ```
|
|
41
51
|
*/
|
|
42
52
|
declare function debounce<T extends (...args: any[]) => any>(fn: T, wait: number, options?: DebounceOptions): DebouncedFunction<T>;
|
|
43
53
|
/**
|
|
44
54
|
* Throttle function execution.
|
|
45
55
|
*
|
|
46
56
|
* Ensures function is called at most once every `wait` milliseconds.
|
|
57
|
+
* By default the first call runs immediately (`leading`) and the latest
|
|
58
|
+
* arguments of later calls in the window run at its end (`trailing`).
|
|
47
59
|
*
|
|
48
60
|
* @param fn - Function to throttle
|
|
49
61
|
* @param wait - Wait time in milliseconds
|
|
@@ -66,13 +78,14 @@ declare function debounce<T extends (...args: any[]) => any>(fn: T, wait: number
|
|
|
66
78
|
*/
|
|
67
79
|
interface ThrottledFunction<T extends (...args: any[]) => any> {
|
|
68
80
|
(...args: Parameters<T>): ReturnType<T>;
|
|
81
|
+
/** Cancel a pending trailing call and reset the throttle window. */
|
|
69
82
|
cancel: () => void;
|
|
83
|
+
/** Run a pending trailing call immediately and return its result. */
|
|
84
|
+
flush: () => ReturnType<T>;
|
|
85
|
+
/** True while a trailing call is scheduled or the throttle window is open. */
|
|
70
86
|
pending: () => boolean;
|
|
71
87
|
}
|
|
72
|
-
declare function throttle<T extends (...args: any[]) => any>(fn: T, wait: number, options?:
|
|
73
|
-
leading?: boolean;
|
|
74
|
-
trailing?: boolean;
|
|
75
|
-
}): ThrottledFunction<T>;
|
|
88
|
+
declare function throttle<T extends (...args: any[]) => any>(fn: T, wait: number, options?: ThrottleOptions): ThrottledFunction<T>;
|
|
76
89
|
/**
|
|
77
90
|
* Sleep for specified milliseconds.
|
|
78
91
|
*
|
|
@@ -166,4 +179,4 @@ declare function retry<T>(options: RetryOptions<T>): Promise<T>;
|
|
|
166
179
|
*/
|
|
167
180
|
declare function timeout<T>(promise: Promise<T>, ms: number): Promise<T>;
|
|
168
181
|
|
|
169
|
-
export { debounce, retry, sleep, throttle, timeout };
|
|
182
|
+
export { type DebouncedFunction, type ThrottledFunction, debounce, retry, sleep, throttle, timeout };
|
package/dist/plugins/async.js
CHANGED
|
@@ -1,136 +1,119 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
code;
|
|
4
|
-
constructor(message, code) {
|
|
5
|
-
super(message);
|
|
6
|
-
this.name = "UtilsError";
|
|
7
|
-
this.code = code;
|
|
8
|
-
Error.captureStackTrace(this, this.constructor);
|
|
9
|
-
}
|
|
10
|
-
};
|
|
11
|
-
var TimeoutError = class extends UtilsError {
|
|
12
|
-
constructor(ms) {
|
|
13
|
-
super(`Operation timed out after ${ms}ms`, "TIMEOUT");
|
|
14
|
-
this.name = "TimeoutError";
|
|
15
|
-
}
|
|
16
|
-
};
|
|
17
|
-
var MaxRetriesExceededError = class extends UtilsError {
|
|
18
|
-
constructor(attempts) {
|
|
19
|
-
super(`Maximum retry attempts (${attempts}) exceeded`, "MAX_RETRIES_EXCEEDED");
|
|
20
|
-
this.name = "MaxRetriesExceededError";
|
|
21
|
-
}
|
|
22
|
-
};
|
|
1
|
+
import { MaxRetriesExceededError, TimeoutError } from '../chunk-IUDFQZIP.js';
|
|
2
|
+
import '../chunk-PZ5AY32C.js';
|
|
23
3
|
|
|
24
4
|
// src/plugins/optional/async.ts
|
|
25
5
|
function debounce(fn, wait, options = {}) {
|
|
6
|
+
return createDebounced(fn, wait, {
|
|
7
|
+
leading: options.leading ?? false,
|
|
8
|
+
trailing: options.trailing ?? true,
|
|
9
|
+
maxWait: options.maxWait
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
function createDebounced(fn, wait, options) {
|
|
13
|
+
wait = Math.max(0, Number(wait) || 0);
|
|
14
|
+
const { leading, trailing } = options;
|
|
15
|
+
const maxing = options.maxWait !== void 0;
|
|
16
|
+
const maxWait = maxing ? Math.max(Number(options.maxWait) || 0, wait) : 0;
|
|
26
17
|
let timeoutId;
|
|
27
18
|
let lastArgs;
|
|
28
19
|
let lastThis;
|
|
29
20
|
let result;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
21
|
+
let lastCallTime;
|
|
22
|
+
let lastInvokeTime = 0;
|
|
23
|
+
let hasInvoked = false;
|
|
24
|
+
const invoke = (time) => {
|
|
25
|
+
const args = lastArgs;
|
|
26
|
+
const thisArg = lastThis;
|
|
27
|
+
lastArgs = void 0;
|
|
28
|
+
lastThis = void 0;
|
|
29
|
+
lastInvokeTime = time;
|
|
30
|
+
hasInvoked = true;
|
|
31
|
+
result = fn.apply(thisArg, args);
|
|
32
|
+
return result;
|
|
37
33
|
};
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
clearTimeout(timeoutId);
|
|
44
|
-
}
|
|
45
|
-
if (shouldCallLeading) {
|
|
46
|
-
invoke();
|
|
47
|
-
}
|
|
48
|
-
timeoutId = setTimeout(() => {
|
|
49
|
-
if (trailing && !shouldCallLeading) {
|
|
50
|
-
invoke();
|
|
51
|
-
}
|
|
52
|
-
timeoutId = void 0;
|
|
53
|
-
}, wait);
|
|
34
|
+
const shouldInvoke = (time) => {
|
|
35
|
+
if (lastCallTime === void 0) return true;
|
|
36
|
+
const sinceLastCall = time - lastCallTime;
|
|
37
|
+
const sinceLastInvoke = time - lastInvokeTime;
|
|
38
|
+
return sinceLastCall >= wait || sinceLastCall < 0 || maxing && sinceLastInvoke >= maxWait;
|
|
54
39
|
};
|
|
55
|
-
|
|
56
|
-
|
|
40
|
+
const remainingWait = (time) => {
|
|
41
|
+
const waitLeft = wait - (time - lastCallTime);
|
|
42
|
+
return maxing ? Math.min(waitLeft, maxWait - (time - lastInvokeTime)) : waitLeft;
|
|
43
|
+
};
|
|
44
|
+
const trailingEdge = (time) => {
|
|
57
45
|
timeoutId = void 0;
|
|
46
|
+
if (trailing && lastArgs) {
|
|
47
|
+
return invoke(time);
|
|
48
|
+
}
|
|
58
49
|
lastArgs = void 0;
|
|
59
50
|
lastThis = void 0;
|
|
51
|
+
return result;
|
|
60
52
|
};
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
53
|
+
const timerExpired = () => {
|
|
54
|
+
const time = Date.now();
|
|
55
|
+
if (shouldInvoke(time)) {
|
|
56
|
+
trailingEdge(time);
|
|
57
|
+
return;
|
|
65
58
|
}
|
|
66
|
-
|
|
59
|
+
timeoutId = setTimeout(timerExpired, remainingWait(time));
|
|
67
60
|
};
|
|
68
|
-
|
|
69
|
-
|
|
61
|
+
const leadingEdge = (time) => {
|
|
62
|
+
const recentlyInvoked = hasInvoked && time - lastInvokeTime < wait;
|
|
63
|
+
if (!recentlyInvoked) {
|
|
64
|
+
lastInvokeTime = time;
|
|
65
|
+
}
|
|
66
|
+
timeoutId = setTimeout(timerExpired, wait);
|
|
67
|
+
return leading && !recentlyInvoked ? invoke(time) : result;
|
|
70
68
|
};
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const { leading = true, trailing = true } = options;
|
|
75
|
-
let lastCallTime = Date.now();
|
|
76
|
-
let timeoutId;
|
|
77
|
-
let lastArgs;
|
|
78
|
-
let lastThis;
|
|
79
|
-
let firstCall = true;
|
|
80
|
-
const throttled = function(...args) {
|
|
81
|
-
const now = Date.now();
|
|
82
|
-
const remaining = wait - (now - lastCallTime);
|
|
69
|
+
const debounced = function(...args) {
|
|
70
|
+
const time = Date.now();
|
|
71
|
+
const isInvoking = shouldInvoke(time);
|
|
83
72
|
lastArgs = args;
|
|
84
73
|
lastThis = this;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
if (
|
|
88
|
-
|
|
89
|
-
fn.apply(this, args);
|
|
90
|
-
lastArgs = void 0;
|
|
91
|
-
lastThis = void 0;
|
|
92
|
-
} else if (trailing) {
|
|
93
|
-
timeoutId = setTimeout(() => {
|
|
94
|
-
lastCallTime = Date.now();
|
|
95
|
-
if (lastArgs) {
|
|
96
|
-
fn.apply(lastThis, lastArgs);
|
|
97
|
-
lastArgs = void 0;
|
|
98
|
-
lastThis = void 0;
|
|
99
|
-
}
|
|
100
|
-
timeoutId = void 0;
|
|
101
|
-
}, wait);
|
|
74
|
+
lastCallTime = time;
|
|
75
|
+
if (isInvoking) {
|
|
76
|
+
if (timeoutId === void 0) {
|
|
77
|
+
return leadingEdge(time);
|
|
102
78
|
}
|
|
103
|
-
|
|
104
|
-
if (timeoutId) {
|
|
79
|
+
if (maxing) {
|
|
105
80
|
clearTimeout(timeoutId);
|
|
106
|
-
timeoutId =
|
|
81
|
+
timeoutId = setTimeout(timerExpired, wait);
|
|
82
|
+
return invoke(time);
|
|
107
83
|
}
|
|
108
|
-
lastCallTime = now;
|
|
109
|
-
fn.apply(this, args);
|
|
110
|
-
lastArgs = void 0;
|
|
111
|
-
lastThis = void 0;
|
|
112
|
-
} else if (!timeoutId && trailing) {
|
|
113
|
-
timeoutId = setTimeout(() => {
|
|
114
|
-
lastCallTime = Date.now();
|
|
115
|
-
if (lastArgs) {
|
|
116
|
-
fn.apply(lastThis, lastArgs);
|
|
117
|
-
lastArgs = void 0;
|
|
118
|
-
lastThis = void 0;
|
|
119
|
-
}
|
|
120
|
-
timeoutId = void 0;
|
|
121
|
-
}, remaining);
|
|
122
84
|
}
|
|
85
|
+
if (timeoutId === void 0) {
|
|
86
|
+
timeoutId = setTimeout(timerExpired, wait);
|
|
87
|
+
}
|
|
88
|
+
return result;
|
|
123
89
|
};
|
|
124
|
-
|
|
125
|
-
|
|
90
|
+
debounced.cancel = () => {
|
|
91
|
+
if (timeoutId !== void 0) {
|
|
92
|
+
clearTimeout(timeoutId);
|
|
93
|
+
}
|
|
126
94
|
timeoutId = void 0;
|
|
127
95
|
lastArgs = void 0;
|
|
128
96
|
lastThis = void 0;
|
|
97
|
+
lastCallTime = void 0;
|
|
98
|
+
lastInvokeTime = 0;
|
|
99
|
+
hasInvoked = false;
|
|
129
100
|
};
|
|
130
|
-
|
|
131
|
-
|
|
101
|
+
debounced.flush = () => {
|
|
102
|
+
if (timeoutId === void 0) {
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
clearTimeout(timeoutId);
|
|
106
|
+
return trailingEdge(Date.now());
|
|
132
107
|
};
|
|
133
|
-
|
|
108
|
+
debounced.pending = () => timeoutId !== void 0;
|
|
109
|
+
return debounced;
|
|
110
|
+
}
|
|
111
|
+
function throttle(fn, wait, options = {}) {
|
|
112
|
+
return createDebounced(fn, wait, {
|
|
113
|
+
leading: options.leading ?? true,
|
|
114
|
+
trailing: options.trailing ?? true,
|
|
115
|
+
maxWait: wait
|
|
116
|
+
});
|
|
134
117
|
}
|
|
135
118
|
function sleep(ms) {
|
|
136
119
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -157,7 +140,7 @@ async function retry(options) {
|
|
|
157
140
|
}
|
|
158
141
|
}
|
|
159
142
|
}
|
|
160
|
-
throw new MaxRetriesExceededError(attempts);
|
|
143
|
+
throw new MaxRetriesExceededError(attempts, lastError);
|
|
161
144
|
}
|
|
162
145
|
function timeout(promise, ms) {
|
|
163
146
|
return new Promise((resolve, reject) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/plugins/optional/async.ts"],"names":[],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QAAA,MAAM,SAAA;AAAA,MACR;AAEA,MAAA,IAAI,CAAA,GAAI,WAAW,CAAA,EAAG;AACpB,QAAA,IAAI,QAAA,GAAW,KAAA;AAEf,QAAA,IAAI,YAAY,aAAA,EAAe;AAC7B,UAAA,QAAA,GAAW,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAA;AAAA,QAClC,CAAA,MAAA,IAAW,YAAY,QAAA,EAAU;AAC/B,UAAA,QAAA,GAAW,SAAS,CAAA,GAAI,CAAA,CAAA;AAAA,QAC1B;AAEA,QAAA,MAAM,MAAM,QAAQ,CAAA;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAEA,EAAA,MAAM,IAAI,wBAAwB,QAAQ,CAAA;AAC5C;AA8BO,SAAS,OAAA,CAAW,SAAqB,EAAA,EAAwB;AACtE,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,MAAA,MAAA,CAAO,IAAI,YAAA,CAAa,EAAE,CAAC,CAAA;AAAA,IAC7B,GAAG,EAAE,CAAA;AAEL,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,OAAA,CAAQ,KAAK,CAAA;AAAA,MACf,CAAA;AAAA,MACA,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,MAAA,CAAO,KAAK,CAAA;AAAA,MACd;AAAA,KACF;AAAA,EACF,CAAC,CAAA;AACH","file":"async.js","sourcesContent":["/**\n * Base error class for all @oxog/utils errors.\n */\nexport class UtilsError extends Error {\n code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = 'UtilsError';\n this.code = code;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Error thrown when an invalid path is provided to get/set/has functions.\n */\nexport class InvalidPathError extends UtilsError {\n constructor(path: string) {\n super(`Invalid path: ${path}`, 'INVALID_PATH');\n this.name = 'InvalidPathError';\n }\n}\n\n/**\n * Error thrown when a circular reference is detected during deep operations.\n */\nexport class CircularReferenceError extends UtilsError {\n constructor() {\n super('Circular reference detected', 'CIRCULAR_REF');\n this.name = 'CircularReferenceError';\n }\n}\n\n/**\n * Error thrown when an operation times out.\n */\nexport class TimeoutError extends UtilsError {\n constructor(ms: number) {\n super(`Operation timed out after ${ms}ms`, 'TIMEOUT');\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Error thrown when a plugin is already registered.\n */\nexport class PluginAlreadyRegisteredError extends UtilsError {\n constructor(name: string) {\n super(`Plugin \"${name}\" already registered`, 'PLUGIN_ALREADY_REGISTERED');\n this.name = 'PluginAlreadyRegisteredError';\n }\n}\n\n/**\n * Error thrown when a requested plugin is not found.\n */\nexport class PluginNotFoundError extends UtilsError {\n constructor(name: string) {\n super(`Plugin \"${name}\" not found`, 'PLUGIN_NOT_FOUND');\n this.name = 'PluginNotFoundError';\n }\n}\n\n/**\n * Error thrown when a plugin dependency is missing.\n */\nexport class PluginDependencyMissingError extends UtilsError {\n constructor(plugin: string, dependency: string) {\n super(`Plugin \"${plugin}\" requires \"${dependency}\" to be registered first`, 'PLUGIN_DEPENDENCY_MISSING');\n this.name = 'PluginDependencyMissingError';\n }\n}\n\n/**\n * Error thrown when retry attempts are exhausted.\n */\nexport class MaxRetriesExceededError extends UtilsError {\n constructor(attempts: number) {\n super(`Maximum retry attempts (${attempts}) exceeded`, 'MAX_RETRIES_EXCEEDED');\n this.name = 'MaxRetriesExceededError';\n }\n}\n","import { DebounceOptions, RetryOptions } from '../../types.js';\nimport { TimeoutError, MaxRetriesExceededError } from '../../errors.js';\n\ninterface DebouncedFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n cancel: () => void;\n flush: () => ReturnType<T>;\n pending: () => boolean;\n}\n\n/**\n * Debounce function execution.\n *\n * Delays function execution until after `wait` milliseconds have elapsed\n * since the last time the debounced function was invoked.\n *\n * @param fn - Function to debounce\n * @param wait - Wait time in milliseconds\n * @param options - Debounce options\n * @returns Debounced function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * // save() will be called 300ms after last call\n * ```\n *\n * @example With control methods\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * debouncedSave.cancel(); // Cancel pending execution\n * debouncedSave.flush(); // Execute immediately\n * debouncedSave.pending(); // Check if pending\n * ```\n *\n * @example Leading edge\n * ```typescript\n * const debounced = debounce(fn, 300, { leading: true });\n * debounced(); // Executes immediately on first call\n * ```\n */\nexport function debounce<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: DebounceOptions = {}\n): DebouncedFunction<T> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let result: ReturnType<T>;\n\n const { leading = false, trailing = true } = options;\n\n const invoke = () => {\n if (lastArgs) {\n result = fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n };\n\n const debounced = function (this: any, ...args: Parameters<T>) {\n lastArgs = args;\n lastThis = this;\n\n const shouldCallLeading = leading && !timeoutId;\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (shouldCallLeading) {\n invoke();\n }\n\n timeoutId = setTimeout(() => {\n if (trailing && !shouldCallLeading) {\n invoke();\n }\n timeoutId = undefined;\n }, wait);\n } as DebouncedFunction<T>;\n\n debounced.cancel = () => {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n };\n\n debounced.flush = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n invoke();\n }\n return result;\n };\n\n debounced.pending = () => {\n return timeoutId !== undefined;\n };\n\n return debounced;\n}\n\n/**\n * Throttle function execution.\n *\n * Ensures function is called at most once every `wait` milliseconds.\n *\n * @param fn - Function to throttle\n * @param wait - Wait time in milliseconds\n * @param options - Throttle options\n * @returns Throttled function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const throttledScroll = throttle(onScroll, 100);\n * window.addEventListener('scroll', throttledScroll);\n * // onScroll will be called at most once every 100ms\n * ```\n *\n * @example With control methods\n * ```typescript\n * const throttled = throttle(fn, 100);\n * throttled.cancel(); // Cancel pending execution\n * throttled.pending(); // Check if pending\n * ```\n */\ninterface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n cancel: () => void;\n pending: () => boolean;\n}\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: { leading?: boolean; trailing?: boolean } = {}\n): ThrottledFunction<T> {\n const { leading = true, trailing = true } = options;\n let lastCallTime = Date.now(); // Initialize to current time\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let firstCall = true;\n\n const throttled = function (this: any, ...args: Parameters<T>) {\n const now = Date.now();\n const remaining = wait - (now - lastCallTime);\n\n lastArgs = args;\n lastThis = this;\n\n if (firstCall) {\n firstCall = false;\n if (leading) {\n // Execute immediately on first call\n lastCallTime = now;\n fn.apply(this, args);\n lastArgs = undefined;\n lastThis = undefined;\n } else if (trailing) {\n // Schedule trailing call\n timeoutId = setTimeout(() => {\n lastCallTime = Date.now();\n if (lastArgs) {\n fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n timeoutId = undefined;\n }, wait);\n }\n } else if (remaining <= 0 || remaining > wait) {\n // Leading edge after throttle period - execute immediately\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n\n lastCallTime = now;\n fn.apply(this, args);\n lastArgs = undefined;\n lastThis = undefined;\n } else if (!timeoutId && trailing) {\n // Trailing edge - schedule execution\n timeoutId = setTimeout(() => {\n lastCallTime = Date.now();\n if (lastArgs) {\n fn.apply(lastThis, lastArgs);\n lastArgs = undefined;\n lastThis = undefined;\n }\n timeoutId = undefined;\n }, remaining);\n }\n } as ThrottledFunction<T>;\n\n throttled.cancel = () => {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n };\n\n throttled.pending = () => {\n return timeoutId !== undefined;\n };\n\n return throttled;\n}\n\n/**\n * Sleep for specified milliseconds.\n *\n * Returns a promise that resolves after the specified delay.\n *\n * @param ms - Milliseconds to sleep\n * @returns Promise that resolves after delay\n *\n * @example Basic usage\n * ```typescript\n * await sleep(1000); // Wait 1 second\n * console.log('Done!');\n * ```\n *\n * @example In async function\n * ```typescript\n * async function process() {\n * console.log('Start');\n * await sleep(1000);\n * console.log('After 1 second');\n * }\n * ```\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff.\n *\n * Retries the function until it succeeds or max attempts are reached.\n *\n * @param options - Retry options\n * @returns Promise with function result\n *\n * @example Basic usage\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'exponential'\n * });\n * ```\n *\n * @example With retry condition\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 5,\n * retryIf: (error) => error.code === 'ECONNRESET'\n * });\n * ```\n *\n * @example Linear backoff\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'linear'\n * });\n * // Waits 1000ms, 2000ms, 3000ms between retries\n * ```\n */\nexport async function retry<T>(options: RetryOptions<T>): Promise<T> {\n const { fn, attempts = 3, delay = 1000, backoff = 'exponential', retryIf } = options;\n\n let lastError: Error | undefined;\n\n for (let i = 0; i < attempts; i++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n if (retryIf && !retryIf(lastError)) {\n throw lastError;\n }\n\n if (i < attempts - 1) {\n let waitTime = delay;\n\n if (backoff === 'exponential') {\n waitTime = delay * Math.pow(2, i);\n } else if (backoff === 'linear') {\n waitTime = delay * (i + 1);\n }\n\n await sleep(waitTime);\n }\n }\n }\n\n throw new MaxRetriesExceededError(attempts);\n}\n\n/**\n * Add timeout to a promise.\n *\n * Rejects with TimeoutError if promise doesn't resolve within specified time.\n *\n * @param promise - Promise to add timeout to\n * @param ms - Timeout in milliseconds\n * @returns Promise with timeout\n *\n * @example Basic usage\n * ```typescript\n * const data = await timeout(fetch('/api'), 5000);\n * // Throws TimeoutError if takes > 5 seconds\n * ```\n *\n * @example With error handling\n * ```typescript\n * try {\n * const data = await timeout(fetch('/api'), 5000);\n * } catch (error) {\n * if (error instanceof TimeoutError) {\n * console.error('Request timed out');\n * } else {\n * console.error('Request failed:', error);\n * }\n * }\n * ```\n */\nexport function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new TimeoutError(ms));\n }, ms);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/optional/async.ts"],"names":[],"mappings":";;;;AAqDO,SAAS,QAAA,CACd,EAAA,EACA,IAAA,EACA,OAAA,GAA2B,EAAC,EACN;AACtB,EAAA,OAAO,eAAA,CAAgB,IAAI,IAAA,EAAM;AAAA,IAC/B,OAAA,EAAS,QAAQ,OAAA,IAAW,KAAA;AAAA,IAC5B,QAAA,EAAU,QAAQ,QAAA,IAAY,IAAA;AAAA,IAC9B,SAAS,OAAA,CAAQ;AAAA,GAClB,CAAA;AACH;AAUA,SAAS,eAAA,CACP,EAAA,EACA,IAAA,EACA,OAAA,EACsB;AACtB,EAAA,IAAA,GAAO,KAAK,GAAA,CAAI,CAAA,EAAG,MAAA,CAAO,IAAI,KAAK,CAAC,CAAA;AACpC,EAAA,MAAM,EAAE,OAAA,EAAS,QAAA,EAAS,GAA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AQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,KAAA,GAAQ,WAAW,MAAM;AAC7B,MAAA,MAAA,CAAO,IAAI,YAAA,CAAa,EAAE,CAAC,CAAA;AAAA,IAC7B,GAAG,EAAE,CAAA;AAEL,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,OAAA,CAAQ,KAAK,CAAA;AAAA,MACf,CAAA;AAAA,MACA,CAAC,KAAA,KAAU;AACT,QAAA,YAAA,CAAa,KAAK,CAAA;AAClB,QAAA,MAAA,CAAO,KAAK,CAAA;AAAA,MACd;AAAA,KACF;AAAA,EACF,CAAC,CAAA;AACH","file":"async.js","sourcesContent":["import { DebounceOptions, RetryOptions, ThrottleOptions } from '../../types.js';\nimport { TimeoutError, MaxRetriesExceededError } from '../../errors.js';\n\nexport interface DebouncedFunction<T extends (...args: any[]) => any> {\n /** Calls `fn` (now or later) and returns the result of the most recent invocation. */\n (...args: Parameters<T>): ReturnType<T>;\n /** Cancel a pending trailing call. */\n cancel: () => void;\n /** Run a pending trailing call immediately and return its result. */\n flush: () => ReturnType<T>;\n /** True while a call is scheduled. */\n pending: () => boolean;\n}\n\n/**\n * Debounce function execution.\n *\n * Delays function execution until after `wait` milliseconds have elapsed\n * since the last time the debounced function was invoked.\n *\n * @param fn - Function to debounce\n * @param wait - Wait time in milliseconds\n * @param options - Debounce options\n * @returns Debounced function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * // save() will be called 300ms after last call\n * ```\n *\n * @example With control methods\n * ```typescript\n * const debouncedSave = debounce(save, 300);\n * debouncedSave(data);\n * debouncedSave.cancel(); // Cancel pending execution\n * debouncedSave.flush(); // Execute immediately\n * debouncedSave.pending(); // Check if pending\n * ```\n *\n * @example Leading edge\n * ```typescript\n * const debounced = debounce(fn, 300, { leading: true });\n * debounced(); // Executes immediately on first call\n * ```\n *\n * @example Maximum wait\n * ```typescript\n * // Runs at least once per second even if calls never pause for 300ms\n * const debounced = debounce(fn, 300, { maxWait: 1000 });\n * ```\n */\nexport function debounce<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: DebounceOptions = {}\n): DebouncedFunction<T> {\n return createDebounced(fn, wait, {\n leading: options.leading ?? false,\n trailing: options.trailing ?? true,\n maxWait: options.maxWait,\n });\n}\n\n/**\n * Shared implementation of debounce/throttle (lodash semantics, except that a\n * leading call never follows a trailing call within the same `wait`):\n * - the trailing call uses the latest arguments and only runs if the function\n * was called again after a leading call;\n * - with `maxWait`, the function runs at least once every `maxWait` ms while calls keep coming;\n * - the wrapper returns the result of the most recent invocation.\n */\nfunction createDebounced<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: { leading: boolean; trailing: boolean; maxWait?: number }\n): DebouncedFunction<T> {\n wait = Math.max(0, Number(wait) || 0);\n const { leading, trailing } = options;\n const maxing = options.maxWait !== undefined;\n const maxWait = maxing ? Math.max(Number(options.maxWait) || 0, wait) : 0;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastThis: any;\n let result: ReturnType<T>;\n let lastCallTime: number | undefined;\n let lastInvokeTime = 0;\n let hasInvoked = false;\n\n const invoke = (time: number): ReturnType<T> => {\n const args = lastArgs!;\n const thisArg = lastThis;\n lastArgs = undefined;\n lastThis = undefined;\n lastInvokeTime = time;\n hasInvoked = true;\n result = fn.apply(thisArg, args);\n return result;\n };\n\n const shouldInvoke = (time: number): boolean => {\n if (lastCallTime === undefined) return true;\n const sinceLastCall = time - lastCallTime;\n const sinceLastInvoke = time - lastInvokeTime;\n return (\n sinceLastCall >= wait || sinceLastCall < 0 || (maxing && sinceLastInvoke >= maxWait)\n );\n };\n\n const remainingWait = (time: number): number => {\n const waitLeft = wait - (time - lastCallTime!);\n return maxing ? Math.min(waitLeft, maxWait - (time - lastInvokeTime)) : waitLeft;\n };\n\n const trailingEdge = (time: number): ReturnType<T> => {\n timeoutId = undefined;\n if (trailing && lastArgs) {\n return invoke(time);\n }\n lastArgs = undefined;\n lastThis = undefined;\n return result;\n };\n\n const timerExpired = (): void => {\n const time = Date.now();\n if (shouldInvoke(time)) {\n trailingEdge(time);\n return;\n }\n timeoutId = setTimeout(timerExpired, remainingWait(time));\n };\n\n const leadingEdge = (time: number): ReturnType<T> => {\n // A trailing call that just ran counts as the leading call of this window,\n // so the function never runs twice within `wait`.\n const recentlyInvoked = hasInvoked && time - lastInvokeTime < wait;\n if (!recentlyInvoked) {\n lastInvokeTime = time;\n }\n timeoutId = setTimeout(timerExpired, wait);\n return leading && !recentlyInvoked ? invoke(time) : result;\n };\n\n const debounced = function (this: any, ...args: Parameters<T>): ReturnType<T> {\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n lastArgs = args;\n // eslint-disable-next-line @typescript-eslint/no-this-alias -- forwarded to fn\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timeoutId === undefined) {\n return leadingEdge(time);\n }\n if (maxing) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(timerExpired, wait);\n return invoke(time);\n }\n }\n if (timeoutId === undefined) {\n timeoutId = setTimeout(timerExpired, wait);\n }\n return result;\n } as DebouncedFunction<T>;\n\n debounced.cancel = () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n timeoutId = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n lastCallTime = undefined;\n lastInvokeTime = 0;\n hasInvoked = false;\n };\n\n debounced.flush = () => {\n if (timeoutId === undefined) {\n return result;\n }\n clearTimeout(timeoutId);\n return trailingEdge(Date.now());\n };\n\n debounced.pending = () => timeoutId !== undefined;\n\n return debounced;\n}\n\n/**\n * Throttle function execution.\n *\n * Ensures function is called at most once every `wait` milliseconds.\n * By default the first call runs immediately (`leading`) and the latest\n * arguments of later calls in the window run at its end (`trailing`).\n *\n * @param fn - Function to throttle\n * @param wait - Wait time in milliseconds\n * @param options - Throttle options\n * @returns Throttled function with control methods\n *\n * @example Basic usage\n * ```typescript\n * const throttledScroll = throttle(onScroll, 100);\n * window.addEventListener('scroll', throttledScroll);\n * // onScroll will be called at most once every 100ms\n * ```\n *\n * @example With control methods\n * ```typescript\n * const throttled = throttle(fn, 100);\n * throttled.cancel(); // Cancel pending execution\n * throttled.pending(); // Check if pending\n * ```\n */\nexport interface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): ReturnType<T>;\n /** Cancel a pending trailing call and reset the throttle window. */\n cancel: () => void;\n /** Run a pending trailing call immediately and return its result. */\n flush: () => ReturnType<T>;\n /** True while a trailing call is scheduled or the throttle window is open. */\n pending: () => boolean;\n}\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n wait: number,\n options: ThrottleOptions = {}\n): ThrottledFunction<T> {\n return createDebounced(fn, wait, {\n leading: options.leading ?? true,\n trailing: options.trailing ?? true,\n maxWait: wait,\n });\n}\n\n/**\n * Sleep for specified milliseconds.\n *\n * Returns a promise that resolves after the specified delay.\n *\n * @param ms - Milliseconds to sleep\n * @returns Promise that resolves after delay\n *\n * @example Basic usage\n * ```typescript\n * await sleep(1000); // Wait 1 second\n * console.log('Done!');\n * ```\n *\n * @example In async function\n * ```typescript\n * async function process() {\n * console.log('Start');\n * await sleep(1000);\n * console.log('After 1 second');\n * }\n * ```\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff.\n *\n * Retries the function until it succeeds or max attempts are reached.\n *\n * @param options - Retry options\n * @returns Promise with function result\n *\n * @example Basic usage\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'exponential'\n * });\n * ```\n *\n * @example With retry condition\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 5,\n * retryIf: (error) => error.code === 'ECONNRESET'\n * });\n * ```\n *\n * @example Linear backoff\n * ```typescript\n * const result = await retry({\n * fn: async () => fetchData(),\n * attempts: 3,\n * delay: 1000,\n * backoff: 'linear'\n * });\n * // Waits 1000ms, 2000ms, 3000ms between retries\n * ```\n */\nexport async function retry<T>(options: RetryOptions<T>): Promise<T> {\n const { fn, attempts = 3, delay = 1000, backoff = 'exponential', retryIf } = options;\n\n let lastError: Error | undefined;\n\n for (let i = 0; i < attempts; i++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n if (retryIf && !retryIf(lastError)) {\n throw lastError;\n }\n\n if (i < attempts - 1) {\n let waitTime = delay;\n\n if (backoff === 'exponential') {\n waitTime = delay * Math.pow(2, i);\n } else if (backoff === 'linear') {\n waitTime = delay * (i + 1);\n }\n\n await sleep(waitTime);\n }\n }\n }\n\n throw new MaxRetriesExceededError(attempts, lastError);\n}\n\n/**\n * Add timeout to a promise.\n *\n * Rejects with TimeoutError if promise doesn't resolve within specified time.\n *\n * @param promise - Promise to add timeout to\n * @param ms - Timeout in milliseconds\n * @returns Promise with timeout\n *\n * @example Basic usage\n * ```typescript\n * const data = await timeout(fetch('/api'), 5000);\n * // Throws TimeoutError if takes > 5 seconds\n * ```\n *\n * @example With error handling\n * ```typescript\n * try {\n * const data = await timeout(fetch('/api'), 5000);\n * } catch (error) {\n * if (error instanceof TimeoutError) {\n * console.error('Request timed out');\n * } else {\n * console.error('Request failed:', error);\n * }\n * }\n * ```\n */\nexport function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new TimeoutError(ms));\n }, ms);\n\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n}\n"]}
|