All files / lib/manager manager.js

64.54% Statements 182/282
59.9% Branches 124/207
66.67% Functions 32/48
70.39% Lines 164/233

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 4379x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x 9x                     9x                       11x 11x 11x 11x                           2x 2x                           2x     2x 6x 7x         7x   2x 2x                   38x 38x 38x   38x 38x 38x                   48x 48x 48x 39x 39x   48x                   2x 2x   2x 2x         2x       10x 2x 2x     10x 10x 10x 10x 10x 2x 4x 4x             4x     2x   10x   10x 10x 10x 10x 15x 15x 15x 15x     10x 10x 1x 1x 1x   1x   10x   10x 89x   55x 8x 8x 47x 8x 8x   39x       10x 49x 39x 39x 39x 39x 1x 1x 1x         39x 39x     39x         39x 39x 38x   1x     39x 32x 32x     39x 29x 29x 30x 30x                           2x 2x   1x 1x   19x 19x   8x 8x   30x   30x 30x         39x                       39x                       39x                       39x                       39x 9x 9x 26x 26x 26x 26x 2x   24x       39x 22x 22x 21x 21x 5x   16x     39x               39x               39x               39x     39x                     39x       10x 8x 8x 8x 8x 8x 8x             10x                 2x 2x       2x 2x 2x 2x 2x                 2x 2x 2x 2x             2x         9x
const yaml = require('js-yaml');
const fs = require('fs');
const path = require('path');
const classes = require('../index');
const vm = require('vm');
const {Writable, Readable} = require('stream');
 
const wrreg = /^writev?|destroy|final$/;
const rereg = /^read|destroy$/;
const trreg = /^transform|flush|final$/;
const horeg = /^hold|release|check$/;
const joreg = /^join$/;
const rureg = /^rule$/;
const fireg = /^identify|match|criteria$/
 
/**
 * Mannager is your "toolbelt" class. It's responsible to regiter classes, fetch instances, parse yaml files and building stream chains.
 * 
 * @typicalname sfc
 * @extends Writable
 */
class Manager {
    
    constructor() {
        this.clean();
    }
 
    /**
     * Clean namager state
     * 
     * Useful when you need to start again
     * 
     * @returns {Manager} 'this' element for chainable purpose.
     * 
     */
    clean() {
        this._registry = {};
        this._paused = false;
        this._resumeStack = [];
        return this;
    }
 
    /**
     * Set manager in paused mode. 
     * 
     * Use it before parsing files like `sfc.pause().parseFiles(...)`
     * 
     * Useful when you need all streams to be created before piping
     * 
     * @returns {Manager} 'this' element for chainable purpose.
     * 
     */
    pause() {
        this._paused = true;
        return this;
    }
 
    /**
     * Set inner streams in fowing mode. 
     * 
     * Use it after parsing files like `sfc.pause().parseFiles(...).resume()`
     * 
     * Useful when you need all streams to be created before piping
     * 
     * @returns {Manager} 'this' element for chainable purpose.
     * 
     */
    resume() {
        Iif(!this._paused) return this;
 
        // ensure all streams are built
        for(let type in this._registry) {
            for(let name in this._registry[type]) {
                this.get(type, name);
            }
        }
 
        // execute all piping
        this._resumeStack.forEach(fn => fn());
 
        this._paused = false;
        return this;
    }
 
    /**
     * Register a stream
     * @param {string} type type of stream
     * @param {string} [name] name for this stream
     * @param {Writable|Readable} elem the stream to register
     */
    set(type, name, elem) {
        Eif(!elem) {
            elem = name;
            name = elem.options.name;
        }
        Iif(!this._registry[type]) this._registry[type] = {};
        Iif(!this._registry[type][name]) this._registry[type][name] = {elem};
        Eif(!this._registry[type][name].elem) this._registry[type][name].elem = elem;
    }
 
