By default, the shared configuration look for 2 entries, this is useful when
your project act both as an app by running the “main.js” and a library by
allowing the “index.js” to be imported.
19817
function getDefaultEntries() {
  let result = {}

  const PROJECT_MAIN = join(PROJECT_SRC_DIR, 'main.js')
  const PROJECT_INDEX = join(PROJECT_SRC_DIR, 'index.js')

  if (existsSync(PROJECT_MAIN))
    result.main = PROJECT_MAIN

  if (existsSync(PROJECT_INDEX))
    result.index = PROJECT_INDEX

  return result
}
1316645
async function build(previousFileSizes) {
  console.log(`${manifest.name}: Creating an optimized production build...`)

  // a project can opt to start
  let webpackConfig = get(manifest, 'skypager.webpack.merge') === false ? {} : config

  if (get(manifest, 'skypager.webpack.build')) {
    console.log(`Using custom wepack config`)
    let configToMerge = require(path.resolve(
      path.dirname(paths.appPackageJson),
      get(manifest, 'skypager.webpack.build')
    ))

    if (typeof configToMerge === 'function') {
      configToMerge = await Promise.resolve(configToMerge(argv.env || 'production', argv, config))
    }

    if (!isArray(configToMerge)) {
      // we won't try and merge webpack config if it is an array
      webpackConfig = configMerge(webpackConfig, configToMerge)
    } else {
      console.log('Using multiple webpack configs')
    }
  }

  const compiler = webpack(webpackConfig)

  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err)
      }

      const messages = formatWebpackMessages(stats.toJson({}, true))
      if (messages.errors.length) {
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1
        }
        console.log(`Build failed in ${manifest.name}`)
        return reject(new Error(messages.errors.join('\n\n')))
      }
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
          )
        )
        return reject(new Error(messages.warnings.join('\n\n')))
      }
      return resolve({
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      })
    })
  })
}
959588
function (runtime, name, fn, config) {
            name = indexMapStr(name);

            var mods = runtime.Env.mods,
                mod = mods[name];

            if (mod && mod.fn) {
                S.log(name + ' is defined more than once', 'warn');
                return;
            }

            // 没有 use，静态载入的 add 可能执行
            Utils.createModuleInfo(runtime, name);

            mod = mods[name];

            // 注意：通过 S.add(name[, fn[, config]]) 注册的代码，无论是页面中的代码，
            // 还是 js 文件里的代码，add 执行时，都意味着该模块已经 LOADED
            S.mix(mod, {
                name: name,
                status: LOADED,
                fn: fn
            });

            S.mix(mod, config);
        }
