Generates HTML files with YAML front matters from Prismic documents.

@param {Object} config - Config object.

@return {Promise} - Promise with no fulfillment value.
490133
function generatePrismicDocuments(config) {
  return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken })
    .then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`)))))
    .then(res => {
      util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`);
      if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`));
      const documents = prismic.reduce(res.results, false, config);

      // Populate config metadata with retrieved documents.
      if (!config.metadata) config.metadata = { $data: {} };
      _.merge(config.metadata.$data, documents);

      for (let docType in documents) {
        const c = _.get(config, `collections.${docType}`);

        if (c && c.permalink) {
          const subdir = `.prismic/${docType}`;
          const dir = path.join(path.join(config.base || ``, config.src || ``), subdir);
          c.pattern = path.join(subdir, `**/*`);

          documents[docType].forEach(doc => {
            const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`;
            const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`]));
            fs.mkdirsSync(dir);
            fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`);
          });
        }
      }

      return;
    });
}
287168
async function read(filename, options = undefined) {
  const {encoding, flag, ...opts} = normalizeOptions(options)

  if (!isNumber(filename)) {
    filename = await normalizePath(base, filename)

    opts.filename = filename
  }

  const content = await fs.readFile(filename, {encoding, flag})

  return yaml.load(content, opts)
}
1121147
function _createScript(config, options, scope={}) {
  if (!isString(config.content)) return config.content;
  const stringScript = wrap(config.content.replace(/^\#\!.*/, ''), scope);
  try {
    return new vm.Script(stringScript, options);
  } catch(error) { // These are not squashed as not evaluation errors but something else.
    if (_runError(error, module)) throw error;
  }
}
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();
            });

        });
    }
1022022
function write(config, filePath) {
    switch (path.extname(filePath)) {
        case ".js":
            writeJSConfigFile(config, filePath);
            break;

        case ".json":
            writeJSONConfigFile(config, filePath);
            break;

        case ".yaml":
        case ".yml":
            writeYAMLConfigFile(config, filePath);
            break;

        default:
            throw new Error("Can't write to unknown file type.");
    }
}
90299
function loadSimpleResourceMap(config) {
    return new Promise((resolve, reject) => {

        // Convert Jest config into glob pattern.
        let testPathDirs;
        let testFileExtensions;
        let generatedGlob;

        if (config.testPathDirs.length === 1) {
            testPathDirs = config.testPathDirs[0];
        } else {
            testPathDirs = '{' + config.testPathDirs.join(',') + '}';
        }

        if (config.testFileExtensions.length === 1) {
            testFileExtensions = config.testFileExtensions[0];
        } else {
            testFileExtensions = '{' + config.testFileExtensions.join(',') + '}';
        }

        generatedGlob = testPathDirs + '/' +
            '**/' + config.testDirectoryName + '/**/*.' + testFileExtensions;

        glob(generatedGlob, (err, files) => {
            if (err) {
                reject(err);
            } else {
                let resourceMap;
                resourceMap = {
                    resourcePathMap: {}
                };
                files.forEach(file => {
                    let fullPath = path.resolve(file);
                    resourceMap.resourcePathMap[fullPath] = {
                        path: fullPath
                    };
                });
                resolve(resourceMap);
            }
        });
    });
}
811910
function(config, sections) {

    function add(content) {
      if (!config) {
        config = [];
      }
      config.push(content);
    }

    sections.forEach(function(section) {

      if (section['sg-angular-directive']) {

        section['sg-angular-directive'].files = section['sg-angular-directive'].file;
        if (!(section['sg-angular-directive'].files instanceof Array)) {
          section['sg-angular-directive'].files = [
            section['sg-angular-directive'].files
          ];
        }

        add(section['sg-angular-directive']);
      }
    });

    return config;

  }
955659
def dump(config):
    

    return yaml.safe_dump(
        config.to_primitive(),
        default_flow_style=False,
        encoding='utf-8',
        allow_unicode=True)
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()
  })
}
435019
function () {
                var stream = new $.streamqueue({
                    objectMode: true
                });

                //Optionally injected additional javascript sourcecode
                injectIntoStream(stream, options.injectInto.js.pre);

                // App files without vendor files
                stream.queue(gulp.src(options.files.jsNoVendor));

                //Angular template files
                stream.queue(
                    gulp.src(options.files.partials)
                        .pipe($.htmlMinify())
                        .pipe($.angularTemplatecache(options.templateCacheOptions))
                );

                //Optionally injected additional javascript sourcecode
                injectIntoStream(stream, options.injectInto.js.post);

                return stream
                    .done()
                    .pipe($.angularFilesort())
                    .pipe($.concat(options.output.js.app))
                    .pipe($.generateOutPipe(options.paths.build, options.output.js.path, 'app.js', options.rev, $.jsMinify)());
            }
