File size: 2,319 Bytes
4114d85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { IComponentNodes } from './Interface'

import path from 'path'
import { Dirent } from 'fs'
import { getNodeModulesPackagePath } from './utils'
import { promises } from 'fs'

export class NodesPool {
    componentNodes: IComponentNodes = {}

    /**
     * Initialize to get all nodes
     */
    async initialize() {
        const packagePath = getNodeModulesPackagePath('flowise-components')
        const nodesPath = path.join(packagePath, 'dist', 'nodes')
        const nodeFiles = await this.getFiles(nodesPath)
        return Promise.all(
            nodeFiles.map(async (file) => {
                if (file.endsWith('.js')) {
                    const nodeModule = await require(file)

                    if (nodeModule.nodeClass) {
                        const newNodeInstance = new nodeModule.nodeClass()
                        newNodeInstance.filePath = file

                        this.componentNodes[newNodeInstance.name] = newNodeInstance

                        // Replace file icon with absolute path
                        if (
                            newNodeInstance.icon &&
                            (newNodeInstance.icon.endsWith('.svg') ||
                                newNodeInstance.icon.endsWith('.png') ||
                                newNodeInstance.icon.endsWith('.jpg'))
                        ) {
                            const filePath = file.replace(/\\/g, '/').split('/')
                            filePath.pop()
                            const nodeIconAbsolutePath = `${filePath.join('/')}/${newNodeInstance.icon}`
                            this.componentNodes[newNodeInstance.name].icon = nodeIconAbsolutePath
                        }
                    }
                }
            })
        )
    }

    /**
     * Recursive function to get node files
     * @param {string} dir
     * @returns {string[]}
     */
    async getFiles(dir: string): Promise<string[]> {
        const dirents = await promises.readdir(dir, { withFileTypes: true })
        const files = await Promise.all(
            dirents.map((dirent: Dirent) => {
                const res = path.resolve(dir, dirent.name)
                return dirent.isDirectory() ? this.getFiles(res) : res
            })
        )
        return Array.prototype.concat(...files)
    }
}