244395
function (cb, data, layout) {
            var self = this;
            var stack = new Y.Parallel();

            Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function (err, opts) {
                //console.log(opts);
                if (err) {
                    console.log(err);
                }
                opts.meta = Y.merge(opts.meta, data);

                opts.meta.title = self.data.project.name;
                opts.meta.moduleName = data.name;
                opts.meta.file = data.file;
                opts.meta.line = data.line;
                opts.meta = self.addFoundAt(opts.meta);
                opts.meta.projectRoot = '../';
                opts.meta.projectAssets = '../assets';
                opts.meta.projectLogo = self._resolveUrl(self.data.project.logo, opts);

                opts = self.populateClasses(opts);
                opts = self.populateModules(opts);
                opts = self.populateFiles(opts);

                opts.meta.classDescription = self._parseCode(self.markdown(data.description || ' '));

                opts.meta.methods = [];
                opts.meta.properties = [];
                opts.meta.attrs = [];
                opts.meta.events = [];
                opts.meta.extension_for = null;
                if (data.uses) {
                    opts.meta.uses = data.uses;
                }
                if (data.entension_for && data.extension_for.length) {
                    opts.meta.extension_for = data.extension_for;
                }

                if (data.extends) {
                    opts.meta.extends = data.extends;
                }

                var classItems = [];
                self.data.classitems.forEach(function (i) {
                    if (i.class === data.name) {
                        classItems.push(i);
                    }
                });

                classItems = self.mergeExtends(data, classItems, true);

                if (data.is_constructor) {
                    var i = Y.mix({}, data);
                    i = self.augmentData(i);
                    i.paramsList = [];
                    if (i.params) {
                        i.params.forEach(function (p) {
                            var name = p.name;
                            if (p.optional) {
                                name = '[' + name + ((p.optdefault) ? '=' + p.optdefault : '') + ']';
                            }
                            i.paramsList.push(name);
                        });
                    }
                    //i.methodDescription = self._parseCode(markdown(i.description));
                    i.hasAccessType = i.access;
                    i.hasParams = i.paramsList.length;
                    if (i.paramsList.length) {
                        i.paramsList = i.paramsList.join(', ');
                    } else {
                        i.paramsList = ' ';
                    }
                    i.returnType = ' ';
                    if (i["return"]) {
                        i.hasReturn = true;
                        i.returnType = i["return"].type;
                    }
                    //console.error(i);
                    opts.meta.is_constructor = [i];
                    if (i.example && i.example.length) {
                        if (i.example.forEach) {
                            var e = '';
                            i.example.forEach(function (v) {
                                e += self._parseCode(self.markdown(v));
                            });
                            i.example = e;
                        } else {
                            i.example = self._parseCode(self.markdown(i.example));
                        }
                    }
                }

                classItems.forEach(function (i) {
                    var e;
                    switch (i.itemtype) {
                    case 'method':
                        i = self.augmentData(i);
                        i.paramsList = [];
                        if (i.params && i.params.forEach) {
                            i.params.forEach(function (p) {
                                var name = p.name;
                                if (p.optional) {
                                    name = '[' + name + ((p.optdefault) ? '=' + p.optdefault : '') + ']';
                                }
                                i.paramsList.push(name);
                            });
                        }
                        //i.methodDescription = self._parseCode(markdown(i.description || ''));
                        i.methodDescription = self._parseCode(i.description);
                        if (i.example && i.example.length) {
                            if (i.example.forEach) {
                                e = '';
                                i.example.forEach(function (v) {
                                    e += self._parseCode(self.markdown(v));
                                });
                                i.example = e;
                            } else {
                                i.example = self._parseCode(self.markdown(i.example));
                            }
                        }
                        i.hasAccessType = i.access;
                        i.hasParams = i.paramsList.length;
                        if (i.paramsList.length) {
                            i.paramsList = i.paramsList.join(', ');
                        } else {
                            i.paramsList = ' ';
                        }
                        i.returnType = ' ';
                        if (i["return"]) {
                            i.hasReturn = true;
                            i.returnType = i["return"].type;
                        }

                        // If this item is provided by a module other
                        // than the module that provided the original
                        // class, add the original module name to the
                        // item's `providedBy` property so we can
                        // indicate the relationship.
                        if ((i.submodule || i.module) !== (data.submodule || data.module)) {
                            i.providedBy = (i.submodule || i.module);
                        }

                        opts.meta.methods.push(i);
                        break;
                    case 'property':
                        i = self.augmentData(i);
                        //i.propertyDescription = self._parseCode(markdown(i.description || ''));
                        i.propertyDescription = self._parseCode(i.description);
                        if (!i.type) {
                            i.type = 'unknown';
                        }
                        if (i.final === '') {
                            i.final = true;
                        }
						if (i.readonly === '') {
							  i.readonly = true;
						}
                        if (i.example && i.example.length) {
                            if (i.example.forEach) {
                                e = '';
                                i.example.forEach(function (v) {
                                    e += self._parseCode(self.markdown(v));
                                });
                                i.example = e;
                            } else {
                                i.example = self._parseCode(self.markdown(i.example));
                            }
                        }

                        // If this item is provided by a module other
                        // than the module that provided the original
                        // class, add the original module name to the
                        // item's `providedBy` property so we can
                        // indicate the relationship.
                        if ((i.submodule || i.module) !== (data.submodule || data.module)) {
                            i.providedBy = (i.submodule || i.module);
                        }

                        opts.meta.properties.push(i);
                        break;

                    case 'attribute': // fallthru
                    case 'config':
                        i = self.augmentData(i);
                        //i.attrDescription = self._parseCode(markdown(i.description || ''));
                        i.attrDescription = self._parseCode(i.description);

                        if (i.itemtype === 'config') {
                            i.config = true;
                        } else {
                            i.emit = self.options.attributesEmit;
                        }
                        if (i.readonly === '') {
                            i.readonly = true;
                        }

                        if (i.example && i.example.length) {
                            if (i.example.forEach) {
                                e = '';
                                i.example.forEach(function (v) {
                                    e += self._parseCode(self.markdown(v));
                                });
                                i.example = e;
                            } else {
                                i.example = self._parseCode(self.markdown(i.example));
                            }
                        }

                        // If this item is provided by a module other
                        // than the module that provided the original
                        // class, add the original module name to the
                        // item's `providedBy` property so we can
                        // indicate the relationship.
                        if ((i.submodule || i.module) !== (data.submodule || data.module)) {
                            i.providedBy = (i.submodule || i.module);
                        }

                        opts.meta.attrs.push(i);
                        break;
                    case 'event':
                        i = self.augmentData(i);
                        //i.eventDescription = self._parseCode(markdown(i.description || ''));
                        i.eventDescription = self._parseCode(i.description);

                        if (i.example && i.example.length) {
                            if (i.example.forEach) {
                                e = '';
                                i.example.forEach(function (v) {
                                    e += self._parseCode(self.markdown(v));
                                });
                                i.example = e;
                            } else {
                                i.example = self._parseCode(self.markdown(i.example));
                            }
                        }

                        // If this item is provided by a module other
                        // than the module that provided the original
                        // class, add the original module name to the
                        // item's `providedBy` property so we can
                        // indicate the relationship.
                        if ((i.submodule || i.module) !== (data.submodule || data.module)) {
                            i.providedBy = (i.submodule || i.module);
                        }

                        opts.meta.events.push(i);
                        break;
                    }
                });

                opts.meta.attrs.sort(self.nameSort);
                opts.meta.events.sort(self.nameSort);
                opts.meta.methods.sort(self.nameSort);
                opts.meta.properties.sort(self.nameSort);

                if (!opts.meta.methods.length) {
                    delete opts.meta.methods;
                }
                if (!opts.meta.properties.length) {
                    delete opts.meta.properties;
                }
                if (!opts.meta.attrs.length) {
                    delete opts.meta.attrs;
                }
                if (!opts.meta.events.length) {
                    delete opts.meta.events;
                }

                var view = new Y.DocView(opts.meta);
                var mainLayout = opts.layouts[layout];
                self.render('{{>classes}}', view, mainLayout, opts.partials, stack.add(function (err, html) {
                    self.files++;
                    stack.html = html;
                    stack.view = view;
                    stack.opts = opts;
                }));
            });

            stack.done(function () {
                cb(stack.html, stack.view, stack.opts);
            });
        }
