
# Actions API Reference

Complete API documentation for all interfaces, types, and functions in the Actions system.

## Core Interfaces

### Action

The main interface representing a complete workflow.

```typescript
interface Action extends TenantEntityWithAccess {
  title: string;
  description?: string;
  triggers?: ActionTrigger[];
  blocks?: ActionBlock[];
  connections?: ActionSocketConnection[];
}
```

**Properties:**
- `title`: Required descriptive name for the automation workflow
- `description`: Optional detailed explanation of what the workflow does
- `triggers`: Array of triggers that can start this Action
- `blocks`: Array of processing blocks in this workflow
- `connections`: Array of socket connections defining data flow

**Inheritance:**
- Extends `TenantEntityWithAccess` for multi-tenant support and access control

**Schema Support:**
- Includes `ActionSchema` TypeSchema for form generation and validation
- Form widgets configured for title and description fields
- Triggers, blocks, and connections are hidden in forms (managed via visual editor)

---

### ActionSchema

TypeSchema definition for Action form generation and validation.

```typescript
const ActionSchema: TypeSchema = mergeObjects(
  TenantEntityWithAccessSchema,
  {
    type: "object",
    properties: {
      title: {
        type: "string",
        title: "Title",
        "x-type-schema": {
          inputWidget: INPUT_WIDGET_STRING,
          viewWidget: { name: VIEW_WIDGET_STRING }
        }
      },
      description: {
        type: "string", 
        title: "Description",
        "x-type-schema": {
          inputWidget: INPUT_WIDGET_STRING,
          viewWidget: { name: VIEW_WIDGET_STRING }
        }
      },
      triggers: {
        type: "array",
        title: "Triggers",
        "x-type-schema": { hiddenInForms: true }
      },
      blocks: {
        type: "array", 
        title: "Blocks",
        "x-type-schema": { hiddenInForms: true }
      },
      connections: {
        type: "array",
        title: "Connections", 
        "x-type-schema": { hiddenInForms: true }
      }
    },
    required: ["title"],
    additionalProperties: false
  }
);
```

**Usage:**
- Integrated with FormComponent for create/edit dialogs
- Used by DataViewComponent for column definitions
- Provides automatic form generation based on schema
- Triggers, blocks, and connections are managed via visual editor

---

### ActionTrigger

Defines when an Action should execute.

```typescript
interface ActionTrigger {
  id: string;
  triggerName: string;
  configuration?: { [key: string]: any };
}
```

**Properties:**
- `id`: Unique identifier for this trigger instance
- `triggerName`: Must match a value from `ActionTriggers` enum
- `configuration`: Optional configuration parameters for the trigger

**Related:**
- `ActionTriggers` enum defines available trigger types
- `DocumentActionTriggerData<T>` interface for document-related trigger data

---

### ActionBlock

Represents a processing unit in a workflow.

```typescript
interface ActionBlock {
  id: string;
  blockName: string;
  configuration?: { [key: string]: any };
}
```

**Properties:**
- `id`: Unique identifier for this block instance
- `blockName`: Must match a registered block name in `ActionBlockRegistry`
- `configuration`: Optional configuration parameters for the block

---

### ActionSocketConnection

Defines data flow between triggers and blocks or between blocks.

```typescript
interface ActionSocketConnection {
  sourceBlockId: string;
  sourceSocketName: string;
  targetBlockId: string;
  targetSocketName: string;
}
```

**Properties:**
- `sourceBlockId`: ID of the source block (or trigger ID)
- `sourceSocketName`: Name of the output socket on source block
- `targetBlockId`: ID of the target block
- `targetSocketName`: Name of the input socket on target block

---

## Block Implementation Interfaces

### ActionBlockImpl

Interface that all block implementations must conform to.

```typescript
interface ActionBlockImpl {
  execute: (socketName: string, data: any) => Promise<ActionBlockResult>;
}
```

**Methods:**
- `execute`: Processes input data and returns execution result

**Parameters:**
- `socketName`: Name of the input socket being triggered
- `data`: Input data from previous block or trigger

**Returns:**
- `Promise<ActionBlockResult>`: Execution result with output data and logs

