Create a new version of rfr.
@param {{root:String}} config config of this version.
@returns {rfr} a new rfr version.
@private
161122
function createVersion(config) {
  if (!(config && (typeof config.root === 'string'
      || config.root === null || config.root === undefined))) {
    throw new Error('"config.root" is required and must be a string');
  }
  var root = config.root;
  if (root === null || root === undefined) {
    root = defaultRoot;
  }

  return createRfr(function(idFromRoot) {
    if (typeof idFromRoot !== 'string') {
      throw new Error('A string is required for the argument of ' +
      'a user created RFR version.');
    }
    return require(normalizeId(idFromRoot, this.root));
  }, root);
}
308114
function _createConfig(){
        let file = repositoryPath + '/config.json';
        let config = {
            simulation: false
        };
        return new Promise(function(resolve, reject) {
            jsonfile.writeFile(file, config, function (err) {
                if(err){
                    reject(err);
                    return;
                }
                resolve();
            });

        });
    }
942240
async function createConfig(optionsArgs) {
  const options = {
    ...DEFAULT_OPTIONS,
    ...optionsArgs,
  };
  const { rules, base } = options;

  const config = {
    ...base,
    rules: base.rules || {},
  };

  return Object.keys(config)
    .reduce(async (collection, key) => {
      const previous = await collection;

      if (key === 'rules') {
        const combinedRules = await combineRules(rules);

        return {
          ...previous,
          rules: {
            ...combinedRules,
            ...config.rules,
          },
        };
      }

      return {
        ...previous,
        [key]: config[key],
      };
    }, Promise.resolve({}));
}
1332723
function buildConfig(
  config, items, item, inheritableConfigs = {}, visitedItems = []
) {
  let { id } = item

  if (visitedItems.includes(id)) {
    throw new Error(`Item "${id}" has cyclic dependencies`)
  }

  let _extends = item.extends || DEFAULT
  let inheritedConfig = inheritableConfigs[_extends]
  visitedItems.push(id)

  if (!inheritedConfig) {
    let parent = findOneById(items, _extends)

    if (!parent) {
      throw new Error(`Item "${id}" tries to extend a non-existent item`)
    }

    parent = buildConfig(
      config, items, parent, inheritableConfigs, visitedItems
    )
    inheritedConfig = extractInheritableConfig(config, parent)
    inheritableConfigs[parent.id] = inheritedConfig
  }

  return mergeConfigs(inheritedConfig, item)
}
1336545
function(config) {
        config = omit(config, 'settings');
        var subbed = cloneDeep(config);
        var subFlag = this._applySubstitutions(subbed, null, null);
        var unsubbed = subFlag ? config : subbed;
        return {subbed:subbed, unsubbed:unsubbed};
    }
1063058
function Parser(config) {
  if (!(this instanceof Parser)) return new Parser(config);

  this.config = config;

  this.config.on('read', function read(type) {
    this[type]();
  }.bind(this));
}
385157
function(config) {
        var self = this;

        return new Promise(function(resolve, reject) {
            if (self._options.output) {
                fs.writeFileAsync(self._options.output, config)
                    .then(function() {
                        resolve(config);
                    });
            } else {
                resolve(config);
            }
        });
    }
87048
private static Configuration createCfg(TemplateConfig config) {
		if (null == config) {
			config = new TemplateConfig();
		}

		final Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		cfg.setLocalizedLookup(false);
		cfg.setDefaultEncoding(config.getCharset().toString());

		switch (config.getResourceMode()) {
		case CLASSPATH:
			cfg.setTemplateLoader(new ClassTemplateLoader(ClassUtil.getClassLoader(), config.getPath()));
			break;
		case FILE:
			try {
				cfg.setTemplateLoader(new FileTemplateLoader(FileUtil.file(config.getPath())));
			} catch (IOException e) {
				throw new IORuntimeException(e);
			}
			break;
		case WEB_ROOT:
			 try {
				 cfg.setTemplateLoader(new FileTemplateLoader(FileUtil.file(FileUtil.getWebRoot(), config.getPath())));
			 } catch (IOException e) {
				 throw new IORuntimeException(e);
			 }
			break;
		case STRING:
			cfg.setTemplateLoader(new SimpleStringTemplateLoader());
			break;
		default:
			break;
		}
		
		return cfg;
	}
