/*
Get source files for analytics subdirectories in top-level `analytics`
directory adjacent to Prebid.js.
Invoke with gulp <task> --analytics
Returns an array of source files for inclusion in build process
325753
function() {
    if (!argv.analytics) { return []; } // empty arrays won't affect a standard build

    const directoryContents = fs.readdirSync(ANALYTICS_PATH);
    return directoryContents
      .filter(file => isModuleDirectory(path.join(ANALYTICS_PATH, file)))
      .map(moduleDirectory => {
        const module = require(path.join(ANALYTICS_PATH, moduleDirectory, MANIFEST));
        return path.join(ANALYTICS_PATH, moduleDirectory, module.main);
      });
  }
1075074
function _getFiles (route) {
  const dir = route[0]
  const prefix = route.splice(1).join('/')

  return _browseDir(dir)
    .map(file => require(file))
    .reduce((acc, routes) => acc.concat(routes), [])
    .map(routes => _normalizeUrl(routes, prefix))
}
606546
function compileSass() {
    let tasks = [];

    Object.keys(config).forEach((key) => {
        let val = config[key];
        tasks.push(gulp.src(val.src)
            .pipe(plumber({ errorHandler: handleErrors }))
            .pipe(sourcemaps.init())
            .pipe(sass(config.settings))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(val.dest)));
    });

    return merge(tasks);
}
234776
function buildDocsTasks() {
    if(npmArgs.remain.indexOf('gentics-ui-core') === -1) {
        return new Promise(gulp.series(
            cleanDocsFolder,
            copyDocsFiles,
            copyJekyllConfig
        ));
    }
    return resolvePromiseDummy();
}
139505
function createTask(gulp, options, taskFile){
	var fn;
	var extension = path.extname(taskFile);
	var filename = path.basename(taskFile, extension);
	var task = require(taskFile)(gulp, options.data, loadGulpConfig.util, filename);
	if(Array.isArray(task)){
		fn = isFunction(task[task.length - 1]) ? task.pop() : void(0);
		gulp.task(filename, task, fn);
	}else if(isString(task)){
		gulp.task(filename, [task]);
	}else if(isFunction(task)){
		gulp.task(filename, task);
	}else if(isExotic(task)){
		keys(task).map(mapTaskObject.bind(this, filename, task)).forEach(function(task){
			if(task.cmds){
				if(isFunction(task.fn)){
					gulp.task(task.name, task.cmds, task.fn);
				}else{
					gulp.task(task.name, task.cmds);
				}
			}else{
				gulp.task(task.name, task.fn);
			}
		});
	}
}
1056324
function preload() {
		var path = config.gulpFiles;

		if (/^[^\/]/.test(path)) {
			path = config.basePath + '/' + path;
		}

		glob.sync(path + '/*/*.js').map(function(file) {
			return file.replace(path, '').split('/').filter(function(split) {
				return !!split;
			});
		}).forEach(function(file) {
			register(
				file[0],
				file[file.length - 1].replace(/\.js$/, ''),
				require(path + '/' + file.join('/'))
			);
		});

		console.log(chalk.cyan('Devour initialized'));

		if (config.verbose) {
			['task', 'pipe'].forEach(function(what) {
				console.log(
					'  - available %ss: %s',
					what,
					what in definitions ? chalk.green(Object.keys(definitions[what]).join(', ')) : chalk.yellow('none')
				);
			});
			console.log('');
		}
	}
71252
function(source) {
      var result = [];

      while(source.length > 0) {
        if(result.length > 0) {
          var nextTarget = source.pop();

          for(var i=0; i<result.length; i++) {
            var targetFile = result[i];

            var dependencies = dependenciesMap[targetFile].dependencies;

            var dependencyMatch = matchPatternFromArray(dependencies, dependenciesMap[nextTarget].dependencyPath.pattern);

            if(dependencyMatch) {
              break;
            }
          }

          // move dependent file to front
          result.splice(i, 0, nextTarget);

        } else {
          result.push(source.pop());
        }
      }

      return result;
    }
962305
function ( taskName ) {
			var task = grunt.config.get( "bundles" )[taskName];
			var retVal = [];
			if ( task ) {
				var sources = task.modules;
				if ( !sys.isEmpty( sources ) && !sys.isEmpty( sources.src ) ) {
					grunt.log.writeln( "Adding sources for " + taskName );
					retVal = sys.map( grunt.file.expand( sources, sources.src ), function ( item ) {
						return resolvePath( item );
					} );
				}
			}
			return retVal;
		}
