npm package: @jtl-software/platform-plugins-core
Description: A lightweight, type-safe communication bridge for JTL Platform plugins.
Latest version: 0.0.0-dev.43bafc1

# ![JTL logo](https://avatars.githubusercontent.com/u/31404730?s=25&v=4) JTL-Platform Plugins Core SDK

A lightweight, type-safe communication bridge for JTL Platform plugins.

## 📦 Installation

Install the package using npm or yarn:

```bash
# Using npm
npm install @jtl-software/platform-plugins-core

# Using yarn
yarn add @jtl-software/platform-plugins-core
```

## 🔍 Overview

The JTL Platform Plugins Core SDK provides a robust communication bridge between plugins and the JTL Platform host application. It enables:

- Bidirectional method calling between plugins and host
- Event-based publish/subscribe communication
- Type-safe messaging with Zod validation
- Promise-based async communication

This package is the foundation for building plugins that integrate seamlessly with the JTL Platform ecosystem.

## 🚀 Usage

### Creating a Plugin Bridge

To use the PluginBridge in your React components, you'll need to initialize it and maintain its instance in your component's state. Typically, this is done within a useEffect hook:

```typescript
import { createPluginBridge, PluginBridge } from '@jtl-software/platform-plugins-core';
import { useState, useEffect } from 'react';

function YourPluginComponent() {
  // Store the PluginBridge instance in component state
  const [pluginBridge, setPluginBridge] = useState<PluginBridge | undefined>(undefined);

  useEffect((): void => {
    console.info('Creating bridge...');
    createPluginBridge().then(bridge => {
      console.log('Bridge created!');

      // Store the bridge instance in state for use throughout your component
      setPluginBridge(bridge);
    });
  }, []);

  // Rest of your component...
}
```

### Subscribe to Host Events

The `subscribe` method allows your plugin to listen for specific events emitted by the host environment.

```typescript
// Listen for inventory updates
pluginBridge.subscribe('inventory:updated', async data => {
  console.info('Inventory updated:', data);
  return { status: 'processed' };
});
```

When the host system triggers an "inventory:updated" event, your callback function will execute with the provided data.

### Publish events to the host

The `publish` method sends data to the host environment under a specific topic.

```typescript
// Notify the host about completed action
await pluginBridge.publish('order:verification:complete', {
  orderId: 'ORD-12345',
  verifiedBy: 'plugin-user',
});
```

This is useful for informing the host about state changes or actions completed within your plugin.

### Exposing Methods to the Host

The `exposeMethod` function makes your plugin's functions callable by the host environment.

```typescript
// Make a function available to the host
pluginBridge.exposeMethod('calculateShippingCost', (weight, destination) => {
  const baseCost = 5.99;
  const zoneRate = destination === 'international' ? 2.5 : 1;
  return baseCost + 0.1 * weight * zoneRate;
});

// Check if a method is exposed
const isExposed = bridge.isMethodExposed('calculateShippingCost'); // true
```

This allows the host environment to directly use functionality implemented in your plugin.

### Calling Host Methods

The `callMethod` function allows your plugin to invoke functions provided by the host environment.

```typescript
// Get user information
const userProfile = await pluginBridge.callMethod('getUserProfile');

// Call a method with parameters
const orderDetails = await pluginBridge.callMethod('getOrderDetails', 'ORD-5678');
```

## 📚 API Reference

### PluginBridge

The main class that handles communication between the plugin and host, it provides the following methods.

---

#### `subscribe(event: string, callback: (data: unknown) => Promise<unknown>): void`

**Description:**  
Registers a listener for a specific event emitted by the host environment. When the event is triggered, the callback is executed with the event data.

**Parameters:**

- `event` (string): The name of the event to listen for.
- `callback` (function): A function that handles the event data.

**Returns:** `void`

---

#### `publish<TPayload>(topic: string, payload: TPayload): Promise<void>`

**Description:**  
Sends data to the host under a specific topic, typically to notify about an action or a state change.

**Parameters:**

- `topic` (string): The topic name under which the data should be published.
- `payload` (`TPayload`): The data to be sent to the host.

**Returns:** `Promise<void>`

---

#### `exposeMethod<TMethod>(methodName: string, method: TMethod): void`

**Description:**  
Makes a plugin method available for the host to call directly.

**Parameters:**

- `methodName` (string): The name under which the method should be exposed.
- `method` (`TMethod`): The actual method implementation.

**Returns:** `void`

---

#### `isMethodExposed(methodName: string): boolean`

**Description:**  
Checks whether a method with the given name has already been exposed to the host.

**Parameters:**

- `methodName` (string): The name of the method to check.

**Returns:** `boolean`

---

#### `callMethod<TResponse>(methodName: string, ...args: unknown[]): Promise<TResponse>`

**Description:**  
Calls a method provided by the host environment and returns the result.

**Parameters:**

- `methodName` (string): The name of the host method to call.
- `...args` (unknown[]): The arguments to pass to the host method.

**Returns:** `Promise<TResponse>`

### Factories

- `createPluginBridge()`: Creates and initializes a PluginBridge instance

## 📦 Dependencies

This package has minimal dependencies:

- `zod`: For runtime type validation