import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/Classes/CookieStorage - Cookie Storage'/>

# CookieStorage Class

A class for managing cookie storage with support for custom listeners. Provides a low-level interface for working with cookies in different environments (DOM, SSR) with automatic type parsing and secure data handling.

Includes tight integration with `CookieBlock` for access control and supports URL-encoded value decoding.

## Key Features

- **Flexible Storage** — supports in-memory storage and external storage mechanisms through listeners
- **Automatic Parsing** — intelligently converts string values to appropriate data types
- **Block Integration** — respects global write blocking via `CookieBlock`
- **Environment Awareness** — automatically detects DOM environment and adapts behavior
- **URL Decoding** — automatically decodes names and values when reading from DOM

## Static Methods

### Action

#### `get`

Retrieves a cookie value by name with automatic type conversion. If the value doesn't exist and a default is provided, it will be set and stored.

**Parameters:**
- `name: string` — the cookie name
- `defaultValue?: T | (() => T)` — default value or function returning the value

**Returns:** `T | undefined` — the converted cookie value or default value

#### `set`

Stores a cookie value with specified options and automatically updates both memory and DOM. If blocking is active via `CookieBlock`, the value is stored in memory only.

**Parameters:**
- `name: string` — the cookie name
- `value: T | (() => T)` — the value or a function returning the value
- `options?: CookieOptions` — additional cookie options

**Returns:** `T` — the stored value

#### `remove`

Removes a cookie by setting an empty value and negative expiration. Equivalent to calling `set(name, '', { age: -1 })`.

**Parameters:**
- `name: string` — the cookie name

### Configuration

- `init(getListener?, getListenerRaw?, setListener?)` — Initializes the storage with custom listeners for reading and writing data. The `setListener` takes 4 arguments: `(key, value, cookie, options)`.
- `reset()` — Resets the storage by clearing all in-memory items and removing listeners

### Auxiliary

- `update()` — Updates in-memory data by parsing values from `document.cookie`

## Types

### `CookieOptions`

Configuration object for cookie parameters:

- `age?: number` — lifetime in seconds (max-age attribute)
- `sameSite?: 'strict' | 'lax'` — SameSite policy
- `path?: string` — cookie path (defaults to `/`)
- `domain?: string` — cookie domain
- `secure?: boolean` — if true, adds the Secure attribute
- `httpOnly?: boolean` — if true, adds the HttpOnly attribute (only for server-side listeners)
- `partitioned?: boolean` — if true, adds the Partitioned attribute (CHIPS)
- `arguments?: string[] | Record<string, any>` — additional directives for the cookie string

## Built-in Type Conversion

`CookieStorage` automatically converts string values when reading:

- `'undefined'` → `undefined`
- `'null'` → `null`
- `'true'` → `true`
- `'false'` → `false`
- `'123'` → `123` (number)
- `'{"key":"value"}'` → `{key: 'value'}` (JSON object)

## Examples

### Basic Usage

```typescript
import { CookieStorage } from '@dxtmisha/functional-basic'

// Get with default value
const theme = CookieStorage.get<string>('theme', 'dark')

// Store value
CookieStorage.set('user', 'john', {
  age: 3600,
  sameSite: 'lax'
})

// Remove
CookieStorage.remove('user')
```

### Initialize with External Storage

```typescript
import { CookieStorage } from '@dxtmisha/functional-basic'

CookieStorage.init(
  (key) => myStorage.get(key),
  undefined,
  (key, value, cookie, options) => {
    // cookie is already formatted string like "key=value; max-age=..."
    myStorage.set(key, value, cookie, options)
  }
)
```

### Initialize for SSR (Raw)

```typescript
import { CookieStorage } from '@dxtmisha/functional-basic'

// For SSR, get all cookies as a raw string
CookieStorage.init(
  undefined,
  () => request.headers.cookie
)
```

### Update and Reset

```typescript
import { CookieStorage } from '@dxtmisha/functional-basic'

// Update in-memory data from document.cookie
// Useful when cookies were set externally
CookieStorage.update()

// Reset storage (clear listeners and in-memory data)
// Useful for testing or cleanup
CookieStorage.reset()
```

### Complete Workflow

```typescript
import { CookieStorage } from '@dxtmisha/functional-basic'

// Initialize with custom storage
CookieStorage.init(
  (key) => redis.get(key),
  undefined,
  (key, value, cookie, options) => redis.set(key, value, cookie, options)
)

// Set value with options
CookieStorage.set('user', 'john', {
  age: 3600,           // 1 hour
  sameSite: 'lax',     // SameSite policy
  path: '/',           // Path
  secure: true,        // HTTPS only
  httpOnly: true,      // XSS protection (for SSR)
  arguments: ['Priority=High'] // Additional directives
})

// Get with type conversion
const user = CookieStorage.get<string>('user')

// Update from external source
CookieStorage.update()

// Clean up
CookieStorage.remove('user')
CookieStorage.reset()
```
