npm package: @lumenlabs-dev/fast-async-retry
Description: Retrying made simple, easy and async - TypeScript version
Author: LumenLabs Development Team
Latest version: 0.1.1

# fast-async-retry

This is a TypeScript refactor of the `async-retry` library. Retrying made simple, easy, and async with full type safety.

## Features

- Full TypeScript support with type definitions
- Automatic retrying with configurable options
- Bail functionality to abort retries
- Retry callbacks for logging/monitoring
- Randomized retry delays
- Built on top of the `retry` package

## Installation

```bash
npm install @lumenlabs-dev/fast-async-retry
# or
yarn add @lumenlabs-dev/fast-async-retry
```

## Usage

### Basic Example

```typescript
import retry from '@lumenlabs-dev/fast-async-retry';
import fetch from 'node-fetch';

const result = await retry(async (bail, attempt, operation) => {
    // If anything throws, we retry
    const res = await fetch('https://google.com');

    if (res.status === 403) {
        // Don't retry upon 403
        bail(new Error('Unauthorized'));
        return;
    }

    const data = await res.text();
    return data.substr(0, 500);
}, {
    retries: 5,
});
```

### With Type Parameters

```typescript
import retry, { Options } from '@lumenlabs-dev/fast-async-retry';

// Define return type and error type
const result = await retry<string, Error>(
    async (bail, attempt, operation) => {
        console.log(`Attempt ${attempt}`);
        
        if (Math.random() > 0.5) {
            throw new Error('Random failure');
        }
        
        return 'Success!';
    },
    {
        retries: 3,
        onRetry: (error, attempt) => {
            console.log(`Retry ${attempt}: ${error.message}`);
        }
    }
);
```

## API

### `retry<TRet, TErr>(fn, opts?)`

Executes the given function with retry logic.

#### Parameters

- `fn: RetryFunction<TRet, TErr>` - The function to retry
  - `bail: (e: TErr) => void` - Call this to abort retrying
  - `attempt: number` - The current attempt number (starts at 1)
  - `operation: Operation` - The retry operation object for advanced control
  
- `opts?: Options<TErr>` - Retry options
  - `retries?: number` - Maximum number of retries (default: 10)
  - `factor?: number` - Exponential backoff factor (default: 2)
  - `minTimeout?: number` - Minimum timeout in ms (default: 1000)
  - `maxTimeout?: number` - Maximum timeout in ms (default: Infinity)
  - `randomize?: boolean` - Randomize timeouts (default: true)
  - `forever?: boolean` - Retry forever (default: false)
  - `unref?: boolean` - Unref timers (default: false)
  - `maxRetryTime?: number` - Maximum total time in ms
  - `onRetry?: (e: TErr, attempt: number) => any` - Callback on retry

#### Returns

`Promise<TRet>` - Resolves with the return value of `fn`

## Type Exports

```typescript
import { Options, RetryFunction } from '@lumenlabs-dev/fast-async-retry';

type MyOptions = Options<Error>;
type MyRetryFn = RetryFunction<string, Error>;

// Example usage with operation parameter
const myRetryFn: MyRetryFn = async (bail, attempt, operation) => {
    // operation provides access to advanced retry control
    return "success";
};
```

## Building

```bash
# Install dependencies
npm install

# Build TypeScript
npm run build

# Run tests
npm test

# Watch mode
npm run build:watch
```

## Project Structure

```
fast-async-retry/
├── src/
│   ├── index.ts           # Main implementation
│   └── types/             # Type declarations
│       ├── global.d.ts
│       └── then-sleep.d.ts
├── test/
│   └── index.test.ts      # Comprehensive test suite
├── dist/                  # Compiled output
│   ├── cjs/               # CommonJS build
│   └── esm/               # ES Module build
├── scripts/
│   └── post-build.js      # Post-build utilities
├── tsconfig.json          # Base TypeScript config
├── tsconfig.cjs.json      # CommonJS build config
├── tsconfig.esm.json      # ES Module build config
└── package.json           # Package manifest
```

## Migration from JavaScript

The TypeScript version is fully compatible with the JavaScript version. Simply update your imports:

```typescript
// Before (JavaScript)
const retry = require('async-retry');

// After (TypeScript/ES Modules)
import retry from '@lumenlabs-dev/fast-async-retry';

// Or CommonJS
const retry = require('@lumenlabs-dev/fast-async-retry').default;
```

## Notes

- The supplied function can be `async` or not. In other words, it can be a function that returns a `Promise` or a synchronous value.
- The retry options are passed to the underlying [`retry`](https://github.com/tim-kos/node-retry) package. See its documentation for more details on how the retry timing algorithm works.

## Credits

This is a TypeScript refactor of the original [`async-retry`](https://github.com/vercel/async-retry) package.

**Original Authors:**
- Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) - [Vercel](https://vercel.com)
- Leo Lamprecht ([@notquiteleo](https://twitter.com/notquiteleo)) - [Vercel](https://vercel.com)

## License

MIT