---

### ActionBlockResult

Result of block execution.

```typescript
interface ActionBlockResult {
  socketName: string;
  data?: any;
  logs: ActionExecutionResultLog[];
}
```

**Properties:**
- `socketName`: Name of the output socket for routing to next block
- `data`: Output data to pass to connected blocks (optional)
- `logs`: Array of log entries from execution

---

## Socket System

### ActionSocket

Defines input/output sockets for type-safe data transfer.

```typescript
interface ActionSocket {
  name: string;
  type: ActionSocketType;
  direction: ActionSocketDirection;
}
```

**Properties:**
- `name`: Unique socket name within the block
- `type`: Data type validation using `ActionSocketType` enum
- `direction`: Socket direction using `ActionSocketDirection` enum

---

### ActionSocketType

Enum defining supported data types for sockets.

```typescript
enum ActionSocketType {
  NUMBER = "number",
  NUMBER_ARRAY = "number[]",
  STRING = "string", 
  STRING_ARRAY = "string[]",
  BOOLEAN = "boolean",
  BOOLEAN_ARRAY = "boolean[]",
  OBJECT = "object",
  OBJECT_ARRAY = "object[]",
  NULL = "null"
}
```

**Values:**
- Primitive types: `NUMBER`, `STRING`, `BOOLEAN`, `NULL`
- Array types: `NUMBER_ARRAY`, `STRING_ARRAY`, `BOOLEAN_ARRAY`
- Complex types: `OBJECT`, `OBJECT_ARRAY`

---

### ActionSocketDirection

Enum defining socket direction.

```typescript
enum ActionSocketDirection {
  IN = "in",
  OUT = "out"
}
```

**Values:**
- `IN`: Input socket (receives data)
- `OUT`: Output socket (produces data)

---

## Trigger System

### ActionTriggers

Enum of available trigger types.

```typescript
enum ActionTriggers {
  DOCUMENT_CREATED = "documentCreated",
  DOCUMENT_UPDATED = "documentUpdated",
  DOCUMENT_DELETED = "documentDeleted"
}
```

**Values:**
- `DOCUMENT_CREATED`: Triggered when a new document is created
- `DOCUMENT_UPDATED`: Triggered when an existing document is modified
- `DOCUMENT_DELETED`: Triggered when a document is removed

---

### DocumentActionTriggerData

Type definition for document-related trigger data.

```typescript
interface DocumentActionTriggerData<T> {
  entity: T;
  collectionName: string;
  userId?: string;
}
```

**Properties:**
- `entity`: The document that triggered the action (typed)
- `collectionName`: Name of the collection containing the document
- `userId`: Optional ID of the user who performed the action

---

## Execution System

### ActionExecutor

Interface for classes that execute Actions.

```typescript
interface ActionExecutor {
  executeActionsByTrigger({
    triggerName,
    data
  }: {
    triggerName: string;
    data: any;
  }): Promise<ActionExecutionResult[]>;
}
```

**Methods:**
- `executeActionsByTrigger`: Executes all Actions matching a trigger name

**Parameters:**
- `triggerName`: Name of the trigger to execute
- `data`: Data to pass to the triggered Actions

**Returns:**
- `Promise<ActionExecutionResult[]>`: Array of execution results

---

### ActionExecutionResult

Result of Action execution.

```typescript
interface ActionExecutionResult {
  success: boolean;
  logs: ActionExecutionResultLog[];
}
```

**Properties:**
- `success`: Whether the Action executed successfully
- `logs`: Array of log entries from the execution

---

### ActionExecutionResultLog

Individual log entry from Action execution.

```typescript
interface ActionExecutionResultLog {
  timestamp: number;
  message: string;
  level: "info" | "warn" | "error";
}
```

**Properties:**
- `timestamp`: Unix timestamp when log was created
- `message`: Human-readable log message
- `level`: Log severity level

---

## Registry System

### ActionBlockRegistry

Registry for managing block implementations.

