npm package: @kkapoor/utils
Description: Utility functions and components
Latest version: 5.0.1

# @kkapoor/utils

A collection of utility functions and types for TypeScript/JavaScript projects, with a focus on Next.js applications.

Current version: **4.0.0**

This package provides both full and mini distributions. The mini distribution (`/dist/mini`) contains a subset of utilities optimized for smaller bundle sizes. You can import from the mini distribution using:

```typescript
import { ... } from '@kkapoor/utils/mini';
```

## Installation

```bash
npm install @kkapoor/utils
# or
yarn add @kkapoor/utils
# or
pnpm add @kkapoor/utils
```

## Features

### Type Utilities

-   `NonEmptyObject<T>`: Ensures an object has at least one required property
-   `NonEmptyArray<T>`: Type for arrays that must have at least one element

### Caching Utilities

The package provides a powerful caching mechanism through the `createCacher` function, which integrates with Next.js's `unstable_cache`:

```typescript
import { createCacher } from '@kkapoor/utils/cache';

const cache = createCacher({
    cacheSubjects: ['users', 'posts'],
    logPrimaryTagInDev: true,
});

const fetchUser = cache(
    async (params: { id: string }) => {
        // Your async function here
        return await fetchUserData(params.id);
    },
    { tags: { subject: 'users' }, revalidate: 60 * 5 }
);
```

The `createCacher` function is no longer applicable when using `cacheComponents` from NextJS v16 onwards, and it is suggested to use the `'use cache'` directive. However, other utilities can be used from this submodule.

### General Utilities

#### Development Logging

```typescript
import { devLog } from '@kkapoor/utils/general';

devLog('This will only log in development mode');
```

#### Maybe Function

```typescript
import { maybe } from '@kkapoor/utils/general';

const value = maybe(someValue); // Returns null if value is falsy
```

#### Pipe Functions

```typescript
import { pipe, createPipeFn } from '@kkapoor/utils/general';

// Direct pipe
const result = pipe(initialValue, transform1, transform2, transform3);

// Create reusable pipe function
const myPipe = createPipeFn(transform1, transform2, transform3);
const result = myPipe(initialValue);
```

#### Time Utilities

```typescript
import { getSeconds } from '@kkapoor/utils/general';

const seconds = getSeconds({
    days: 1,
    hours: 2,
    minutes: 30,
    seconds: 45,
});
```

### Authentication Utilities - DEPRECATED

```bash
npm install @kkapoor/next-jose-auth
```

The package provides a robust JWT-based authentication system through the `createAuthenticationClient` function:

````typescript
import { createAuthenticationClient } from '@kkapoor/utils/auth';

const auth = createAuthenticationClient({
    tokenPreferences: {
        ACCESS: {
            cookieName: 'access_token',
            maxAge: 60 * 15, // 15 minutes
            secret: process.env.JWT_ACCESS_SECRET!,
        },
        REFRESH: {
            cookieName: 'refresh_token',
            maxAge: 60 * 60 * 24 * 7, // 7 days
            secret: process.env.JWT_REFRESH_SECRET!,
        },
    },
    routePreferences: {
        routes: [
            { path: '/api', private: true },
            { path: '/dashboard', private: true },
            { path: '/auth', ignore: true },
        ],
        redirects: {
            onAuth: '/dashboard',
            onNoAuth: '/auth/login',
        },
    },
    JWTDefaultSettings: {
        issuer: 'your-app',
        alg: 'HS256',
    },
});

// Sign tokens and set cookies
await auth.signTokensAndSetCookie({ userId: '123' });

// Get current session
const session = await auth.getSession();

// Refresh token middleware
export async function middleware(request: NextRequest) {
    return auth.refreshToken(request);
}

## Requirements

-   Node.js 18 or later
-   Next.js >= 15.0.0 (peer dependency)

## License

MIT

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

### Constants

```typescript
import { __DEV__ } from '@kkapoor/utils/constants';

if (__DEV__) {
    // Development-only code
}
````