Returns build config for entries
@returns {!Promise<!{entries, dependencies, commons}>}
488825
async function getBuildConfig() {
	const entries = await $C(vinyl.src(path.join(entry(), '*.js'), {read: false}))
		.async
		.to({})
		.reduce((res, el) => {
			const
				src = el.path,
				name = path.basename(src, '.js');

			let source;
			function getSource() {
				source = source || fs.readFileSync(src, 'utf-8');
				return source;
			}

			res[name] = {
				path: src,

				get source() {
					return getSource();
				},

				get parent() {
					return $C(getEntryParents(getSource())).one.get();
				},

				get parents() {
					return getEntryParents(getSource());
				},

				getRuntimeDependencies({cache} = {}) {
					return getEntryRuntimeDependencies(path.dirname(src), getSource(), {cache});
				}
			};

			return res;
		});

	function factory(entries) {
		function filter(cb) {
			return factory($C(entries).filter(cb).map());
		}

		return {
			entries,
			filter,
			getUnionEntryPoints({cache} = {}) {
				return getUnionEntryPoints(entries, {cache});
			}
		};
	}

	return factory(entries);
}
1329255
function getBuildFactory(build) {
  return function createBuild(inputpath, outputname) {
    const input = path.relative(process.cwd(), inputpath);
    let parent = build;

    if (!parent.builds.some(build => build.input == input)) {
      const outputpath = path.join(path.dirname(parent.outputpaths[0]), outputname);
      const buildConfig = {
        batch: parent.batch,
        boilerplate: false,
        bootstrap: false,
        browser: parent.browser,
        bundle: parent.bundle,
        fileCache: parent.fileCache,
        index: ++numBuilds,
        input,
        inputpaths: [inputpath],
        isAppServer: false,
        isDynamicBuild: true,
        label: '',
        level: parent.level + 1,
        output: path.relative(process.cwd(), path.dirname(outputpath)),
        outputpaths: [outputpath],
        parent,
        resolverCache: parent.resolverCache,
        runtimeOptions: parent.runtimeOptions,
        type: parent.type,
        watchOnly: parent.watchOnly
      };
      const build = buildFactory(buildConfig);

      build.fileFactoryOptions = getFileFactoryOptions(
        build,
        parent,
        null,
        null,
        Object.assign({}, parent.fileFactoryOptions)
      );
      build.fileFactory = build.fileFactoryOptions.fileFactory;
      parent.builds.push(build);
      parent.childInputpaths.push(inputpath);
    }

    // Find root build
    while (parent.parent)
      parent = parent.parent;
    parent.processFilesOptions.importBoilerplate = true;
  };
}
50111
function() {
        var self = this;

        self._modules = [];

        return new Promise(function(resolve, reject) {
            var base;
            var processors = [];

            if (self._options.base) {
                base = fs.readFileSync(path.resolve(self._options.base), 'utf8');
            }

            // For every file or folder, create a promise,
            // parse the file, extract the config and store it
            // to the global modules array.
            // Once all files are being processed, store the generated config.
            for (var i = 0; i < self._options.args.length; i++) {
                var file = self._options.args[i];

                var fileStats = fs.statSync(file);

                if (fileStats.isDirectory(file)) {
                    var walker = walk.walk(file, {
                        followLinks: false
                    });

                    walker.on('file', self._onWalkerFile.bind(self));

                    processors.push(self._onWalkerEnd(walker));
                } else if (fileStats.isFile()) {
                    processors.push(self._processFile(file));
                }
            }

            Promise.all(processors)
                .then(function(uselessPromises) {
                    return self._generateConfig();
                })
                .then(function(config) {
                    var content;

                    if (self._options.config) {
                        if (base) {
                            content = base + self._options.config + '.modules = ' + JSON.stringify(config) + ';';
                        } else {
                            content = 'var ' + self._options.config + ' = {modules: ' + JSON.stringify(config) + '};';
                        }
                    } else {
                        content = JSON.stringify(config);
                    }

                    return self._saveConfig(beautify(content));
                })
                .then(function(config) {
                    resolve(config);
                })
                .catch(function(error) {
                    reject(error);
                });
        });
    }
25204
function (buildConfig) {
        var src;
        if (buildConfig.nodeProject) {
            src = '<%=buildConfig.libDirectory%>/**/*.js';
        } else if (buildConfig.bowerJSON) {
            src = buildConfig.bowerJSON.main;
        }

        return src;
    }
