npm package: @bakelor/iframe-bridge
Description: A secure, bidirectional communication library for Angular applications using iframes
Author: Bakelor
Latest version: 8.3.1

# Bakelor IFrame Bridge

A powerful and flexible solution for secure communication between host applications and embedded iframes in Angular applications.

[![npm version](https://badge.fury.io/js/%40bakelor%2Fiframe-bridge.svg)](https://www.npmjs.com/package/@bakelor/iframe-bridge)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- 🔒 Secure bidirectional communication between host and client applications
- 🔄 Real-time data synchronization with pub/sub channels
- 🎯 Type-safe API registration and invocation
- 🌐 Built-in language support (English & Turkish)
- 🎨 Theme support (Light & Dark)
- 📊 Interactive debug monitor with real-time message tracking
- 🔍 Advanced message filtering and search capabilities
- 📡 Channel-based publish/subscribe system
- 🛠 Customizable API endpoints
- 📝 Comprehensive message logging
- 🎛 Resizable monitor panel with dynamic pagination
- 🔧 Framework version tracking and compatibility
- 📈 Built-in performance metrics API support
- 🌍 Trusted origin validation
- 🎭 Customizable powered by label

## Installation

```bash
npm install @bakelor/iframe-bridge
```

## Quick Start

### 1. Host Application Setup

```typescript
// app.module.ts
import { BakelorIframeBridgeModule } from '@bakelor/iframe-bridge';

@NgModule({
  imports: [
    BakelorIframeBridgeModule
  ]
})
export class AppModule { }

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { HostConfig, ThemeType, HostBridgeService } from '@bakelor/iframe-bridge';
import { VERSION } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <bakelor-host
      [config]="hostConfig"
      [clientUrl]="clientUrl"
      [showMonitor]="true">
    </bakelor-host>
  `
})
export class AppComponent implements OnInit {
  hostConfig: HostConfig = {
    appName: 'Host Demo App',
    version: '1.0.0',
    metaTags: [
      { name: 'description', content: 'Host application using Bakelor-Bridge' },
      { name: 'author', content: 'Bakelor' }
    ],
    language: 'en',
    theme: ThemeType.LIGHT,
    trustedOrigin: 'https://localhost:4201',
    iframeWidth: '100%',
    iframeHeight: '600px',
    script: {
      name: '@bakelor/iframe-bridge',
      version: '3.0.5',
      framework: {
        name: 'Angular',
        version: VERSION.full
      }
    },
    timestamp: Date.now()
  };

  clientUrl = 'https://localhost:4201';

  constructor(private bridgeService: HostBridgeService) {
    // Enable debug mode
    this.bridgeService.enableDebug(true);
  }

  ngOnInit() {
    // Initialize bridge service
    this.bridgeService.initialize(this.hostConfig);

    // Register server time channel
    this.bridgeService.registerChannel(
      'serverTime',
      'Server time updates',
      { 
        time: new Date().toISOString(), 
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone 
      }
    );

    // Start publishing server time
    setInterval(() => {
      const timeData = {
        time: new Date().toISOString(),
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
      };
      this.bridgeService.publishToChannel('serverTime', timeData);
    }, 1000);
  }
}
```

### 2. Client Application Setup

```typescript
// app.module.ts
import { BakelorIframeBridgeModule } from '@bakelor/iframe-bridge';

@NgModule({
  imports: [
    BakelorIframeBridgeModule
  ]
})
export class AppModule { }

// app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ClientConfig, ThemeType, ClientBridgeService } from '@bakelor/iframe-bridge';

@Component({
  selector: 'app-root',
  template: `
    <bakelor-client [config]="clientConfig">
      <!-- Your client app content -->
    </bakelor-client>
  `
})
export class AppComponent implements OnInit, OnDestroy {
  clientConfig: ClientConfig = {
    appName: 'Client Demo App',
    version: '1.0.0',
    metaTags: [
      { name: 'description', content: 'Client application using Bakelor-Bridge' },
      { name: 'author', content: 'Bakelor' }
    ],
    language: 'en',
    theme: ThemeType.LIGHT,
    trustedOrigin: 'https://localhost:4200',
    poweredByLabel: 'Powered by Bakelor',
    script: {
      name: 'Client Demo App',
      version: '1.0.0',
      framework: {
        name: 'Angular',
        version: "VERSION.full"
      }
    },
    timestamp: Date.now()
  };