679098
function getConfig() {
  // Load the myrmex main configuration file
  let config = {};
  try {
    // try to load a myrmex.json or myrmex.js file
    config = require(path.join(process.cwd(), 'myrmex'));
  } catch (e) {
    // Silently ignore if there is no configuration file
    return config;
  }

  config.config = config.config || {};

  // Load sub-configuration files
  config.configPath = config.configPath || './config';
  const configPath = path.join(process.cwd(), config.configPath);
  let files = [];
  try {
    files = fs.readdirSync(configPath);
  } catch (e) {
    // Silently ignore if there is no configuration directory
  }
  files.forEach(file => {
    const parse = path.parse(file);
    // We load all .js and .json files in the configuration directory
    if (['.js', '.json'].indexOf(parse.ext) !== -1) {
      config.config[parse.name] = _.merge(config.config[parse.name] || {}, require(path.join(configPath, file)));
    }
  });

  // Add configuration passed by environment variables
  Object.keys(process.env).forEach(key => {
    const prefix = 'MYRMEX_';
    if (key.substring(0, prefix.length) === prefix) {
      // We transform
      //     MYRMEX_myConfig_levels = value
      // into
      //     { config: { myConfig: { levels: value } } }
      function addParts(config, parts, value) {
        const part = parts.shift();
        if (parts.length === 0) {
          // Convert string values "true" and "false" to booleans
          if (value === 'false') { value = false; }
          if (value === 'true') { value = true; }
          config[part] = value;
        } else {
          if (config[part] === undefined) {
            config[part] = {};
          }
          addParts(config[part], parts, value);
        }
      }
      addParts(config.config, key.substring(prefix.length).split('_'), process.env[key]);
    }
  });

  return config;
}
245537
function(suppliedConfig) {
    if (typeof suppliedConfig.sdk === 'undefined') suppliedConfig.sdk = {}
    if (suppliedConfig.app_key) suppliedConfig.sdk.appKey = suppliedConfig.app_key
    return $.extend(true, {}, defaultConfig.primary.sdk, suppliedConfig.sdk);
  }