855201
function getManifestEntriesFromCompilation(compilation, config) {
  const blacklistedChunkNames = config.excludeChunks;
  const whitelistedChunkNames = config.chunks;
  const {assets, chunks} = compilation;
  const {publicPath} = compilation.options.output;

  const assetMetadata = generateMetadataForAssets(assets, chunks);
  const filteredAssetMetadata = filterAssets(assetMetadata,
      whitelistedChunkNames, blacklistedChunkNames);

  const knownHashes = [
    compilation.hash,
    compilation.fullHash,
    ...getKnownHashesFromAssets(filteredAssetMetadata),
  ].filter((hash) => !!hash);

  const manifestEntries = [];
  for (const [file, metadata] of Object.entries(filteredAssetMetadata)) {
    // Filter based on test/include/exclude options set in the config,
    // following webpack's conventions.
    // This matches the behavior of, e.g., UglifyJS's webpack plugin.
    if (!ModuleFilenameHelpers.matchObject(config, file)) {
      continue;
    }

    const publicURL = resolveWebpackURL(publicPath, file);
    const manifestEntry = getEntry(knownHashes, publicURL, metadata.hash);
    manifestEntries.push(manifestEntry);
  }
  return manifestEntries;
}
452852
function configGen() {
  return {
    input: 'src/index.ts',
    output: {
      file: 'dist/web/buttplug.js',
      format: 'iife',
      name: "Buttplug"
    },
    plugins: [
      nodeResolve({
        jsnext: true,
        main: true,
        extensions: [ '.ts', '.js', '.json' ],
        browser: true
      }),
      typescript({ tsconfigOverride: { compilerOptions: { module: "ES2015" } } }),
      json(),
      nodeBuiltins(),
      nodeGlobals(),
      commonjs({
        // non-CommonJS modules will be ignored, but you can also
        // specifically include/exclude files
        include: ['../../node_modules/**', './node_modules/**'],  // Default: undefined
      }),
    ]
  };
}
284204
function () {
      var pkgs = this.pkgs;
      var configNames = _.chain(pkgs)
        .map(function (pkg) { return _.keys(pkg.config); })
        .flatten()
        .uniq()
        .value();

      // Take "first" config value in arrays as "winning" value.
      return _.chain(configNames)
        .map(function (name) {
          return [name, _.find(pkgs, function (pkg) {
            return _.has(pkg.config, name);
          }).config[name]];
        })
        // Object.
        .reduce(function (memo, pair) {
          memo[pair[0]] = pair[1];
          return memo;
        }, {})
        .value();
    }