    /**
     * Retrieve a stream by type and name. If stream has ended, creates a new instance
     * @param {string} type type of stream
     * @param {string} name the name of the stream to retrieve
     * @returns {Readable|Writable|null} returns the indicated stream or null if not found
     */
    get(type, name) {
        const reg = this._registry[type] && this._registry[type][name];
        Iif(!reg) return null;
        if(!reg.elem || (reg.elem instanceof Writable && reg.elem._writableState.ended) || (reg.elem instanceof Readable && reg.elem._readableState.ended)) {
            Iif(!reg.build) return null;
            reg.elem = reg.build()
        }
        return reg.elem;
    }
 
    /**
     * Parse a JSON or YAML string and create streams
     * @param {string} confStr JSON or YAML string.
     * @param {NodeCallback} cb Callback returning an error if occurred.
     */
    parse(confStr, cb) {
        let conf;
        try {
            conf = JSON.parse(confStr)
        } catch(e1) {
            try {
                conf = yaml.safeLoadAll(confStr);
            } catch(e2) {
                return cb("Probably not valid JSON or YAML."+[e1.message, e2.message]);
            }
        }
        this._build(conf, cb);
    }
 
    _build(conf, options, cb) {
        if(typeof options == 'function') {
            cb=options;
            options={};
        }
 
        try {
            Iif(!Array.isArray(conf)) conf = [conf];
            conf.forEach(conf => {
                let _require={};
                if(conf._require) {
                    Object.keys(conf._require).forEach((key)=>{
                        const m = key.match(/^{(.*)}$/)
                        Iif(m) {
                            const tmp = require(conf._require[key])
                            m[1].split(/\s*,\s*/).forEach((key)=>{
                                _require[key] = tmp[key];
                            })
 
                        } else {
                            _require[key]=require(conf._require[key])
                        }
                    });
                    delete conf._require;
                }
                _require = {...options.require||{}, ..._require};
                
                const context = {..._require, ...classes};
                vm.createContext(context);
                Iif(options.goal && !conf.__goal__) throw 'Goal chain must have "__goal__" key to get a starting point';
                const _buildMethod = (code, params)=>{
                    let fn = null;
                    Iif(Array.isArray(code)) code = code.join('\n');
                    Eif(typeof code == 'string') fn = vm.compileFunction(code, params||[], {parsingContext: context, contextExtensions: [process, global, {__dirname: require.main.path, __filename: require.main.filename}]});
                    return fn;
                }
 
                let _customTypes={};
                if(conf._customTypes) {
                    Object.keys(conf._customTypes).forEach((key)=>{
                        Iif(!conf._customTypes[key].constructor) conf._customTypes[key] = {constructor: conf._customTypes[key]};
                        _customTypes[key] = _buildMethod(conf._customTypes[key].constructor, ['options']);
                    });
                    delete conf._customTypes;
                }
                _customTypes = {...options.customTypes||{}, ..._customTypes};
 
                const _getDst = (dst) => {
                    if(Array.isArray(dst)) return dst.map(_getDst);
                    
                    if(options.goal && dst == '__resolve__') {
                        let self = options.goal;
                        return self._resolve_writer;
                    } else if (options.goal && dst == '__reject__') {
                        let self = options.goal;
                        return self._reject_writer;
                    } else {
                        return this.get(dst.type, dst.name);
                    }
                };
 
                Object.keys(conf).forEach(key => {
                    if(key == "__goal__" || key == "_customTypes" || key == "_editorAttrs" || key == "_require") return;
                    const cnf = conf[key];
                    Iif(!cnf.type) throw 'Configuration must have a "type" defined in '+key;
                    Iif(cnf.type == 'sfc' || cnf.type == 'DataWrapper') throw 'Invalid type '+cnf.type+' in '+key;
                    if(cnf.options) {
                        Object.keys(cnf.options).forEach(op => {
                            let option = cnf.options[op];
                            Iif(option._type == 'method') {
                                cnf.options[op] = _buildMethod(option.code, option.params);
                            }
                        });
                    }
                    if(!this._registry[cnf.type]) this._registry[cnf.type] = {};
                    this._registry[cnf.type][key] = {build: () => {
                        
                        let elem;
                        Iif(cnf.hasOwnProperty('constructor')) {
                            if(typeof cnf.constructor != 'function') cnf.constructor = _buildMethod(cnf.constructor, ['options']);
                            elem = cnf.constructor({...cnf.options||{}, name: key});
                            this.set(cnf.type, key, elem);
                        } else {
                            Iif(!classes[cnf.type]&&!_customTypes[cnf.type]) throw 'Unrecognized type '+cnf.type+' in '+key;
                            if(classes[cnf.type]) {
                                elem = new context[cnf.type]({...cnf.options||{}, name: key});
                            } else {
                                elem = _customTypes[cnf.type]({...cnf.options||{}, name: key});
                            }
                        }
                        if(options.goal) {
                            elem.goal = options.goal;
                            options.goal._registerChild(elem);
                        }
                        
                        if(cnf.methods) {
                            const methods = Object.keys(cnf.methods);
                            methods.forEach(method=>{
                                const def = cnf.methods[method];
                                switch(cnf.type) {
                                    case 'FlowHold': 
                                        method = method.replace(horeg, str=>'_'+str);
                                        break;
                                    case 'FlowJoin':
                                        method = method.replace(joreg, str=>'_'+str);
                                        break;
                                    case 'FlowFirst':
                                        method = method.replace(fireg, str=>'_'+str);
                                        break;
                                    case 'Rule':
                                        method = method.replace(rureg, str=>'_'+str);
                                        break;
                                    case 'Duplex':
                                        method = method.replace(wrreg, str=>'_'+str).replace(rereg, str=>'_'+str);
                                        break;
                                    case 'Readable':
                                        method = method.replace(rereg, str=>'_'+str);
                                        break;
                                    case 'Transform':
                                        method = method.replace(trreg, str=>'_'+str);
                                        break;
                                    case 'Writable':
                                        method = method.replace(wrreg, str=>'_'+str);
                                        break;
                                }
                                if(typeof def.code != 'function') def.code = _buildMethod(def.code, def.params);
                                
                                Eif(typeof def.code == 'function') {
                                    elem[method] = def.code.bind(elem);
                                }
                            })
                        }
 
                        Iif(cnf.on) {
                            const events = Object.keys(cnf.on);
                            events.forEach(event=>{
                                const def = cnf.on[event];
                                if(typeof def.code != 'function') def.code = _buildMethod(def.code, def.params);
                                
                                if(typeof def.code == 'function') {
                                    elem.on(event, def.code.bind(elem));
                                }
                            });
                        }
 
                        Iif(cnf.pon) {
                            const events = Object.keys(cnf.pon);
                            events.forEach(event=>{
                                const def = cnf.pon[event];
                                if(typeof def.code != 'function') def.code = _buildMethod(def.code, def.params);
                                
                                if(typeof def.code == 'function') {
                                    elem.prependListener(event, def.code.bind(elem));
                                }
                            });
                        }
 
                        Iif(cnf.once) {
                            const events = Object.keys(cnf.once);
                            events.forEach(event=>{
                                const def = cnf.once[event];
                                if(typeof def.code != 'function') def.code = _buildMethod(def.code, def.params);
                                
                                if(typeof def.code == 'function') {
                                    elem.once(event, def.code.bind(elem));
                                }
                            });
                        }
 
                        Iif(cnf.ponce) {
                            const events = Object.keys(cnf.ponce);
                            events.forEach(event=>{
                                const def = cnf.ponce[event];
                                if(typeof def.code != 'function') def.code = _buildMethod(def.code, def.params);
                                
                                if(typeof def.code == 'function') {
                                    elem.prependOnceListener(event, def.code.bind(elem));
                                }
                            });
                        }
                        
                        if(cnf.when && elem.when) {
                            let whens = Array.isArray(cnf.when)?cnf.when:[cnf.when]
                            whens.forEach(when => {
                                if(typeof when.cond != 'function') when.cond = _buildMethod(when.cond, ['payload']);
                                Eif(typeof when.cond == 'function') {
                                    const dst = _getDst(when.dst);
                                    if(this._paused) {
                                        return this._resumeStack.push(() => elem.when(when.cond.bind(elem), dst));
                                    }
                                    elem.when(when.cond.bind(elem), dst);
                                }
                            });
                        }
                        if(cnf.pipe && elem.pipe) {
                            const pipes = Array.isArray(cnf.pipe)?cnf.pipe:[cnf.pipe];
                            pipes.forEach(pipe => {
                                const dst = _getDst(pipe);
                                if(this._paused) {
                                    return this._resumeStack.push(() => elem.pipe(dst));
                                }
                                elem.pipe(dst);
                            });
                        }
                        Iif(cnf.none && elem.none) {
                            let dst = _getDst(cnf.none);
                            if(this._paused) {
                                this._resumeStack.push(() => elem.none(dst));
                            } else {
                                elem.none(dst);
                            }
                        }
                        Iif(cnf.resolve && elem.resolve) {
                            let dst = _getDst(cnf.resolve);
                            if(this._paused) {
                                this._resumeStack.push(() => elem.resolve(dst));
                            } else {
                                elem.resolve(dst);
                            }
                        }
                        Iif(cnf.reject && elem.reject) {
                            let dst = _getDst(cnf.reject);
                            if(this._paused) {
                                this._resumeStack.push(() => elem.reject(dst));
                            } else {
                                elem.reject(dst);
                            }
                        }
                        Iif(cnf.build && elem.build) {
                            elem.build(cnf.build, {require: _require, customTypes: _customTypes});
                        }
                        Iif(cnf.chain && elem.chain) {
                            Object.keys(cnf.chain).forEach((event)=>{
                                let dst = _getDst(cnf.chain[event]);
                                if(this._paused) {
                                    this._resumeStack.push(() => elem.chain(event, dst));
                                } else {
                                    elem.chain(event, dst);
                                }
                            });
                        }
 
                        return elem;
                    }}
                });
                
                if(options.goal) {
                    let startElems = _getDst(conf.__goal__);
                    Iif(!Array.isArray(startElems)) startElems = [startElems];
                    startElems = startElems.filter(elem => elem);
                    Iif(!startElems.length) throw "Manager could not resolve any of the following elements: "+conf.__group__.join(', ');
                    options.goal._start.unpipe();
                    startElems.forEach(dst => options.goal._start.pipe(dst));
                }
            });
        } catch(e) {
            if (cb) return cb(e);
            throw e;
        }
        cb && cb();
    }
 