263039
function bundle(entryPoints, config, callback) {
    const entryPointsMap = {};
    entryPoints.forEach((module) => {
        entryPointsMap[module.name] = module;
    });
    const allMentionedModulesMap = {};
    entryPoints.forEach((module) => {
        allMentionedModulesMap[module.name] = true;
        (module.include || []).forEach(function (includedModule) {
            allMentionedModulesMap[includedModule] = true;
        });
        (module.exclude || []).forEach(function (excludedModule) {
            allMentionedModulesMap[excludedModule] = true;
        });
    });
    const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
    const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
    const loaderModule = { exports: {} };
    r.call({}, require, loaderModule, loaderModule.exports);
    const loader = loaderModule.exports;
    config.isBuild = true;
    config.paths = config.paths || {};
    if (!config.paths['vs/nls']) {
        config.paths['vs/nls'] = 'out-build/vs/nls.build';
    }
    if (!config.paths['vs/css']) {
        config.paths['vs/css'] = 'out-build/vs/css.build';
    }
    loader.config(config);
    loader(['require'], (localRequire) => {
        const resolvePath = (path) => {
            const r = localRequire.toUrl(path);
            if (!/\.js/.test(r)) {
                return r + '.js';
            }
            return r;
        };
        for (const moduleId in entryPointsMap) {
            const entryPoint = entryPointsMap[moduleId];
            if (entryPoint.append) {
                entryPoint.append = entryPoint.append.map(resolvePath);
            }
            if (entryPoint.prepend) {
                entryPoint.prepend = entryPoint.prepend.map(resolvePath);
            }
        }
    });
    loader(Object.keys(allMentionedModulesMap), () => {
        const modules = loader.getBuildInfo();
        const partialResult = emitEntryPoints(modules, entryPointsMap);
        const cssInlinedResources = loader('vs/css').getInlinedResources();
        callback(null, {
            files: partialResult.files,
            cssInlinedResources: cssInlinedResources,
            bundleData: partialResult.bundleData
        });
    }, (err) => callback(err, null));
}
206595
function initLibraries(cfg = {}) {
	_.each(configMap, (keys, libName) => {
		let lib = libs[libName];
		let options = {};
		_.each(keys, (key) => options[key] = cfg[key]);
		lib.setOptions && lib.setOptions(options);
	});
}
150028
function initDir (config) {
    // create global dir config
    config.dir = {
        assets: [__dirname+'/assets'],
        app: [],
        components: [],
        helpers: [__dirname+'/helpers'],
        layouts: [__dirname+'/layouts'],
        partials: [__dirname+'/partials'],
        services: [],
        views: [__dirname+'/views'],
    }
    // iterate over modules getting and merging directories for each
    _.each(config.moduleNames, moduleName => {
        // get module
        var module = config.modules[moduleName]
        // iterate over dir configs
        _.each(config.dir, (dirs, dirName) => {
            // get directories for module
            var moduleDirs = getDir(module, dirName)
            // debug
            debug('initDir %s %s', moduleName, dirName, moduleDirs)
            // add module dirs to config
            _.each(moduleDirs, moduleDir => config.dir[dirName].push(moduleDir))
        })
    })
    // debug merged dirs
    debug('initDir', config.dir)
}
1128090
function getEntries(config) {
    assert_usage(config && config.entry);
    if( config.entry.constructor===String ) {
        return {main: [config.entry]};
    }
    if( config.entry.constructor===Array ) {
        return {main: [...config.entry]};
    }
    if( config.entry.constructor===Object ) {
        const entries = {};
        Object.entries(config.entry)
        .forEach(([entryName, entryFiles]) => {
            if( entryFiles && entryFiles.constructor===Array ) {
                entries[entryName] = [...entryFiles];
                return;
            }
            if( entryFiles && entryFiles.constructor===String ) {
                entries[entryName] = [entryFiles];
                return;
            }
            assert_usage(false, entryFiles, entryName);
        });
        return entries;
    }
    assert_usage(false);
}
17210
function getConfig(req, res, next) {
  var params = {
    appId: req.params.projectid || req.params.id
  };

  forms.getAppConfig(req.connectionOptions, params, formsResultHandlers(constants.resultTypes.formProjects, req, next));
}
1114770
function equalConfig(page, oldPage) {
  const keys = Object.keys(page.config || {});
  const oldKeys = Object.keys(oldPage.config || {});

  if (keys.length !== oldKeys.length) return false;
  if (keys.some(key => page.config[key] !== oldPage.config[key])) return false;
  return true;
}
509679
function mergeDefaultConfig(opts) {

    let devModeEnabled = isDevelopMode();
    let debugModeEnabled = isDebugMode();

    console.log('------------------------------------------------------------------------------------');
    console.log(`Executing build for ` + (devModeEnabled ? ENV_DEVELOPMENT : ENV_PROD));
    console.log('------------------------------------------------------------------------------------');

    let config = {

        metadata: {
            ENV: devModeEnabled ? ENV_DEVELOPMENT : ENV_PROD
        },
        devtool: 'source-map',
        debug: debugModeEnabled,

        entry: {},

        output: {
            filename: devModeEnabled ? '[name].bundle.js' : '[name].[chunkhash].bundle.js',
            sourceMapFilename: devModeEnabled ? '[name].bundle.map' : '[name].[chunkhash].bundle.map',
            chunkFilename: devModeEnabled ? '[id].chunk.js' : '[id].[chunkhash].chunk.js'
        },

        resolve: {
            cache: false,
            extensions: ['', '.ts', '.tsx', '.js', '.json', '.css', '.html']
        },

        module: {
            preLoaders: [],
            loaders: []
        },

        plugins: [],

        // we need this due to problems with es6-shim
        node: {
            global: 'window',
            progress: false,
            crypto: 'empty',
            module: false,
            clearImmediate: false,
            setImmediate: false
        }
    };

    if (debugModeEnabled) {
        console.log(merge(config, opts));
        console.log('------------------------------------------------------------------------------------');
    }

    return merge(config, opts);
}
881203
function concat(app) {
  var files = app.views.files;
  var css = '';

  for (var file in files) {
    if ('.css' != path.extname(file)) continue;
    css += files[file].contents.toString();
    delete files[file];
  }

  css = myth(css);
  app.files.addView('index.css', {
    contents: new Buffer(css)
  });
}
1251825
function CommonJsProject(opts) {
  this.roots = opts.roots;
  this.textPluginPattern = opts.textPluginPattern || /^text!/;

  opts.roots = this.roots.map(function(root) {
    if (!copy.isDirectory(root)) {
      throw new Error('Each commonjs root should be a directory: ' + root);
    }
    return ensureTrailingSlash(root);
  }, this);

  // A module is a Location that also has dep
  this.currentModules = {};
  this.ignoredModules = {};
}
595592
function onJSChanged() {
  if (typeof this.jsh === 'undefined') {
    var JSH = require('./helpers/JsHelper');
    this.jsh = new JSH(this.directory);
  }

  var that = this;
  // Cases to recompute:
  //    a root file changes: index.js could remove require of lib/index making index.js a root and lib/index a root
  //    a non-root file changes: b.js is the root and a.js changes to require b.js making it the new root
  return this.jsh.getRoots().then(function (roots) {
    return that.jsh.haveRootsChanged(roots);
  })
  .then(function (haveRootsChanged) {

    if (! haveRootsChanged) {
      console.log('roots haven\'t changed');
      return;
    }

    console.log('An app root has changed');

    // Need all of the targets to regenerate the gruntfile
    return that.getAllSettings().then(function (targets) {
      return that.engine.getConfig(targets, that.extensions);
    })
    .then(function (config) {
      // Grab the targets for the apps and merge with the existing targets
      return that.jsh.getSettings().then(function (settings) {
        utils.shallowExtend(config, settings.target);

        return config;
      });
    })
    .then(function (config) {
      // console.log('Config: ', config)
      return that.engine.flushConfig(config)
        .then(function () {
          return that.engine.compileTasks(config);
        });
    });
  });
}
665191
function (dirname, indexpath) {
    var extensions = {js: 1},
        modules = {};

    indexpath = indexpath || path.join(dirname, 'index.js');

    // Load all exported objects into a single module.
    fs.readdirSync(dirname).forEach(function (filename) {
      var fullpath = path.join(dirname, filename),
          parts    = filename.split('.'),
          module, name;

      if (fullpath !== indexpath && extensions[parts.pop()] && '.' !== filename[0]) {
        name = parts.join('.');
        module = require(fullpath);

        // Grab the function name or module name if possible.
        if (typeof module.name === 'string') {
          name = module.name;
        }

        modules[name] = module;
      }
    });

    return modules;
  }