686666
async function mergeRenovateConfig(config) {
  let returnConfig = { ...config };
  const fileList = await platform.getFileList();
  async function detectConfigFile() {
    for (const fileName of configFileNames) {
      if (fileName === 'package.json') {
        try {
          const pJson = JSON.parse(await platform.getFile('package.json'));
          if (pJson.renovate) {
            logger.info('Using package.json for global renovate config');
            return 'package.json';
          }
        } catch (err) {
          // Do nothing
        }
      } else if (fileList.includes(fileName)) {
        return fileName;
      }
    }
    return null;
  }
  const configFile = await detectConfigFile();
  if (!configFile) {
    logger.debug('No renovate config file found');
    return returnConfig;
  }
  logger.debug(`Found ${configFile} config file`);
  let renovateJson;
  if (configFile === 'package.json') {
    // We already know it parses
    renovateJson = JSON.parse(await platform.getFile('package.json')).renovate;
    logger.info({ config: renovateJson }, 'package.json>renovate config');
  } else {
    let renovateConfig = await platform.getFile(configFile);
    // istanbul ignore if
    if (renovateConfig === null) {
      logger.warn('Fetching renovate config returns null');
      throw new Error('registry-failure');
    }
    // istanbul ignore if
    if (!renovateConfig.length) {
      renovateConfig = '{}';
    }

    const fileType = path.extname(configFile);

    if (fileType === '.json5') {
      try {
        renovateJson = JSON5.parse(renovateConfig);
      } catch (err) /* istanbul ignore next */ {
        logger.debug(
          { renovateConfig },
          'Error parsing renovate config renovate.json5'
        );
        const error = new Error('config-validation');
        error.configFile = configFile;
        error.validationError = 'Invalid JSON5 (parsing failed)';
        error.validationMessage = 'JSON5.parse error: ' + err.message;
        throw error;
      }
    } else {
      let allowDuplicateKeys = true;
      let jsonValidationError = jsonValidator.validate(
        renovateConfig,
        allowDuplicateKeys
      );
      if (jsonValidationError) {
        const error = new Error('config-validation');
        error.configFile = configFile;
        error.validationError = 'Invalid JSON (parsing failed)';
        error.validationMessage = jsonValidationError;
        throw error;
      }
      allowDuplicateKeys = false;
      jsonValidationError = jsonValidator.validate(
        renovateConfig,
        allowDuplicateKeys
      );
      if (jsonValidationError) {
        const error = new Error('config-validation');
        error.configFile = configFile;
        error.validationError = 'Duplicate keys in JSON';
        error.validationMessage = JSON.stringify(jsonValidationError);
        throw error;
      }
      try {
        renovateJson = JSON.parse(renovateConfig);
      } catch (err) /* istanbul ignore next */ {
        logger.debug({ renovateConfig }, 'Error parsing renovate config');
        const error = new Error('config-validation');
        error.configFile = configFile;
        error.validationError = 'Invalid JSON (parsing failed)';
        error.validationMessage = 'JSON.parse error: ' + err.message;
        throw error;
      }
    }
    logger.info({ configFile, config: renovateJson }, 'Repository config');
  }
  const migratedConfig = await migrateAndValidate(config, renovateJson);
  if (migratedConfig.errors.length) {
    const error = new Error('config-validation');
    error.configFile = configFile;
    error.validationError =
      'The renovate configuration file contains some invalid settings';
    error.validationMessage = migratedConfig.errors
      .map(e => e.message)
      .join(', ');
    throw error;
  }
  if (migratedConfig.warnings) {
    returnConfig.warnings = returnConfig.warnings.concat(
      migratedConfig.warnings
    );
  }
  delete migratedConfig.errors;
  delete migratedConfig.warnings;
  logger.debug({ config: migratedConfig }, 'migrated config');
  // Decrypt before resolving in case we need npm authentication for any presets
  const decryptedConfig = decryptConfig(migratedConfig, config.privateKey);
  // istanbul ignore if
  if (decryptedConfig.npmrc) {
    logger.debug('Found npmrc in decrypted config - setting');
    npmApi.setNpmrc(decryptedConfig.npmrc);
  }
  // Decrypt after resolving in case the preset contains npm authentication instead
  const resolvedConfig = decryptConfig(
    await presets.resolveConfigPresets(decryptedConfig),
    config.privateKey
  );
  delete resolvedConfig.privateKey;
  logger.trace({ config: resolvedConfig }, 'resolved config');
  // istanbul ignore if
  if (resolvedConfig.npmrc) {
    logger.debug(
      'Ignoring any .npmrc files in repository due to configured npmrc'
    );
    npmApi.setNpmrc(resolvedConfig.npmrc);
    resolvedConfig.ignoreNpmrcFile = true;
  }
  // istanbul ignore if
  if (resolvedConfig.hostRules) {
    logger.info('Setting hostRules from config');
    resolvedConfig.hostRules.forEach(hostRules.update);
    delete resolvedConfig.hostRules;
  }
  returnConfig = mergeChildConfig(returnConfig, resolvedConfig);
  returnConfig.renovateJsonPresent = true;
  returnConfig.packageRules = flattenPackageRules(returnConfig.packageRules);
  // istanbul ignore if
  if (returnConfig.ignorePaths && returnConfig.ignorePaths.length) {
    logger.debug(
      { ignorePaths: returnConfig.ignorePaths },
      `Found repo ignorePaths`
    );
  }
  return returnConfig;
}
438669
function buildForBrowser() {
  return doBrowserify('pouchdb', 'lib/index-browser.js', {
    standalone: 'PouchDB'
  }).then(function (code) {
    code = comments.pouchdb + code;
    return all([
      writeFile(addPath('pouchdb', 'dist/pouchdb.js'), code),
      doUglify('pouchdb', code, comments.pouchdb, 'dist/pouchdb.min.js')
    ]);
  });
}
622768
function requireFunc() {
    if (typeof arguments[0] === 'string') {
      const dep = arguments[0];
      const got = defined(dep);
      if (got) return got.val;
      throw new Error(`commonjs dependency "${dep}" is not prepared.`);
    }

    return requirejs.apply(null, arguments);
  }
343117
function build() {
    const p = pending = new Emitter()
    buffer = bundler.toString()

    if (p !== pending) return
    pending.emit('ready', null, pending = false)
  }
