npm package: @fileflow/shared
Description: Shared types, schemas, and utilities for FileFlow
Latest version: 0.1.0

# @fileflow/shared

Core types, schemas, and utilities for FileFlow - a comprehensive data import and KYC verification platform.

## Installation

```bash
npm install @fileflow/shared
# or
pnpm add @fileflow/shared
# or
yarn add @fileflow/shared
```

## Usage

### Import Feature Types

```typescript
import type {
  ImportSchema,
  SchemaColumn,
  ColumnType,
  ValidatorConfig,
  ImportSession,
  ImportSessionStatus,
} from '@fileflow/shared';

// Define your import schema
const schema: ImportSchema = {
  name: 'User Import',
  columns: [
    {
      name: 'email',
      type: 'email',
      required: true,
      validators: [
        {
          type: 'email',
          message: 'Must be a valid email',
          severity: 'error',
        },
      ],
    },
    {
      name: 'age',
      type: 'number',
      required: false,
      validators: [
        {
          type: 'range',
          config: { min: 18, max: 120 },
          message: 'Age must be between 18 and 120',
          severity: 'error',
        },
      ],
    },
  ],
  options: {
    allowExtraColumns: false,
    strictColumnOrder: false,
    maxRows: 10000,
  },
};
```

### KYC Feature Types

```typescript
import type {
  KYCSession,
  KYCDocument,
  DocumentType,
  DocumentStatus,
  PassportData,
  DriversLicenseData,
  ProofOfAddressData,
} from '@fileflow/shared';

// Create a KYC session
const session: Partial<KYCSession> = {
  userId: 'user-123',
  requiredDocuments: ['passport', 'proof_of_address'],
  status: 'pending',
};

// Handle document data
const processPassport = (data: PassportData) => {
  console.log(`Passport number: ${data.passportNumber}`);
  console.log(`Nationality: ${data.nationality}`);
  console.log(`Expiry: ${data.expiryDate}`);
};
```

### Theme Customization

```typescript
import type {
  ThemeConfig,
  FeatureThemes,
  FeatureType,
} from '@fileflow/shared';
import {
  DEFAULT_THEME,
  DEFAULT_FEATURE_THEMES,
  PRESET_THEMES,
  mergeFeatureThemes,
  themeToCssVariables,
} from '@fileflow/shared';

// Use default theme
const theme = DEFAULT_THEME;

// Customize for specific features
const customThemes: FeatureThemes = {
  import: {
    ...DEFAULT_THEME,
    colors: {
      ...DEFAULT_THEME.colors,
      primary: '#6366f1',
      primaryHover: '#4f46e5',
    },
  },
  kyc: {
    ...DEFAULT_THEME,
    colors: {
      ...DEFAULT_THEME.colors,
      primary: '#0d9488',
      primaryHover: '#0f766e',
    },
  },
};

// Use preset themes
const darkTheme = PRESET_THEMES.find(t => t.id === 'dark')?.theme;

// Convert theme to CSS variables
const cssVars = themeToCssVariables(DEFAULT_THEME);
// Returns: { '--ff-color-primary': '#6366f1', ... }
```

### PaySpace Batch Upload

```typescript
import {
  PAYSPACE_BATCH_SCHEMA,
  TRANSACTION_TYPES,
  PAYMENT_METHODS,
  type TransactionType,
  type PaymentMethod,
} from '@fileflow/shared';

// Use the pre-built PaySpace schema
const schema = PAYSPACE_BATCH_SCHEMA;

// Access constants
const validTransactionTypes: TransactionType[] = TRANSACTION_TYPES;
const validPaymentMethods: PaymentMethod[] = PAYMENT_METHODS;
```

### Zod Schemas

All types have corresponding Zod schemas for runtime validation:

```typescript
import {
  ImportSchemaSchema,
  CreateImportSessionSchema,
  CreateKYCSessionSchema,
  UploadDocumentSchema,
} from '@fileflow/shared';

// Validate data at runtime
const result = ImportSchemaSchema.safeParse(data);
if (result.success) {
  const validSchema = result.data;
  // Use validated data
} else {
  console.error(result.error);
}
```