  private timeUnsubscribe?: () => void;

  constructor(private bridgeService: ClientBridgeService) {
    // Enable debug mode
    this.bridgeService.enableDebug(true);
  }

  ngOnInit() {
    // Initialize bridge service
    this.bridgeService.initialize(this.clientConfig);

    // Subscribe to server time channel
    this.timeUnsubscribe = this.bridgeService.subscribeToChannel(
      'serverTime',
      (data: { time: string; timezone: string }) => {
        console.log('Server time:', data.time);
        console.log('Timezone:', data.timezone);
      }
    );
  }

  ngOnDestroy() {
    // Unsubscribe from server time channel
    if (this.timeUnsubscribe) {
      this.timeUnsubscribe();
    }
  }
}
```

## API Registration and Usage

### Host Application

```typescript
// Register an API with parameters and response type
this.bridgeService.registerApi(
  'getUserById',
  'Get user information by ID',
  {
    id: {
      type: 'string',
      description: 'User ID',
      required: true
    },
    includeDetails: {
      type: 'boolean',
      description: 'Include detailed information',
      required: false,
      defaultValue: false
    }
  },
  {
    id: '1',
    name: 'John',
    surname: 'Doe',
    email: 'john@example.com'
  },
  async (params: { id: string, includeDetails?: boolean }) => {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const user = {
      id: params.id,
      name: 'John',
      surname: 'Doe'
    };

    if (params.includeDetails) {
      return {
        ...user,
        email: 'john@example.com',
        age: 30,
        address: 'Istanbul, Turkey'
      };
    }

    return user;
  }
);
```

### Client Application

```typescript
// Call host API with parameters
async getUserDetail() {
  try {
    const user = await this.bridgeService.callApi('getUserById', {
      id: '1',
      includeDetails: true
    });
    console.log('User details:', user);
  } catch (error) {
    console.error('API error:', error);
  }
}
```

## Performance Metrics API Example

```typescript
// Register performance metrics API
this.bridgeService.registerApi(
  'appMetrics',
  'Get application performance metrics',
  {
    startDate: {
      type: 'string',
      description: 'Start date (ISO format)',
      required: true
    },
    endDate: {
      type: 'string',
      description: 'End date (ISO format)',
      required: true
    },
    metrics: {
      type: 'array',
      description: 'Metrics to retrieve',
      required: false,
      defaultValue: ['cpu', 'memory', 'network']
    }
  },
  {
    metrics: {
      cpu: { average: 45.2, peak: 78.5 },
      memory: { used: 1240.5, total: 4096, unit: 'MB' },
      network: { incoming: 1024, outgoing: 512, unit: 'KB/s' }
    }
  },
  async (params) => {
    // Implement your metrics collection logic here
    return {
      metrics: {
        cpu: {
          average: Math.random() * 100,
          peak: Math.random() * 100,
          timestamps: [new Date().toISOString()]
        },
        memory: {
          used: Math.random() * 4096,
          total: 4096,
          unit: 'MB'
        },
        network: {
          incoming: Math.random() * 2048,
          outgoing: Math.random() * 1024,
          unit: 'KB/s'
        }
      },
      period: {
        start: params.startDate,
        end: params.endDate
      }
    };
  }
);
```

## Configuration Types

### Host Config

```typescript
interface HostConfig {
  appName: string;
  version: string;
  metaTags?: Array<{ name: string; content: string; }>;
  language: string;
  theme: ThemeType;
  trustedOrigin: string;
  iframeWidth: string;
  iframeHeight: string;
  script?: {
    name: string;
    version: string;
    framework?: {
      name: string;
      version: string;
    };
  };
  timestamp?: number;
  debug?: boolean;
}
```

### Client Config

```typescript
interface ClientConfig {
  appName: string;
  version: string;
  metaTags?: Array<{ name: string; content: string; }>;
  language: string;
  theme: ThemeType;
  trustedOrigin: string;
  poweredByLabel: string;
  script?: {
    name: string;
    version: string;
    framework?: {
      name: string;
      version: string;
    };
  };
  timestamp?: number;
  debug?: boolean;
}
```

## Contributing

We welcome contributions! Please feel free to submit a Pull Request.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

For support, please create an issue in the GitHub repository or contact us at support@bakelor.com.