1343595
function writeYAMLConfigFile(config, filePath) {
    debug(`Writing YAML config file: ${filePath}`);

    // lazy load YAML to improve performance when not used
    const yaml = require("js-yaml");

    const content = yaml.safeDump(config, { sortKeys: true });

    fs.writeFileSync(filePath, content, "utf8");
}
1056436
function generateGruntfile (generatedConfig) {
  return function(grunt) {
    var path = require('path'),
        fs = require('fs');

    require('load-grunt-tasks')(grunt);

    grunt.initConfig(generatedConfig);

    grunt.registerTask('default', ['watch']);

    // Handle new files with that have a new, supported preprocessor
    grunt.event.on('watch', function(action, filepath) {
      var ext = path.extname(filepath);

      // Ignore directories
      if (fs.lstatSync(filepath).isDirectory()) return;

      if (action === 'added') {
        // This is a special message that's parsed by YA
        // to determine if support for an additional preprocessor is necessary
        // Note: this allows us to avoid controlling grunt manually within YA
        console.log('EXTADDED:' + ext);

      // Note: we don't do anything for newly added .js files
      // A new js file can't be the root unless it's changed to require
      // the current root and saved/changed
      } else if (action === 'changed' || action === 'deleted') {
        if (ext === '.js') {
          // Ignore bundles
          if (/.+bundle.js/g.test(filepath)) return;

          // Notify YA to recompute the roots and
          // generate a configuration
          console.log('JSCHANGED:' + filepath);
        }
      }
    });

    // For watching entire directories but allowing
    // the grunt.event binding to take care of it
    grunt.registerTask('noop', function () {});
  };
}
559229
async function buildConfig(file) {
  const { default: config } = await import(`${CONFIGS_PATH}/${file}`);
  const { creator, name, packageName } = config;

  creator
    .then((data) => {
      const stringifiedData = JSON.stringify(data);
      const generatedData = TEMPLATE.replace(/{{ data }}/, stringifiedData);
      const packageFile = path.resolve(PACKAGES_PATH, packageName, 'index.js');
      fs.writeFileSync(packageFile, generatedData);
    })
    .then(
      () => console.log(`Finished building ${name} config to ./packages/${packageName}`),
      error => console.log(error),
    );
}
1090279
function (config) {
    /**
     * The iterator function, which is called on each component.
     *
     * @param  {string} version    the version of the component
     * @param  {string} component  the name of the component
     * @return {undefined}
     */
    return function (version, component) {
        var dep = config.get('global-dependencies').get(component) || {
            main: '',
            type: '',
            name: '',
            dependencies: {}
        };

        console.log(version, component);

        var componentConfigFile = findComponentConfigFile(config, component);
        var warnings = config.get('warnings');

        var overrides = config.get('overrides');

        if (overrides && overrides[component]) {
            if (overrides[component].dependencies) {
                componentConfigFile.dependencies = overrides[component].dependencies;
            }

            if (overrides[component].main) {
                componentConfigFile.main = overrides[component].main;
            }
        }

        var mains = findMainFiles(config, component, componentConfigFile);
        var fileTypes = _.chain(mains).map(path.extname).unique().value();

        dep.main = mains;
        dep.type = fileTypes;
        dep.name = componentConfigFile.name;

        var depIsExcluded = _.find(config.get('exclude'), function (pattern) {
            return path.join(config.get('bower-directory'), component).match(pattern);
        });

        if (dep.main.length === 0 && !depIsExcluded) {
            // can't find the main file. this config file is useless!
            warnings.push(component + ' was not injected in your file.');
            warnings.push(
                'Please go take a look in "' + path.join(config.get('bower-directory'), component) + '" for the file you need, then manually include it in your file.');

            config.set('warnings', warnings);
            return;
        }

        if (componentConfigFile.dependencies) {
            dep.dependencies = componentConfigFile.dependencies;

            _.each(componentConfigFile.dependencies, gatherInfo(config));
        }

        config.get('global-dependencies').set(component, dep);
    };
}
1366591
function createConfig(target /*: Target */, dev /*: boolean */,
        minimize /*: boolean */) /*: Object */ {
    const cssLoaders /*: Array<Object> */ = [{loader: 'css-loader'}];
    if (minimize) {
        cssLoaders[0].options = {importLoaders: 1};
        cssLoaders.push({
            loader: 'postcss-loader',
            options: {plugins: [require('cssnano')()]},
        });
    }

    const lessOptions = {modifyVars: {
        version: `"${version}"`,
    }};

    // use only necessary fonts, overridable by environment variables
    let isCovered = false;
    for (const font of fonts) {
        const override = process.env[`USE_${font.toUpperCase()}`];
        const useFont = override === "true" || override !== "false" && !isCovered;
        lessOptions.modifyVars[`use-${font}`] = useFont;

        const support = caniuse.feature(caniuse.features[font]).stats;
        isCovered = isCovered || useFont && browserslist.every(browser => {
            const [name, version] = browser.split(' ');
            return !support[name] || support[name][version] === 'y';
        });
    }

    return {
        mode: dev ? 'development' : 'production',
        context: __dirname,
        entry: {
            [target.name]: target.entry,
        },
        output: {
            filename: minimize ? '[name].min.js' : '[name].js',
            library: target.library,
            libraryTarget: 'umd',
            libraryExport: 'default',
            // Enable output modules to be used in browser or Node.
            // See: https://github.com/webpack/webpack/issues/6522
            globalObject: "(typeof self !== 'undefined' ? self : this)",
            path: path.resolve(__dirname, 'dist'),
            publicPath: dev ? '/' : '',
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: 'babel-loader',
                },
                {
                    test: /\.css$/,
                    use: [
                        dev ? 'style-loader' : MiniCssExtractPlugin.loader,
                        ...cssLoaders,
                    ],
                },
                {
                    test: /\.less$/,
                    use: [
                        dev ? 'style-loader' : MiniCssExtractPlugin.loader,
                        ...cssLoaders,
                        {
                            loader: 'less-loader',
                            options: lessOptions,
                        },
                    ],
                },
                {
                    test: /\.(ttf|woff|woff2)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: 'fonts/[name].[ext]',
                        },
                    }],
                },
            ],
        },
        externals: 'katex',
        plugins: [
            !dev && new MiniCssExtractPlugin({
                filename: minimize ? '[name].min.css' : '[name].css',
            }),
        ].filter(Boolean),
        devtool: dev && 'inline-source-map',
        optimization: {
            minimize,
            minimizer: [
                new TerserPlugin({
                    terserOptions: {
                        output: {
                            ascii_only: true,
                        },
                    },
                }),
            ],
        },
        performance: {
            hints: false,
        },
    };
}
118428
function writeConfigFile(config, yoRcPath = '.yo-rc.json') {
  let newYoRc = { ...config };
  if (FileUtils.doesFileExist(yoRcPath)) {
    const yoRc = JSON.parse(fs.readFileSync(yoRcPath, { encoding: 'utf-8' }));
    newYoRc = {
      ...yoRc,
      ...config,
      [GENERATOR_NAME]: {
        ...yoRc[GENERATOR_NAME],
        ...config[GENERATOR_NAME]
      }
    };
  }
  fs.writeFileSync(yoRcPath, JSON.stringify(newYoRc, null, 2));
}
269056
function loadConfigFile(configInfo) {
    const { filePath } = configInfo;
    let config;

    switch (path.extname(filePath)) {
        case ".js":
            config = loadJSConfigFile(filePath);
            if (configInfo.configName) {
                config = config.configs[configInfo.configName];
                if (!config) {
                    throw configMissingError(configInfo.configFullName);
                }
            }
            break;

        case ".json":
            if (path.basename(filePath) === "package.json") {
                config = loadPackageJSONConfigFile(filePath);
                if (config === null) {
                    return null;
                }
            } else {
                config = loadJSONConfigFile(filePath);
            }
            break;

        case ".yaml":
        case ".yml":
            config = loadYAMLConfigFile(filePath);
            break;

        default:
            config = loadLegacyConfigFile(filePath);
    }

    return ConfigOps.merge(ConfigOps.createEmptyConfig(), config);
}