```typescript
class ActionBlockRegistry {
  private blocks: Map<string, ActionBlockImpl>;
  
  registerBlock(blockName: string, impl: ActionBlockImpl): void;
  getBlockByName(blockName: string): Promise<ActionBlockImpl | undefined>;
}
```

**Methods:**

#### registerBlock
Registers a new block implementation.

**Parameters:**
- `blockName`: Unique name for the block
- `impl`: Implementation conforming to `ActionBlockImpl`

**Returns:** `void`

#### getBlockByName
Retrieves a block implementation by name.

**Parameters:**
- `blockName`: Name of the block to retrieve

**Returns:** `Promise<ActionBlockImpl | undefined>`

---

## Execution Functions

### executeActionsByTrigger

Main function for executing Actions based on trigger.

```typescript
async function executeActionsByTrigger(
  options: ActionsByTriggerExecutionOptions
): Promise<ActionExecutionResult[]>
```

**Parameters:**
- `options`: Execution options object

**Returns:**
- `Promise<ActionExecutionResult[]>`: Array of execution results

---

### ActionsByTriggerExecutionOptions

Options for trigger-based execution.

```typescript
interface ActionsByTriggerExecutionOptions {
  triggerName: string;
  triggerData: any;
  blockRegistry: ActionBlockRegistry;
  actions: Action[];
}
```

**Properties:**
- `triggerName`: Name of trigger to match
- `triggerData`: Data to pass to triggered Actions
- `blockRegistry`: Registry containing block implementations
- `actions`: Array of Actions to consider for execution

---

## Constants

### TRIGGER_SOCKET_NAME

Special socket name used by all triggers.

```typescript
const TRIGGER_SOCKET_NAME = "trigger";
```

This constant defines the output socket name that all triggers use when connecting to blocks.

---

## Type Schema Integration

### ActionSocketSchema

TypeSchema definition for ActionSocket validation.

```typescript
const ActionSocketSchema: TypeSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
    type: { 
      type: "string",
      enum: Object.values(ActionSocketType)
    },
    direction: {
      type: "string", 
      enum: Object.values(ActionSocketDirection)
    }
  },
  required: ["name", "type", "direction"]
};
```

Used for validating socket definitions in the type system.

---

## Error Handling

### Common Error Scenarios

1. **Block Not Found**
   ```typescript
   throw new Error(`Block implementation for ${blockName} not found`);
   ```

2. **Target Block Missing**
   ```typescript
   throw new Error(`Target block ${targetBlockId} not found for connection`);
   ```

3. **Missing Trigger Name**
   ```typescript
   throw new Error("Trigger name is required for execution");
   ```

4. **No Actions Found**
   ```typescript
   throw new Error("No actions found for the specified trigger");
   ```

### Error Recovery

- Block execution errors are captured and logged
- Execution continues with remaining blocks/Actions
- All results (success and failure) are returned
- Errors don't cascade to other workflows

---

## Usage Examples

### Basic Block Implementation

```typescript
const myBlock: ActionBlockImpl = {
  execute: async (socketName: string, data: any): Promise<ActionBlockResult> => {
    return {
      socketName: "output",
      data: { processed: true },
      logs: [{
        timestamp: Date.now(),
        message: "Processing completed",
        level: "info"
      }]
    };
  }
};
```

### Registry Usage

```typescript
const registry = new ActionBlockRegistry();
registry.registerBlock("my-block", myBlock);

const impl = await registry.getBlockByName("my-block");
if (impl) {
  const result = await impl.execute("input", { value: 42 });
}
```

### Action Definition

```typescript
const action: Action = {
  triggers: [{
    id: "trigger-1",
    triggerName: "documentCreated"
  }],
  blocks: [{
    id: "block-1", 
    blockName: "send-mail",
    configuration: { to: "admin@example.com" }
  }],
  connections: [{
    sourceBlockId: "trigger-1",
    sourceSocketName: "trigger",
    targetBlockId: "block-1",
    targetSocketName: "in"
  }]
};
```

### Execution

```typescript
const results = await executeActionsByTrigger({
  triggerName: "documentCreated",
  triggerData: { documentId: "123", userId: "user-456" },
  blockRegistry: myRegistry,
  actions: [action]
});
```