119303
function createAction(config){
    // make a copy of config with defaults
    config = basis.object.extend({
      prepare: nothingToDo,
      request: nothingToDo
    }, config);

    // if body is function take in account special action context
    if (typeof config.body == 'function')
    {
      var bodyFn = config.body;
      config.body = function(){
        return bodyFn.apply(this.context, this.args);
      };
    }

    // splice properties
    var fn = basis.object.splice(config, ['prepare', 'request']);
    var callback = basis.object.merge(
      DEFAULT_CALLBACK,
      basis.object.splice(config, ['start', 'success', 'failure', 'abort', 'complete'])
    );

    // lazy transport
    var getTransport = basis.fn.lazyInit(function(){
      var transport = resolveTransport(config);

      transport.addHandler(CALLBACK_HANDLER, callback);

      return transport;
    });

    return function action(){
      // this - instance of AbstractData
      if (this.state != STATE_PROCESSING)
      {
        if (fn.prepare.apply(this, arguments))
        {
          /** @cut */ basis.dev.info('Prepare handler returns trulthy result. Operation aborted. Context: ', this);
          return Promise.reject('Prepare handler returns trulthy result. Operation aborted. Context: ', this);
        }

        var request;
        var requestData = basis.object.complete({
          origin: this,
          bodyContext: {
            context: this,
            args: basis.array(arguments)
          }
        }, fn.request.apply(this, arguments));

        // if body is function take in account special action context
        if (typeof requestData.body == 'function')
        {
          var bodyFn = requestData.body;
          requestData.body = function(){
            return bodyFn.apply(this.context, this.args);
          };
        }

        // do a request
        if (request = getTransport().request(requestData))
          return new Promise(function(fulfill, reject){
            request.addHandler(PROMISE_REQUEST_HANDLER, {
              request: request,
              fulfill: fulfill,
              reject: reject
            });
          });

        return Promise.reject('Request is not performed');
      }
      else
      {
        /** @cut */ basis.dev.warn('Context in processing state. Operation aborted. Context: ', this);
        return Promise.reject('Context in processing state, request is not performed');
      }
    };
  }
956162
function transformConfig (config) {
	if (config === null || typeof config !== 'object') {
		config = {};
	}

	if (!Object.keys(config).length) {
		return {
			options: {},
			files: {
				ignore: [ignoreNodeModules()]
			}
		};
	}

	let runConfig = {
		options: {
			showMaxStack: 0
		}
	};

	if (config.noDisabling) {
		runConfig.options.noDisabling = true;
	}

	if (config.formatter) {
		runConfig.options.formatter = config.formatter;
	}
	if (config.showMaxStack >= 0) {
		runConfig.options.showMaxStack = config.showMaxStack;
	}
	if (config.outputFile) {
		runConfig.options['output-file'] = config.outputFile;
	}
	if (Array.isArray(config.ignore)) {
		runConfig.files = {
			ignore: config.ignore.concat(ignoreNodeModules())
		};
	} else {
		runConfig.files = {
			ignore: [ignoreNodeModules()]
		};
	}

	return runConfig;
}
386839
function build (config) {
  return new Promise((resolve, reject) => {
    const compiler = webpack(Object.assign(config, {
      output: { filename: 'file' },
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': '"production"',
          'process.browser': true
        })
      ]
    }), (err, stats) => {
      if (err || stats.hasErrors()) reject(err || new Error(stats.toString('errors-only')))
      const compilation = stats.compilation
      const compiler = compilation.compiler
      const memoryFs = compiler.outputFileSystem
      const outputFile = compilation.assets.file.existsAt
      resolve(memoryFs.readFileSync(outputFile, 'utf8'))
    })
    compiler.outputFileSystem = new MemoryFs()
  })
}
80683
function (config) {
        // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
        if (Transaction.databases[config.identity]) {
            // @todo - emit wrror event instead of console.log
            console.log('Warn: duplicate setup of connection found in Transactions.setup');
            this.teardown();
        }

        var _db;

        // clone the configuration
        config = util.clone(config);
        delete config.replication;

        // allow special transaction related config
        util.each(config, function (value, name, config) {
            if (!/^transaction.+/g.test(name)) { return; }

            // remove transaction config prefix
            var baseName = name.replace(/^transaction/g, '');
            baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);

            delete config[name];
            config[baseName] = value;
        });

        _db = db.createSource(config);

        // Save a few configurations
        _db && (_db.transactionConfig = {
            rollbackOnError: config.rollbackTransactionOnError
        });

        Transaction.databases[config.identity] = _db;
    }