    /**
     * Parse a file or directory and build streams. If no parameter is passed, parseFiles will automatically search for _sfc_ directory, and files that ends with _.sfc_, _.sfc.yaml_, _.sfc.yml_ or _.sfc.json_.
     * @param {string|array} [filePaths] path of yaml/json file or a directory containing those files.
     * @returns {Manager} returns 'this' for chainable purposes
     */
    parseFiles(filePaths) {
        let autoSearch = false;
        Iif(!filePaths) {
            autoSearch = true;
            filePaths = './';
        }
        Eif(!Array.isArray(filePaths)) filePaths = [filePaths];
        filePaths.forEach(filePath => {
            try {
                let stat = fs.statSync(filePath);
                Iif(stat.isDirectory()) {
                    let files = fs.readdirSync(filePath);
                    if(files.length) this.parseFiles(files.filter(file => {
                        if(autoSearch && !/^(.+\.)?sfc(\.(yaml|yml|json))?$/.test(file)) {
                            return false;
                        }
                        return true;
                    }).map(file=>path.join(filePath, file)));
                } else {
                    Iif(!/\.(yaml|yml|json|sfc\.?)/.test(path.basename(filePath))) return;
                    let data = fs.readFileSync(filePath);
                    this.parse(data, (err) => {
                        Iif(err) console.log('Cannot parse file '+filePath+'. '+err);
                    });
                }
            } catch(e) {
                return console.log(e);
            }
        });
        return this;
    }
 
}
 
module.exports.Manager = new Manager();