589711
function zip() {
  var dist = 'dist';
  var ext = '.html';

  function getHtmlFiles(dir) {
    return fs.readdirSync(dir)
      .filter(function(file) {
        var fileExt = path.join(dir, file);
        var isHtml = path.extname(fileExt) == ext;
        return fs.statSync(fileExt).isFile() && isHtml;
      });
  }

  var htmlFiles = getHtmlFiles(dist);

  var moveTasks = htmlFiles.map(function(file){
    var sourcePath = path.join(dist, file);
    var fileName = path.basename(sourcePath, ext);

    var moveHTML = gulp.src(sourcePath)
      .pipe($.rename(function (path) {
        path.dirname = fileName;
        return path;
      }));

    var moveImages = gulp.src(sourcePath)
      .pipe($.htmlSrc({ selector: 'img'}))
      .pipe($.rename(function (path) {
        path.dirname = fileName + path.dirname.replace('dist', '');
        return path;
      }));

    return merge(moveHTML, moveImages)
      .pipe($.zip(fileName+ '.zip'))
      .pipe(gulp.dest('dist'));
  });

  return merge(moveTasks);
}
261319
function _client_compile_task(file) {

    var infile = amigo_js_dev_path + '/' +file;
    //var outfile = amigo_js_out_path + '/' +file;

    var b = browserify(infile);
    return b
    // not in npm, don't need in browser
	.exclude('ringo/httpclient')
	.bundle()
    // desired output filename to vinyl-source-stream
	.pipe(source(file))
	.pipe(gulp.dest(amigo_js_out_path));
}
1236334
function () {

    var outputFiles = [
      path.join(module.folders.dest, '**/*')
    ].concat(ignoreGlob);

    return gulp.src(outputFiles, { read: false })
      .pipe(filter(function (file) {
        return isFile(file);
      }))
      .pipe(clean({ force: true }));

  }
276520
function getFiles(folder = srcFolder){
  let all = [];
  let f = fs.readdirSync(folder);
  for(file of f){
    all.push(path.join(folder,file))
    if(fs.lstatSync(path.join(folder,file)).isDirectory()){
      all = all.concat(getFiles(path.join(folder,file)));
    }
  }
  return all;
}
855115
async function archiveWorkingDir(dirPath, archive) {
  // recursively collect all entries (files and directories)
  const allEntries = await collectFSEntries(dirPath, []);

  const process = (entry, cb) => {
    const p = relativePaths(dirPath, entry.path);
    if (p.length) {
      if (entry.stats.isDirectory()) {
        archive.append(null, { name: `${p}/` });
      } else {
        archive.append(fse.createReadStream(entry.path), { name: p });
      }
    }
    cb();
  };

  return new Promise((resolve, reject) => {
    async.eachSeries(
      allEntries,
      process,
      (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(archive);
        }
      },
    );
  });
}
1360624
async function buildSassFiles(files, outputDir, config) {
  const renderedFiles = await Promise.all(files.map(async file => {
    const css = await renderFile(file, config);
    return {file, css};
  }));

  await fs.ensureDir(outputDir);

  return Promise.all(renderedFiles.map(({file, css}) => {
    const outputFile = getOutputFile(file, outputDir);
    return writeFile(outputFile, css);
  }));
}
486119
function createBuildTask(filename, prefix, suffix) {
  return () =>
    gulp
      .src([
        `${closureLibRoot}/closure/goog/**/*.js`,
        `${closureLibRoot}/third_party/closure/goog/**/*.js`,
        'src/**/*.js'
      ], { base: '.' })
      .pipe(sourcemaps.init())
      .pipe(
        closureCompiler({
          js_output_file: filename,
          output_wrapper: `${prefix}%output%${suffix}`,
          entry_point: 'fireauth.exports',
          compilation_level: OPTIMIZATION_LEVEL,
          externs: [
            'externs/externs.js',
            'externs/grecaptcha.js',
            'externs/gapi.iframes.js',
            path.resolve(
              __dirname,
              '../firebase/externs/firebase-app-externs.js'
            ),
            path.resolve(
              __dirname,
              '../firebase/externs/firebase-error-externs.js'
            ),
            path.resolve(
              __dirname,
              '../firebase/externs/firebase-app-internal-externs.js'
            )
          ],
          language_out: 'ES5',
          only_closure_dependencies: true
        })
      )
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('dist'));
}
1088258
function getIncludes(ext, exclude) {
    var globs = [];

    modules.forEach(function (module) {

      if (!settings.release) {

        // Not in release mode:
        // Ensure the main module file is included first

        globs.push(module.folder + '/' + module.folder + ext);
        globs.push(module.folder + '/**/*' + ext);
      } else {

        // In release mode:
        // Include the minified version.

        globs.push(module.folder + '/' + module.folder + '.min' + ext);
      }

    });

    var res = gulp.src(globs, {
      read: false,
      cwd: path.resolve(settings.folders.dest)
    });

    if (exclude) {
      res = res.pipe(gfilter('!**/*' + exclude));
//      res = res.pipe(utils.dumpFilePaths());
    }

    return res;
  }
736527
function bundle(watch, cb) {
    // prevent gulp calling done callback more than once when watching
    var firstTime = true;

    gulp.src('www/build/app.ts')
        .pipe(sourcemaps.init())
        .pipe(gulp_jspm({selfExecutingBundle: true}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('www/build/js'));
    // compiler.run(compileHandler);
    compileHandler();

    function compileHandler(err, stats) {
        if (firstTime) {
            firstTime = false;
            cb();
        }
        // print build stats and errors
        // console.log(stats.toString(statsOptions));
    }

    return true;
}