/*
Define a helper function to check and rewport that a windows .dll file is
the correct version of LJM.
485741
function windowsHelperCheckLJMVersion(libLocation, libraryVersion, ljmVersion) {
    var isCorrectVersion = false;
    // On windows we can do a direct compare.
    if(libraryVersion === ljmVersion) {
        // Congrats, we have found the required version of LJM!

        // Debugging info...
        if(DEBUG_LJM_LIBRARY_LOCATION_SELECTION) {
            console.log('Found Library!', libLocation);
        }

        // Indicate that we have not found the required version of LJM.
        isCorrectVersion = true;
    } else {
        // We have not found the required version of LJM.
    
        // Debugging info...
        if(DEBUG_LJM_LIBRARY_LOCATION_SELECTION) {
            console.log('Library:', libLocation);
            console.log('Is the wrong version:', libraryVersion, ljmVersion);
        }

        // Indicate that we have not found the required version of LJM.
        isCorrectVersion = false;
    }
    return isCorrectVersion;
}
1345382
function compileFile(module, filename) {
		const templateString = fs.readFileSync(filename, 'utf8');

		module.exports = handlebars.compile(templateString);
	}
123550
function wlCheck(wl, record, value) {
  if (!value) value = 'allow';

  let wlItem = _.get(wl, record);

  if (_.isArray(wlItem)) return wlItem.indexOf(value) !== -1;

  return wlItem === value;
}
588197
function updateServicesJS(newFileName) {

  console.log(" 🔰  updating: ".cyan + "components.js".white);

  if (process.cwd().includes('client/app/services') === false) {
    process.chdir(`./client/app/services`);
  }

  if (process.cwd().includes(`client/app/services/${newFileName}`) === true) {
    process.chdir('..');
  }

  componentsArray = [];
  genArr = [];


  // sync with updates
  fs.readdir(process.cwd(), function (err, items) {
    genArr = items;
    generateDirectArray(genArr);
  });


  function generateDirectArray(items) {
    for (var i = 0; i < items.length; i++) {
      if (isDirectory(items[i])) {
      } else {
        componentsArray.push(items[i]);
      }
    }
    importStringGenerator();
  }

  function isDirectory(inputString) {
    var str = inputString;
    var patt = new RegExp("[.]");
    var res = patt.test(str);
    return res;
  }

  function importStringGenerator() {

    genString = "";
    for (var i = 0; i < componentsArray.length; i++) {
      genString = genString + `import ${componentsArray[i]}Service from './${componentsArray[i]}/${componentsArray[i]}';\r`
    }

    listString = "";
    for (var i = 0; i < componentsArray.length; i++) {

      // check if last in list in order to not include comma
      if (i === (componentsArray.length - 1)) {
        listString = listString + `  .service('${componentsArray[i]}Service', ${componentsArray[i]}Service);` + `\r`
      } else {
        listString = listString + `  .service('${componentsArray[i]}Service', ${componentsArray[i]}Service)` + `\r`
      }
    }


    fs.writeFile("services.js", `import angular from 'angular';
${genString}

const ServicesModule = angular.module('app.services', [])
${listString}

export default ServicesModule;`, function (err) {
      if (err) {
        return console.log(` ❌  failed to update due to error:  ${err}`);
      }
      console.log(" 🔰  updated: ".cyan + "services.js".white);
    });
  }
}
1202635
async function exportCustomSelectorsToMjsFile(to, customSelectors) {
	const mjsContents = Object.keys(customSelectors).reduce((mjsLines, name) => {
		mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(customSelectors[name])}'`);

		return mjsLines;
	}, []).join(',\n');
	const mjs = `export const customSelectors = {\n${mjsContents}\n};\n`;

	await writeFile(to, mjs);
}
458497
function updateComponentsJS(newFileName) {

  console.log(" 🔰  updating: ".cyan + "components.js".white);

  if (process.cwd().includes('client/app/components') === false) {
    process.chdir(`./client/app/components`);
  }

  componentsArray = [];
  genArr = [];


  // sync app.component with updates
  fs.readdir(process.cwd(), function (err, items) {
    genArr = items;
    generateDirectArray(genArr);
  });


  function generateDirectArray(items) {
    for (var i = 0; i < items.length; i++) {
      if (isDirectory(items[i])) {
      } else {
        componentsArray.push(items[i]);
      }
    }
    importStringGenerator();
  }

  function isDirectory(inputString) {
    var str = inputString;
    var patt = new RegExp("[.]");
    var res = patt.test(str);
    return res;
  }

  String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
  }

  function importStringGenerator() {
    if (typeof newFileName != 'undefined') {
      componentsArray.push(`${newFileName}`);
    }

    genString = "";
    for (var i = 0; i < componentsArray.length; i++) {
      genString = genString + `    import ${componentsArray[i].capitalizeFirstLetter()}Module from './${componentsArray[i]}/${componentsArray[i]}.module';\r`
    }
    listString = "";
    for (var i = 0; i < componentsArray.length; i++) {

      // check if last in list in order to not include comma
      if (i === (componentsArray.length - 1)) {
        listString = listString + `     ${componentsArray[i].capitalizeFirstLetter()}Module` + `.name \r`
      } else {
        listString = listString + `     ${componentsArray[i].capitalizeFirstLetter()}Module` + '.name, \r'
      }

    }


    fs.writeFile("components.js", `import angular from 'angular';
${genString}

const ComponentsModule = angular.module('app.components',[
  ${listString}
]);

export default ComponentsModule;

  `, function (err) {
      if (err) {
        return console.log(` ❌  failed to update due to error:  ${err}`);
      }
      console.log(" 🔰  updated: ".cyan + "components.js".white);
    });
  }
}
577437
function warnAboutGlobalCode (sandbox, path)
  {
    var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL +
      (path ? reportErrorLocation (path) : '') +
      getExplanation (
        'This kind of code will behave differently between release and debug builds.' + NL +
        'You should wrap it in a self-invoking function and/or assign global variables/functions ' +
        'directly to the window object.'
      )
    );
    if (context.verbose) {
      var found = false;
      util.forEachProperty (sandbox, function (k, v)
      {
        if (!found) {
          found = true;
          msg += '  Detected globals:'.yellow + NL;
        }
        msg += (typeof v === 'function' ? '    function '.blue : '    var      '.blue) + k.cyan + NL;
      });
    }
    warn (msg + '>>'.yellow);
  }
950374
function AssemblyScriptLiveLoader(source) {
    var jsModule;
    var wasmModule;
    if (this.cacheable) {
        this.cacheable();
    }
    this.addDependency(wasmFooterPath);
    jsModule = createJsModule(source);
    wasmModule = createWasmModule(source, compile(source));
    return createCompatibleModule(jsModule, wasmModule);
}
894902
function __eval(__source, __global, load) {
    // Hijack System.register to set declare function
    System.__curRegister = System.register;
    System.register = function(name, deps, declare) {
      // store the registered declaration as load.declare
      load.declare = typeof name == 'string' ? declare : deps;
    }
    eval('var __moduleName = "' + (load.name || '').replace('"', '\"') + '"; (function() { ' + __source + ' \n }).call(__global);');

    System.register = System.__curRegister;
    delete System.__curRegister;
  }
756317
function shouldRenameDeclaration(name, path, binding, rootScope) {
  const isRootScope = path.scope === rootScope;
  const isGlobal = isRootScope && name in rootScope.globals;
  const program = rootScope.path;

  if (isGlobal) return false;

  if (!isRootScope) {
    const functionParent = path.getFunctionParent();
    const declarationParent = getDeclarationParent(path);

    // Bail if not a declaration or is property/key of object
    if (!declarationParent || isPropertyOrKey(path)) return false;

    if (declarationParent.isBlockScoped()) {
      // Handle function declaration (which defines it's own scope)
      if (declarationParent.isFunctionDeclaration()) {
        return declarationParent.parentPath.scope === rootScope && declarationParent.node.id === path.node;
      }
      // Skip let/const in block scope
      return false;
      // Handle re-assignment of root bound declaration (ignore function expressions)
    } else if (declarationParent.isAssignmentExpression() && !path.parentPath.isFunctionExpression()) {
      const declarationBinding = declarationParent.scope.getBinding(name);

      return declarationBinding ? declarationBinding.scope === rootScope : false;
      // Skip if in function scope
    } else if (functionParent !== program) {
      return false;
    }
  }

  // Skip if property or key of object
  return !isPropertyOrKey(path);
}
159352
function jslintFile(file, extraArgs) {
    return readConf(homeDir, {})
        .then(function (homeConf) {
            if (Array.isArray(file)) {
                return file.reduce(function (prom, file) {
                    return prom.then(function (oldReport) {
                        return jslintFile(file, extraArgs)
                            .then(function (newReport) {
                                return oldReport.concat(newReport);
                            });
                    });
                }, Promise.resolve([]));
            }
            return readFile(file, "utf8")
                .then(function (data) {
                    const opts = (
                        typeof extraArgs === "object" && extraArgs !== null
                    )
                        ? extraArgs
                        : {};
                    const projectDir = opts.projectDir || process.cwd();
                    return readConf(projectDir, path.dirname(file), homeConf)
                        .then(function (conf) {
                            const newConf = Object.assign(
                                {},
                                conf,
                                opts.options
                            );
                            const lines = Array.isArray(data)
                                ? data
                                : data.split(/\n|\r\n?/);
                            const sb = opts.shaBang
                                ? lines[0].startsWith("#!")
                                    ? [""].concat(lines.slice(1))
                                    : lines
                                : lines;
                            const report = {
                                pathname: file,
                                report: jslint(sb, newConf, opts.globals)
                            };

                            return typeof opts.callback === "function"
                                ? opts.callback(report)
                                : report;
                        });
                });
        });
}
123500
function checkImportCall(node) {
    if (node.callee.type !== 'Import') return
    if (node.arguments.length !== 1) return

    const modulePath = node.arguments[0]
    if (modulePath.type !== 'Literal') return
    if (typeof modulePath.value !== 'string') return

    checkSourceValue(modulePath, node)
  }
1082788
private void debugVerifyCatalog(InMemoryJarfile origJarFile, Catalog origCatalog)
    {
        final VoltCompiler autoGenCompiler = new VoltCompiler(m_isXDCR);
        // Make the new compiler use the original jarfile's classloader so it can
        // pull in the class files for procedures and imports
        autoGenCompiler.m_classLoader = origJarFile.getLoader();
        List<VoltCompilerReader> autogenReaderList = new ArrayList<>(1);
        autogenReaderList.add(new VoltCompilerJarFileReader(origJarFile, AUTOGEN_DDL_FILE_NAME));
        InMemoryJarfile autoGenJarOutput = new InMemoryJarfile();
        autoGenCompiler.m_currentFilename = AUTOGEN_DDL_FILE_NAME;
        // This call is purposely replicated in retryFailedCatalogRebuildUnderDebug,
        // where it provides an opportunity to set a breakpoint on a do-over when this
        // mainline call produces a flawed catalog that fails the catalog diff.
        // Keep the two calls in synch to allow debugging under the same exact conditions.
        Catalog autoGenCatalog = autoGenCompiler.compileCatalogInternal(null, null,
                autogenReaderList, autoGenJarOutput);
        if (autoGenCatalog == null) {
            Log.info("Did not verify catalog because it could not be compiled.");
            return;
        }

        FilteredCatalogDiffEngine diffEng =
                new FilteredCatalogDiffEngine(origCatalog, autoGenCatalog, false);
        String diffCmds = diffEng.commands();
        if (diffCmds != null && !diffCmds.equals("")) {
            // This retry is disabled by default to avoid confusing the unwary developer
            // with a "pointless" replay of an apparently flawed catalog rebuild.
            // Enable it via this flag to provide a chance to set an early breakpoint
            // that is only triggered in hopeless cases.
            if (RETRY_FAILED_CATALOG_REBUILD_UNDER_DEBUG) {
                autoGenCatalog = replayFailedCatalogRebuildUnderDebug(
                        autoGenCompiler, autogenReaderList,
                        autoGenJarOutput);
            }
            // Re-run a failed diff more verbosely as a pre-crash test diagnostic.
            diffEng = new FilteredCatalogDiffEngine(origCatalog, autoGenCatalog, true);
            diffCmds = diffEng.commands();
            String crashAdvice = "Catalog Verification from Generated DDL failed! " +
                    "VoltDB dev: Consider" +
                    (RETRY_FAILED_CATALOG_REBUILD_UNDER_DEBUG ? "" :
                        " setting VoltCompiler.RETRY_FAILED_CATALOG_REBUILD_UNDER_DEBUG = true and") +
                    " setting a breakpoint in VoltCompiler.replayFailedCatalogRebuildUnderDebug" +
                    " to debug a replay of the faulty catalog rebuild roundtrip. ";
            VoltDB.crashLocalVoltDB(crashAdvice + "The offending diffcmds were: " + diffCmds);
        }
        else {
            Log.info("Catalog verification completed successfuly.");
        }
    }
919600
async function exportCustomSelectorsToCjsFile(to, customSelectors) {
	const jsContents = Object.keys(customSelectors).reduce((jsLines, name) => {
		jsLines.push(`\t\t'${escapeForJS(name)}': '${escapeForJS(customSelectors[name])}'`);

		return jsLines;
	}, []).join(',\n');
	const js = `module.exports = {\n\tcustomSelectors: {\n${jsContents}\n\t}\n};\n`;

	await writeFile(to, js);
}
474424
function checkWin32(directoryPath) {
  if (directoryPath.charAt(1) !== ':') {
    return new Promise((resolve, reject) => {
      reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`))
    })
  }

  return check(
    `wmic logicaldisk get size,freespace,caption`,
    driveData => {
      // Only get the drive which match the path
      const driveLetter = driveData[0]
      return directoryPath.startsWith(driveLetter)
    },
    {
      diskPath: 0,
      free: 1,
      size: 2
    }
  )
}
722475
function checkPhantomjsVersion(phantomPath) {
  console.log('Found PhantomJS at', phantomPath, '...verifying')
  return kew.nfcall(cp.execFile, phantomPath, ['--version']).then(function (stdout) {
    var version = stdout.trim()
    if (helper.version == version) {
      return true
    } else {
      console.log('PhantomJS detected, but wrong version', stdout.trim(), '@', phantomPath + '.')
      return false
    }
  }).fail(function (err) {
    console.error('Error verifying phantomjs, continuing', err)
    return false
  })
}
1024459
function hasFileInLocal(url, mockFileDir) {
    var filePath = findInLocal(url, mockFileDir);
    var status;
    try{
        status = fs.statSync(filePath);
    }catch(e){
        return false;
    }
    return status.isFile();
}