## Iframe Integration

FileFlow provides embeddable iframe versions of both Import and KYC features for quick integration without SDK installation.

### Basic Iframe Setup

```html
<!-- KYC Verification Embed -->
<iframe 
  id="kyc-iframe"
  src="https://fileflow-web.fly.dev/embed/kyc"
  width="100%"
  height="600"
  style="border: none; border-radius: 12px;"
  allow="camera"
></iframe>

<!-- Data Import Embed -->
<iframe 
  id="import-iframe"
  src="https://fileflow-web.fly.dev/embed/import"
  width="100%"
  height="500"
  style="border: none; border-radius: 12px;"
></iframe>
```

### Iframe Configuration

Customize via URL parameters:

```html
<!-- Customized KYC with brand color and pre-selected documents -->
<iframe 
  src="https://fileflow-web.fly.dev/embed/kyc?primaryColor=%230d9488&documents=passport,drivers_license&showHeader=true"
  width="100%"
  height="650"
  allow="camera"
></iframe>

<!-- Customized Import with higher row limit -->
<iframe 
  src="https://fileflow-web.fly.dev/embed/import?primaryColor=%236366f1&maxRows=5000"
  width="100%"
  height="550"
></iframe>
```

#### Available Parameters

**Common Parameters:**
- `primaryColor` - Brand color in hex (URL encoded, e.g., `%236366f1` for #6366f1)
- `showHeader` - Show/hide header bar (default: `true`)

**KYC Parameters:**
- `documents` - Comma-separated document types: `passport`, `drivers_license`, `proof_of_address`
- `autoStart` - Auto-create session without document selection screen

**Import Parameters:**
- `maxRows` - Maximum rows to import (default: 1000)

### Parent-Iframe Communication

The iframe communicates with your application via `postMessage` API:

```typescript
// Listen for events from FileFlow embeds
window.addEventListener('message', (event) => {
  // KYC Events
  if (event.data.source === 'fileflow-kyc') {
    switch (event.data.type) {
      case 'sessionCreated':
        console.log('Session ID:', event.data.data.sessionId);
        break;
        
      case 'uploadComplete':
        console.log('Document uploaded:', event.data.data.type);
        break;
        
      case 'verificationComplete':
        const { verified, sessionId, documents } = event.data.data;
        console.log('Verification complete:', verified);
        // Handle verification result
        if (verified) {
          // Update user status, redirect, etc.
        }
        break;
        
      case 'error':
        console.error('KYC Error:', event.data.data.message);
        break;
        
      case 'close':
        // User clicked Done - close iframe/modal
        document.getElementById('kyc-iframe').style.display = 'none';
        break;
    }
  }
  
  // Import Events
  if (event.data.source === 'fileflow-import') {
    switch (event.data.type) {
      case 'fileParsed':
        const { headers, rowCount } = event.data.data;
        console.log(`Parsed ${rowCount} rows with headers:`, headers);
        break;
        
      case 'validated':
        const { errors, rows } = event.data.data;
        if (errors.length > 0) {
          console.warn('Validation errors:', errors);
        }
        break;
        
      case 'importComplete':
        const { totalRows, data } = event.data.data;
        console.log(`Import complete: ${totalRows} rows`);
        // Process imported data
        processImportedData(data);
        break;
        
      case 'close':
        // User clicked Done
        document.getElementById('import-iframe').style.display = 'none';
        break;
    }
  }
});
```

### Event Types

**KYC Events:**
- `sessionCreated` - Session initialized with `{ sessionId }`
- `uploadStarted` - Document upload began `{ type, fileName }`
- `uploadComplete` - Document processed `{ type, data }`
- `uploadError` - Upload failed `{ type, message }`
- `verificationComplete` - All documents verified `{ verified, sessionId, documents }`
- `stateChange` - User moved to new step `{ step, ... }`
- `close` - User clicked Done `{ verified }`
- `error` - General error `{ message }`

**Import Events:**
- `uploadStarted` - File upload began `{ fileName }`
- `fileParsed` - File parsed successfully `{ headers, rowCount }`
- `validated` - Validation complete `{ errors, rows }`
- `importComplete` - Import finished `{ totalRows, data }`
- `stateChange` - User moved to new step `{ step, rows }`
- `close` - User clicked Done `{ success }`
- `error` - Error occurred `{ message }`

### TypeScript Support

If using TypeScript, you can type the postMessage events:

```typescript
interface FileFlowMessage {
  source: 'fileflow-kyc' | 'fileflow-import';
  type: string;
  data: unknown;
}

interface KYCVerificationComplete {
  verified: boolean;
  sessionId: string;
  documents: Array<{
    type: string;
    status: string;
    extractedData: unknown;
  }>;
}

interface ImportComplete {
  totalRows: number;
  data: Record<string, unknown>[];
}

window.addEventListener('message', (event: MessageEvent<FileFlowMessage>) => {
  if (event.data.source === 'fileflow-kyc') {
    if (event.data.type === 'verificationComplete') {
      const result = event.data.data as KYCVerificationComplete;
      // Type-safe access to result
    }
  }
});
```

## API Reference

### Types

#### Import Types

- `ImportSchema` - Complete schema definition for data import
- `SchemaColumn` - Single column definition with type and validators
- `ColumnType` - Available column types (text, number, email, etc.)
- `ValidatorConfig` - Validation rule configuration
- `ValidatorType` - Available validators (required, email, range, etc.)
- `TransformConfig` - Data transformation rules
- `ImportSession` - Import session state and data
- `ImportSessionStatus` - Session status enum
- `ValidationError` - Validation error details

#### KYC Types

- `KYCSession` - KYC session state and configuration
- `KYCDocument` - Document upload details
- `DocumentType` - Available document types
- `DocumentStatus` - Document processing status
- `PassportData` - Extracted passport information
- `DriversLicenseData` - Extracted license information
- `ProofOfAddressData` - Extracted address proof information
- `FraudFlag` - Detected fraud indicators

#### Theme Types

- `ThemeConfig` - Complete theme configuration
- `ThemeColors` - Color palette definition
- `ThemeTypography` - Font and text styling
- `ThemeSpacing` - Border radius and spacing values
- `ThemeShadows` - Shadow definitions
- `FeatureType` - Feature identifier ('import' | 'kyc')
- `FeatureThemes` - Theme configuration per feature

### Constants

#### Import Constants

```typescript
import { COLUMN_TYPES, VALIDATOR_TYPES } from '@fileflow/shared';

// Available column types
COLUMN_TYPES = ['text', 'number', 'email', 'url', 'date', 'boolean', 'select'];

// Available validator types
VALIDATOR_TYPES = ['required', 'email', 'url', 'range', 'pattern', 'custom'];
```

#### KYC Constants

```typescript
import { DOCUMENT_TYPES, KYC_SESSION_STATUSES } from '@fileflow/shared';

DOCUMENT_TYPES = ['passport', 'drivers_license', 'proof_of_address'];
KYC_SESSION_STATUSES = ['pending', 'in_progress', 'completed', 'failed'];
```

#### Theme Constants

```typescript
import { DEFAULT_THEME, PRESET_THEMES } from '@fileflow/shared';

// Default theme configuration
DEFAULT_THEME: ThemeConfig;

// Pre-built theme presets
PRESET_THEMES: Array<{ id: string; name: string; theme: ThemeConfig }>;
```

### Utilities

#### `mergeFeatureThemes(base, overrides)`

Merge feature theme overrides with base themes.

```typescript
const merged = mergeFeatureThemes(DEFAULT_FEATURE_THEMES, {
  import: {
    colors: {
      primary: '#ff0000',
    },
  },
});
```

#### `themeToCssVariables(theme)`

Convert theme configuration to CSS variable object.

```typescript
const cssVars = themeToCssVariables(theme);
// { '--ff-color-primary': '#6366f1', ... }

// Apply to document
Object.entries(cssVars).forEach(([key, value]) => {
  document.documentElement.style.setProperty(key, value);
});
```

## Development

```bash
# Install dependencies
pnpm install

# Build
pnpm build

# Type check
pnpm typecheck

# Watch mode
pnpm dev
```

## License

MIT