95007
function nodeGo(config) {
        // Create the node
        RED.nodes.createNode(this, config)

        /** @since 2019-02-02 - the current instance name (url) */
        var uibInstance = config.url // for logging

        log.verbose(`[${uibInstance}] ================ instance registered ================`)

        /** A copy of 'this' object in case we need it in context of callbacks of other functions. @constant {Object} node */
        const node = this

        log.verbose(`[${uibInstance}] = Keys: this, config =`, {'this': Object.keys(node), 'config': Object.keys(config)})

        //#region --- Create local copies of the node configuration (as defined in the .html file)
        // NB: node.id and node.type are also available
        node.name          = config.name || ''
        node.topic         = config.topic || ''
        // TODO: Needs validation as a suitable URL path
        node.url           = config.url  || 'uibuilder'
        node.fwdInMessages = config.fwdInMessages        // @since 2017-09-20 changed to remove default, || with boolean doesn't work properly
        node.allowScripts  = config.allowScripts
        node.allowStyles   = config.allowStyles
        node.debugFE       = config.debugFE
        node.copyIndex     = config.copyIndex
        node.filename      = config.filename
        node.format        = config.format
        node.template      = config.template
        //#endregion ----

        log.verbose(`[${uibInstance}] Node instance settings`, {'name': node.name, 'topic': node.topic, 'url': node.url, 'fwdIn': node.fwdInMessages, 'allowScripts': node.allowScripts, 'allowStyles': node.allowStyles, 'debugFE': node.debugFE })

        // Keep a log of the active instances @since 2019-02-02
        instances[node.id] = node.url
        log.verbose(`[${uibInstance}] Node Instances Registered`, instances)

        /** Name of the fs path used to hold custom files & folders for THIS INSTANCE of uibuilder
         *   Files in this folder are also served to URL but take preference
         *   over those in the nodes folders (which act as defaults) @type {string}
         */
        node.customFolder = path.join(uib_rootPath, node.url)

        /** User supplied vendor packages
         * & only if using dev folders (delete ~/.node-red/uibuilder/<url>/dist/index.html)
         * JK @since 2017-08-17 fix for non-existent properties and use getProps()
         * JK @since 2018-01-06 use uib_globalSettings instead of RED.settings.uibuilder. At least an empty array is returned.
         * @type {Array}
         */
        node.userVendorPackages = uiblib.getProps(RED,config,'userVendorPackages',null) || uiblib.getProps(RED,uib_globalSettings,'userVendorPackages',[])

        log.verbose(`[${uibInstance}] Node package details`, { 'usrVendorPkgs': node.userVendorPackages, 'customAppFldr': uib_rootPath, 'customFldr': node.customFolder } )

        //#region ---- Socket.IO instance configuration ----
        /** How many Socket clients connected to this instance? @type {integer} */
        node.ioClientsCount = 0
        /** How many msg's received since last reset or redeploy? @type {integer} */
        node.rcvMsgCount = 0
        /** The channel names for Socket.IO @type {Object} */
        node.ioChannels = {control: 'uiBuilderControl', client: 'uiBuilderClient', server: 'uiBuilder'}
        /** Make sure each node instance uses a separate Socket.IO namespace - WARNING: This HAS to match the one derived in uibuilderfe.js
         * @since v1.0.10, changed namespace creation to correct a missing / if httpNodeRoot had been changed from the default. @type {string} */
        node.ioNamespace = tilib.urlJoin(httpNodeRoot, node.url)
        //#endregion ---- ----

        log.verbose(`[${uibInstance}] Socket.io details`, { 'ClientCount': node.ioClientsCount, 'rcvdMsgCount': node.rcvMsgCount, 'Channels': node.ioChannels, 'Namespace': node.ioNamespace } )

        // Keep track of the number of times each instance is deployed.
        // The initial deployment = 1
        if ( deployments.hasOwnProperty(node.id) ) deployments[node.id]++
        else deployments[node.id] = 1
        log.verbose(`[${uibInstance}] Number of Deployments`, deployments[node.id] )

        // We need an http server to serve the page. @since 2019-02-04 removed httpAdmin - we only want to use httpNode for web pages
        const app = RED.httpNode // || RED.httpAdmin

        /** Provide the ability to have a ExpressJS middleware hook.
         * This can be used for custom authentication/authorisation or anything else.
         * The function must be defined in settings.js
         * @since v1.0.3 2017-12-15
         */
        var httpMiddleware = function(req,res,next) { next() }
        if ( uib_globalSettings.hasOwnProperty('middleware') ) {
            /** Is a uibuilder specific function available? */
            if ( typeof uib_globalSettings.middleware === 'function' ) {
                log.verbose(`[${uibInstance}] Using uibuilder specific middleware from settings.js`)
                httpMiddleware = uib_globalSettings.middleware
            }
        } else {
            /** If not, see if the Node-RED one is available and use that instead.
             * Use httNodeMiddleware function which is defined in settings.js
             * as for the http in/out nodes - normally used for authentication
             */
            if ( typeof RED.settings.httpNodeMiddleware === 'function' ) {
                log.verbose(`[${uibInstance}] Using Node-RED middleware from settings.js`)
                httpMiddleware = RED.settings.httpNodeMiddleware
            }
        }

        /** This ExpressJS middleware runs when the uibuilder page loads
         * @see https://expressjs.com/en/guide/using-middleware.html */
        function localMiddleware (req, res, next) {
            // Tell the client what Socket.IO namespace to use,
            // trim the leading slash because the cookie will turn it into a %2F
            res.setHeader('uibuilder-namespace', node.ioNamespace)
            res.cookie('uibuilder-namespace', tilib.trimSlashes(node.ioNamespace), {path: node.url, sameSite: true})
            next()
        }

        //#region ----- Create local folder structure ----- //
        var customStatic = function(req,res,next) { next() } // Dummy ExpressJS middleware, replaced by local static folder if needed
        var customFoldersOK = true
        // TODO: May be better as async calls - probably not, but a promisified version would be OK?
        // Make sure the global custom folder exists first
        try {
            fs.mkdirSync(uib_rootPath) // try to create
            fs.accessSync( uib_rootPath, fs.constants.W_OK ) // try to access
        } catch (e) {
            if ( e.code !== 'EEXIST' ) { // ignore folder exists error
                log.error(`[${uibInstance}] Custom folder ERROR, path: ${uib_rootPath}`, e.message)
                customFoldersOK = false
            }
        }
        // make sure the folder for this node instance exists
        try {
            fs.mkdirSync(node.customFolder)
            fs.accessSync(node.customFolder, fs.constants.W_OK)
        } catch (e) {
            if ( e.code !== 'EEXIST' ) {
                log.error(`[${uibInstance}] Local custom folder ERROR`, e.message)
                customFoldersOK = false
            }
        }
        // Then make sure the DIST & SRC folders for this node instance exist
        try {
            fs.mkdirSync( path.join(node.customFolder, 'dist') )
            fs.mkdirSync( path.join(node.customFolder, 'src') )
        } catch (e) {
            if ( e.code !== 'EEXIST' ) {
                log.error(`[${uibInstance}] Local custom dist or src folder ERROR`, e.message)
                customFoldersOK = false
            }
        }

        // We've checked that the custom folder is there and has the correct structure
        if ( customFoldersOK === true ) {
            // local custom folders are there ...
            log.debug(`[${uibInstance}] Using local front-end folders in`, node.customFolder)

            /** Now copy files from the master template folder (instead of master src) @since 2017-10-01
             *  Note: We don't copy the master dist folder
             *  Don't copy if copy turned off in admin ui 
             * TODO: always copy index.html */
            if ( node.copyIndex ) {
                const cpyOpts = {'overwrite':false, 'preserveTimestamps':true}
                fs.copy( path.join( masterTemplateFolder, templateToUse ), path.join(node.customFolder, 'src'), cpyOpts, function(err){
                    if(err){
                        log.error(`[${uibInstance}] Error copying template files from ${path.join( __dirname, 'templates')} to ${path.join(node.customFolder, 'src')}`, err)
                    } else {
                        log.debug(`[${uibInstance}] Copied template files to local src (not overwriting)`, node.customFolder )
                    }
                })
            }
        } else {
            // Local custom folders are not right!
            log.error(`[${uibInstance}] Wanted to use local front-end folders in ${node.customFolder} but could not`)
        }

        //#region Add static path for local custom files
        // TODO: need a build capability for dist - nb probably keep vendor and private code separate
        try {
            // Check if local dist folder contains an index.html & if NR can read it - fall through to catch if not
            fs.accessSync( path.join(node.customFolder, 'dist', 'index.html'), fs.constants.R_OK )
            // If the ./dist/index.html exists use the dist folder...
            log.debug(`[${uibInstance}] Using local dist folder`)
            customStatic = serveStatic( path.join(node.customFolder, 'dist') )
            // NOTE: You are expected to have included vendor packages in
            //       a build process so we are not loading them here
        } catch (e) {
            // dist not being used or not accessible, use src
            log.debug(`[${uibInstance}] Dist folder not in use or not accessible. Using local src folder`, e.message )
            customStatic = serveStatic( path.join(node.customFolder, 'src') )
            // Include vendor resource source paths if needed
            node.userVendorPackages.forEach(function (packageName) {
                // @since 2017-09-19 Using get-installed-path to find where a module is actually installed
                // @since 2017-09-19 AND try require.resolve() as backup (NB this may return unusable path for linked modules)
                var installPath = ''
                try { //@since 2017-09-21 force cwd to be NR's UserDir - Colin Law
                    installPath = getInstalledPathSync(packageName, {local:true, cwd: userDir})
                } catch (e1) {
                    // if getInstalledPath fails, try nodejs internal resolve
                    try {
                        // @since 2017-11-11 v1.0.2 resolve returns the root script not the path
                        installPath = path.dirname( require.resolve(packageName) )
                    } catch (e2) {
                        log.error(`[${uibInstance}] Failed to add user vendor path - no install found for ${packageName}.  Try doing "npm install ${packageName} --save" from ${userDir}`, e2.message );
                        RED.log.warn(`uibuilder:${uibInstance}: Failed to add user vendor path - no install found for ${packageName}.  Try doing "npm install ${packageName} --save" from ${userDir}`)
                    }
                }
                if (installPath !== '') {
                    let vendorPath = tilib.urlJoin(node.url, 'vendor', packageName)
                    log.info(`[${uibInstance}] Adding user vendor path`, {
                        'url': vendorPath, 'path': installPath
                    })
                    app.use( vendorPath, serveStatic(installPath) )
                    vendorPaths[packageName] = {'url': vendorPath, 'path': installPath}
                }
            }) // -- end of forEach vendor package -- //
        }
        //#endregion -- Added static path for local custom files -- //
        //#endregion ------ End of Create custom folder structure ------- //

        /** Create a new, additional static http path to enable
         * loading of central static resources for uibuilder */
        var masterStatic = function(req,res,next) { next() }
        //Object.defineProperty(f, 'name', {value: myName, writable: false})
        try {
            // Will we use "compiled" version of module front-end code?
            fs.accessSync( path.join(__dirname, 'dist', 'index.html'), fs.constants.R_OK )
            log.debug(`[${uibInstance}] Using master production build folder`)
            // If the ./dist/index.html exists use the dist folder...
            masterStatic = serveStatic( path.join( __dirname, 'dist' ) )
        } catch (e) {
            // ... otherwise, use dev resources at ./src/
            log.debug(`[${uibInstance}] Using master src folder and master vendor packages` )
            log.debug('        Reason for not using master dist folder: ', e.message )
            masterStatic = serveStatic( path.join( __dirname, 'src' ) )
            // Include vendor resource source paths if needed
            vendorPackages.forEach(function (packageName) {
                // @since 2017-09-19 Using get-installed-path to find where a module is actually installed
                // @since 2017-09-19 AND try require.resolve() as backup (NB this may return unusable path for linked modules)
                var installPath = ''
                try { //@since 2017-09-21 force cwd to be NR's UserDir - Colin Law
                    installPath = getInstalledPathSync(packageName, {local:true, cwd: userDir})
                } catch (e1) {
                    // if getInstalledPath fails, try nodejs internal resolve
                    try {
                        // @since 2017-11-11 v1.0.2 resolve returns the root script not the path
                        installPath = path.dirname( require.resolve(packageName) )
                    } catch (e2) {
                        log.error(`[${uibInstance}] Failed to add master vendor path - no install found for ${packageName}. Should have been installed by this module`)
                        RED.log.warn(`uibuilder:${uibInstance}: Failed to add master vendor path - no install found for ${packageName}. Should have been installed by this module`)
                    }
                }
                if (installPath !== '') {
                    log.info(`[${uibInstance}] Adding master vendor path`, {
                        'url':  tilib.urlJoin(node.url, 'vendor', packageName), 'path': installPath
                    } )
                    app.use( tilib.urlJoin(node.url, 'vendor', packageName), serveStatic(installPath) )
                }
            })
        }

        app.use( tilib.urlJoin(node.url), httpMiddleware, localMiddleware, customStatic, masterStatic )

        const fullPath = tilib.urlJoin( httpNodeRoot, node.url ) // same as node.ioNamespace

        log.info(`[${uibInstance}] Version ${nodeVersion} started at URL ${fullPath}`)
        log.info(`[${uibInstance}] UI Source files at ${node.customFolder}`)
        RED.log.info(`uibuilder:${uibInstance}: UI Builder Version ${nodeVersion} started at URL ${fullPath}`)
        RED.log.info(`uibuilder:${uibInstance}: UI Source files at ${node.customFolder}`)

        //console.dir(app._router.stack)
        //if (debug && process.env.NODE_ENV === 'development') { // Only in dev environment
            // Absolute path to output file
            //var filepath = path.join(__dirname, './routes.generated.txt')
            // Invoke express-print-routes
            //require('express-print-routes')(app, filepath)
        //}

        // We only do the following if io is not already assigned (e.g. after a redeploy)
        uiblib.setNodeStatus( { fill: 'blue', shape: 'dot', text: 'Node Initialised' }, node )

        /** Each deployed instance has it's own namespace @type {Object.ioNameSpace} */
        var ioNs = io.of(node.ioNamespace)

        /** When someone loads the page, it will try to connect over Socket.IO
         *  note that the connection returns the socket instance to monitor for responses from
         *  the ui client instance */
        ioNs.on('connection', function(socket) {
            node.ioClientsCount++

            log.verbose(`[${uibInstance}] Socket connected, clientCount: ${node.ioClientsCount}, ID: ${socket.id}`)

            uiblib.setNodeStatus( { fill: 'green', shape: 'dot', text: 'connected ' + node.ioClientsCount }, node )

            // Let the clients (and output #2) know we are connecting & send the desired debug state
            uiblib.sendControl({
                'uibuilderCtrl': 'client connect',
                'cacheControl': 'REPLAY',          // @since 2017-11-05 v0.4.9 @see WIKI for details
                'debug': node.debugFE,
                '_socketId': socket.id,
                'from': 'server',
                // @since 2018-10-07 v1.0.9 - send server timestamp so that client can work out
                // time difference (UTC->Local) without needing clever libraries.
                'serverTimestamp': (new Date()),
            }, ioNs, node)
            //ioNs.emit( node.ioChannels.control, { 'uibuilderCtrl': 'server connected', 'debug': node.debugFE } )

            // if the client sends a specific msg channel...
            socket.on(node.ioChannels.client, function(msg) {
                log.debug(`[${uibInstance}] Data received from client, ID: ${socket.id}, Msg:`, msg)

                // Make sure the incoming msg is a correctly formed Node-RED msg
                switch ( typeof msg ) {
                    case 'string':
                    case 'number':
                    case 'boolean':
                        msg = { 'topic': node.topic, 'payload': msg}
                }

                // If the sender hasn't added msg._clientId, add the Socket.id now
                if ( ! msg.hasOwnProperty('_socketId') ) {
                    msg._socketId = socket.id
                }

                // Send out the message for downstream flows
                // TODO: This should probably have safety validations!
                node.send(msg)
            })
            socket.on(node.ioChannels.control, function(msg) {
                log.debug(`[${uibInstance}] Control Msg from client, ID: ${socket.id}, Msg:`, msg)

                // Make sure the incoming msg is a correctly formed Node-RED msg
                switch ( typeof msg ) {
                    case 'string':
                    case 'number':
                    case 'boolean':
                        msg = { 'uibuilderCtrl': msg }
                }

                // If the sender hasn't added msg._clientId, add the Socket.id now
                if ( ! msg.hasOwnProperty('_socketId') ) {
                    msg._socketId = socket.id
                }

                // @since 2017-11-05 v0.4.9 If the sender hasn't added msg.from, add it now
                if ( ! msg.hasOwnProperty('from') ) {
                    msg.from = 'client'
                }

                // Send out the message on port #2 for downstream flows
                uiblib.sendControl(msg, ioNs, node)  // fn adds topic if needed
                //node.send([null,msg])
            })

            socket.on('disconnect', function(reason) {
                node.ioClientsCount--
                log.debug(
                    `[${uibInstance}] Socket disconnected, clientCount: ${node.ioClientsCount}, Reason: ${reason}, ID: ${socket.id}`
                )
                if ( node.ioClientsCount <= 0) uiblib.setNodeStatus( { fill: 'blue', shape: 'dot', text: 'connected ' + node.ioClientsCount }, node )
                else uiblib.setNodeStatus( { fill: 'green', shape: 'ring', text: 'connected ' + node.ioClientsCount }, node )
                // Let the control output port know a client has disconnected
                uiblib.sendControl({
                    'uibuilderCtrl': 'client disconnect',
                    'reason': reason,
                    '_socketId': socket.id,
                    'from': 'server'
                }, ioNs, node)
                //node.send([null, {'uibuilderCtrl': 'client disconnect', '_socketId': socket.id, 'topic': node.topic}])
            })

            socket.on('error', function(err) {
                log.error(`[${uibInstance}] ERROR received, ID: ${socket.id}, Reason: ${err.message}`)
                // Let the control output port know there has been an error
                uiblib.sendControl({
                    'uibuilderCtrl': 'socket error',
                    'error': err.message,
                    '_socketId': socket.id,
                    'from': 'server'
                }, ioNs, node)
            })

            /* More Socket.IO events but we really don't need to monitor them
                socket.on('disconnecting', function(reason) {
                    RED.log.audit({
                        'UIbuilder': node.url+' DISCONNECTING received', 'ID': socket.id,
                        'data': reason
                    })
                })
                socket.on('newListener', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' NEWLISTENER received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('removeListener', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' REMOVELISTENER received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('ping', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' PING received', 'ID': socket.id,
                        'data': data
                    })
                })
                socket.on('pong', function(data) {
                    RED.log.audit({
                        'UIbuilder': node.url+' PONG received', 'ID': socket.id,
                        'data': data
                    })
                })
            */

        }) // ---- End of ioNs.on connection ---- //

        /** Handler function for node input events (when a node instance receives a msg)
         * @param {Object} msg The msg object received.
         **/
        function nodeInputHandler(msg) {
            log.verbose(`[${uibInstance}] nodeGo:nodeInputHandler - emit received msg - Namespace: ${node.url}`) //debug

            // If msg is null, nothing will be sent
            if ( msg !== null ) {
                // if msg isn't null and isn't an object
                // NOTE: This is paranoid and shouldn't be possible!
                if ( typeof msg !== 'object' ) {
                    // Force msg to be an object with payload of original msg
                    msg = { 'payload': msg }
                }
                // Add topic from node config if present and not present in msg
                if ( !(msg.hasOwnProperty('topic')) || msg.topic === '' ) {
                    if ( node.topic !== '' ) msg.topic = node.topic
                    else msg.topic = 'uibuilder'
                }
            }

            // Keep this fn small for readability so offload
            // any further, more customised code to another fn
            msg = uiblib.inputHandler(msg, node, RED, io, ioNs, log)

        } // -- end of msg received processing -- //

        // Process inbound messages
        node.on('input', nodeInputHandler)

        // Do something when Node-RED is closing down
        // which includes when this node instance is redeployed
        node.on('close', function(removed,done) {
            log.debug(`[${uibInstance}] nodeGo:on-close: ${removed?'Node Removed':'Node (re)deployed'}`)

            node.removeListener('input', nodeInputHandler)

            // Do any complex close processing here if needed - MUST BE LAST
            //processClose(null, node, RED, ioNs, io, app) // swap with below if needing async
            uiblib.processClose(done, node, RED, ioNs, io, app, log, instances)

            done()
        })

    }
192450
function buildConfig (_config) {
  _config.datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore', {}))

  return _config
}
145505
async function create(sourcedir) {
	const target = join(sourcedir, FILENAME);
	const exists = await exist(target);

	const source = exists
		? target
		: join(__dirname, FILENAME)
	;

	const content = await readFile(source);
	await writeFile(primed, content.toString());

	return exists
		?	'Creating a new Dangerfile'
		: 'Creating a default Dangerfile'
	;
}
823939
public static function create(Config $config)
    {
        if (php_sapi_name() === 'cli' || !(self::$instance instanceof self)) {
            self::$instance = new self($config);
        }

        return self::$instance;
    }
149395
function createEvent(config) {
  const { type, target } = config;
  const eventObject = new Event(type);

  if (target) {
    eventObject.target = target;
    eventObject.srcElement = target;
    eventObject.currentTarget = target;
  }

  return eventObject;
}