410902
function build(base, config) {
  var result = resolver(base);
  Object.keys(config).forEach(function (key) {
    var value = config[key];
    if (typeof value === "string") {
      result[key] = resolver(result(value, true));
    } else if (Array.isArray(value) && value.length === 2 &&
        typeof value[0] === "string" &&  typeof value[1] === "object") {
      result[key] = build(result(value[0], true), value[1]);
    } else {
      throw new TypeError("Invalid value at: " + key);
    }
  });
  return result;
}
1225310
async function build() {
  console.time('Packager');

  let requires = [];
  let esmExportString = '';
  let cjsExportString = '';

  try {
    if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
    fs.writeFileSync(ROLLUP_INPUT_FILE, '');
    fs.writeFileSync(TEST_MODULE_FILE, '');

    // All the snippets that are Node.js-based and will break in a browser
    // environment
    const nodeSnippets = fs
      .readFileSync('tag_database', 'utf8')
      .split('\n')
      .filter(v => v.search(/:.*node/g) !== -1)
      .map(v => v.slice(0, v.indexOf(':')));

    const snippets = fs.readdirSync(SNIPPETS_PATH);
    const archivedSnippets = fs
      .readdirSync(SNIPPETS_ARCHIVE_PATH)
      .filter(v => v !== 'README.md');

    snippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(SNIPPETS_PATH, snippet);
      const snippetName = snippet.replace('.md', '');
      let code = getCode(rawSnippetString);
      if (nodeSnippets.includes(snippetName)) {
        requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
        code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
      }
      esmExportString += `export ${code}`;
      cjsExportString += code;
    });
    archivedSnippets.forEach(snippet => {
      const rawSnippetString = getRawSnippetString(
        SNIPPETS_ARCHIVE_PATH,
        snippet
      );
      cjsExportString += getCode(rawSnippetString);
    });

    requires = [
      ...new Set(
        requires
          .filter(Boolean)
          .map(v =>
            v[0].replace(
              'require(',
              'typeof require !== "undefined" && require('
            )
          )
      )
    ].join('\n');

    fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);

    const testExports = `module.exports = {${[...snippets, ...archivedSnippets]
      .map(v => v.replace('.md', ''))
      .join(',')}}`;

    fs.writeFileSync(
      TEST_MODULE_FILE,
      `${requires}\n\n${cjsExportString}\n\n${testExports}`
    );

    // Check Travis builds - Will skip builds on Travis if not CRON/API
    if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
      fs.unlink(ROLLUP_INPUT_FILE);
      console.log(
        `${chalk.green(
          'NOBUILD'
        )} Module build terminated, not a cron job or a custom build!`
      );
      console.timeEnd('Packager');
      process.exit(0);
    }

    await doRollup();

    // Clean up the temporary input file Rollup used for building the module
    fs.unlink(ROLLUP_INPUT_FILE);

    console.log(`${chalk.green('SUCCESS!')} Snippet module built!`);
    console.timeEnd('Packager');
  } catch (err) {
    console.log(`${chalk.red('ERROR!')} During module creation: ${err}`);
    process.exit(1);
  }
}
1203446
function getEntitlementFiles(preferences) {
    const files = [];
    const entitlements = path.join(
      preferences.projectRoot,
      "platforms",
      "ios",
      preferences.projectName,
      "Resources",
      `${preferences.projectName}.entitlements`
    );
    files.push(
      path.join(
        preferences.projectRoot,
        "platforms",
        "ios",
        preferences.projectName,
        `${preferences.projectName}.entitlements`
      )
    );
    files.push(entitlements);

    for (let i = 0; i < BUILD_TYPES.length; i++) {
      const buildType = BUILD_TYPES[i];
      const plist = path.join(
        preferences.projectRoot,
        "platforms",
        "ios",
        preferences.projectName,
        `Entitlements-${buildType}.plist`
      );
      files.push(plist);
    }

    return files;
  }
1175296
function getDepends(file, config) {
    var code = fs.readFileSync(file, 'utf8'),
        // only process the first module in file
        meta = ast.parse(code)[0],
        deps = ((meta || {}).dependencies || []).map(function (dep) {
            return idToPath(dep, config);
        });
    return deps;
}
18210
function getDependencies(jsSource) {
  const lines = jsSource.split('\n');
  const dependencies = {
    ol: pkg.version
  };
  for (let i = 0, ii = lines.length; i < ii; ++i) {
    const line = lines[i];
    const importMatch = line.match(importRegEx);
    if (importMatch) {
      const imp = importMatch[1];
      if (!imp.startsWith('ol/') && imp != 'ol') {
        const parts = imp.split('/');
        let dep;
        if (imp.startsWith('@')) {
          dep = parts.slice(0, 2).join('/');
        } else {
          dep = parts[0];
        }
        if (dep in pkg.devDependencies) {
          dependencies[dep] = pkg.devDependencies[dep];
        }
      }
    }
  }
  return dependencies;
}
1727
function prepareBuild(config) {

  function serve(exitCode) {

    // Save our exitCode for testing
    _exitCode = exitCode;

    // Reset skyuxconfig.json
    resetConfig();

    return server.start('unused-root', tmp)
      .then(port => browser.get(`https://localhost:${port}/dist/`));
  }

  writeConfig(config);

  return new Promise((resolve, reject) => {
    rimrafPromise(path.join(tmp, 'dist'))
      .then(() => exec(`node`, [cliPath, `build`, `--logFormat`, `none`], cwdOpts))
      .then(serve)
      .then(resolve)
      .catch(err => reject(err));
  });
}