File size: 2,210 Bytes
b39afbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
 * Copyright (c) 2023 MERCENARIES.AI PTE. LTD.
 * All rights reserved.
 */

import { type Socket } from 'rete';
import CustomSocket from './CustomSocket';
import { type WorkerContext } from '../openapi/types';

// Custom Settings

// array_separator - used for join and split operations when handling arrays. Default: '\n'
// null_value - used for null values. Default: ''

class TextSocket extends CustomSocket {
  override compatibleWith(socket: Socket, noReverse: boolean): boolean {
    const cs: Partial<CustomSocket> = this;

    if (cs.type) {
      return ['string', 'object', 'number', 'integer', 'float', 'file', 'image', 'audio', 'document', 'text'].includes(
        cs.type
      );
    } else {
      return socket instanceof TextSocket;
    }
  }

  convertSingleValue(value: any): string {
    if (value == null || value === undefined) {
      return this.customSettings?.null_value || '';
    }

    if (typeof value === 'object') {
      if (value instanceof Date) {
        return value.toISOString();
      }
      // Omnitool Fids
      else if (value.fid && value.furl) {
        return value.furl;
      } else {
        return JSON.stringify(value, null, 2);
      }
    }

    if (typeof value === 'string') {
      return value;
    }

    if (typeof value === 'number') {
      return value.toString();
    }

    if (typeof value === 'boolean') {
      return value ? 'true' : 'false';
    }

    return JSON.stringify(value, null, 2);
  }

  async handleInput(ctx: WorkerContext, value: any): Promise<any | null> {
    const arraySeparator = this.customSettings?.array_separator ?? '\n';

    if (this.array && typeof value === 'string') {
      value = value.split(arraySeparator);
    }

    if (!Array.isArray(value)) {
      value = [value];
    }

    value = value.map(this.convertSingleValue.bind(this));

    if (this.customSettings?.filter_empty) {
      value = value.filter((v: string) => v);
    }

    return this.array ? value : value.join(arraySeparator);
  }

  async handleOutput(ctx: WorkerContext, value: any): Promise<any | null> {
    return await this.handleInput(ctx, value); // Use the same logic for input and output.
  }
}

export default TextSocket;