/*
Grabs an app plugin, or returns false
969778
function(appName) {
    if (appName) {
      var options = _.sortBy(apps[appName].options, 'weight');
      apps[appName].options = options;
      return apps[appName];
    }
    return false;
  }
832390
function loadPlugin(book, plugin) {
    var logger = book.getLogger();

    var name = plugin.getName();
    var pkgPath = plugin.getPath();

    // Try loading plugins from different location
    var p = Promise()
    .then(function() {
        var packageContent;
        var packageMain;
        var content;

        // Locate plugin and load package.json
        try {
            var res = resolve.sync('./package.json', { basedir: pkgPath });

            pkgPath = path.dirname(res);
            packageContent = require(res);
        } catch (err) {
            if (!isModuleNotFound(err)) throw err;

            packageContent = undefined;
            content = undefined;

            return;
        }

        // Locate the main package
        try {
            var indexJs = path.normalize(packageContent.main || 'index.js');
            packageMain = resolve.sync('./' + indexJs, { basedir: pkgPath });
        } catch (err) {
            if (!isModuleNotFound(err)) throw err;
            packageMain = undefined;
        }

        // Load plugin JS content
        if (packageMain) {
            try {
                content = require(packageMain);
            } catch(err) {
                throw new error.PluginError(err, {
                    plugin: name
                });
            }
        }

        // Update plugin
        return plugin.merge({
            'package': Immutable.fromJS(packageContent),
            'content': Immutable.fromJS(content || {})
        });
    })

    .then(validatePlugin);

    p = timing.measure('plugin.load', p);

    logger.info('loading plugin "' + name + '"... ');
    return logger.info.promise(p);
}
1046888
function getAppContextFromArgv(apps) {
  return Promise.try(function() {
    return _.find(apps, function(app) {
      return app.name === argv.payload[0];
    });
  });
}
179316
function pushCouchapp(dbName, opts) {
  opts = opts || {}

  if (!dbName && typeof dbName !== 'string') {
    throw new PluginError(PLUGIN_NAME, 'Missing database name.');
  }

  return through.obj(function (file, enc, cb) {
    var ddocObj = require(file.path)
    var url = /^https?:\/\//.test(dbName) ? dbName : buildURL(dbName, opts);

    if (file.isNull()) {
      return cb(null, file)
    }

    if (file.isStream()) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported.'))
      return cb(null, file)
    }

    if (path.extname(file.path) !== '.js') {
      this.emit('error', new PluginError(PLUGIN_NAME, 'File extension not supported.'))
      return cb(null, file)
    }

    if (has(opts, 'attachments')) {
      var attachmentsPath = path.join(process.cwd(), path.normalize(opts.attachments))
      couchapp.loadAttachments(ddocObj, attachmentsPath)
    }

    couchapp.createApp(ddocObj, url, function (app) {
      app.push(function () {
        gutil.log(PLUGIN_NAME, 'Couchapp pushed!')
        return cb(null, file)
      })
    })
  })
}
929662
def get(self, name=None):
        
        return self.app.commands.get(name, self.plugin)
457908
function tryPlugin(mId, space) {
  const parsed = parse(mId);
  const pluginId = parsed.prefix.slice(0, -1);
  // text,json,raw plugins are built-in
  if (pluginId) {
    if (pluginId !== 'text' && pluginId !== 'raw') {
      return new Promise((resolve, reject) => {
        const req = (deps, callback, errback) => {
          const errback2 = e => {
            if (errback) {
              try {
                errback(e);
              } catch (err) {
                // ignore
              }
            }
            reject(e);
          };
          return requirejs(deps, callback, errback2);
        };
        try {
          const onload = loaded => {
            space.define(mId, [], () => loaded);
            resolve(space.req(mId));
          };
          onload.error = err => reject(err);

          requirejs([pluginId], plugin => {
            // Call requirejs plugin api load(name, require, load, options)
            // Options set to {} just to make existing requirejs plugins happy.
            plugin.load(parsed.bareId, req, onload, {});
          });
        } catch (err) {
          reject(err);
        }
      });
    }
  } else if (parsed.ext && parsed.ext !== '.js') {
    // Try extension plugin like "ext:css".
    const extPluginName = 'ext:' + parsed.ext.slice(1);
    if (userSpace.has(extPluginName) || packageSpace.has(extPluginName)) {
      return new Promise((resolve, reject) => {
        const req = (deps, callback, errback) => {
          const errback2 = e => {
            if (errback) {
              try {
                errback(e);
              } catch (err) {
                // ignore
              }
            }
            reject(e);
          };
          return requirejs(deps, callback, errback2);
        };
        try {
          const onload = loaded => {
            space.define(mId, [], () => loaded);
            resolve(space.req(mId));
          };
          onload.error = err => reject(err);

          requirejs([extPluginName], plugin => {
            // Call requirejs plugin api load(name, require, load, options)
            // Options set to {} just to make existing requirejs plugins happy.
            plugin.load(parsed.cleanId, req, onload, {});
          });
        } catch (err) {
          reject(err);
        }
      });
    }
    // else by default use text! for any unknown extname
    return new Promise(resolve => {
      space.define(parsed.cleanId,['text!' + parsed.cleanId], m => m);
      resolve(space.req(mId));
    });
  }
}
1259845
function webapp(id, plugin, striderjson, context, done) {
  if (plugin.appConfig) {
    defExtend(plugin.appConfig, context.config.plugins[id] || {});
  }
  // setup routes
  if (plugin.routes) {
    jobRoutes(id, plugin, context);
  }
  if (plugin.globalRoutes) {
    globalRoutes(id, plugin, context);
  }
  if (plugin.auth) {
    plugin.auth(context.passport, context);
  }
  // listen to global events; most job plugins shouldn't need this
  if (plugin.listen) {
    plugin.listen(context.emitter, context);
  }
  done(null, plugin.config);
}
640265
def get_plugin(self, name):
        
        for p in self._plugins:
            if p.name == name:
                return p
        return None
115705
async function getEnvConfig(asset, isSourceModule) {
  // Load the target engines for the app and generate a @babel/preset-env config
  let targetEngines = await getTargetEngines(asset, true);
  let targetEnv = await getEnvPlugins(targetEngines, true);
  if (!targetEnv) {
    return null;
  }

  // If this is the app module, the source and target will be the same, so just compile everything.
  // Otherwise, load the source engines and generate a babel-present-env config.
  if (!isSourceModule) {
    let sourceEngines = await getTargetEngines(asset, false);
    let sourceEnv = (await getEnvPlugins(sourceEngines, false)) || targetEnv;

    // Do a diff of the returned plugins. We only need to process the remaining plugins to get to the app target.
    let sourcePlugins = new Set(sourceEnv.map(p => p[0]));
    targetEnv = targetEnv.filter(plugin => {
      return !sourcePlugins.has(plugin[0]);
    });
  }

  return {
    internal: true,
    babelVersion: 7,
    config: {
      plugins: targetEnv
    }
  };
}
442814
function wrapper(app) {
    let httpMethods = getHttpMethod();
    httpMethods = httpMethods.concat(['use', 'all', 'param']);
    httpMethods.forEach(function (method) {
        app[method] = getWrappedAction(app[method]);
    });
    return app;
}
1217682
function createPlugin (appName, hotReloadService, rootURL) {

  function Plugin (window, host) {
    this.window = window;
    this.host = host;
  }
  Plugin.identifier = 'ember-hot-reload';
  Plugin.version = '1.0'; // Just following the example, this might not be even used
  Plugin.prototype.reload = function(path) {
    const cancelableEvent = { modulePath: path, cancel: false};
    hotReloadService.trigger('willLiveReload', cancelableEvent);
    if (cancelableEvent.cancel) {   // Only hotreload if someone canceled the regular reload
      // Reloading app.js will fire Application.create unless we set this.
      window.runningTests = true;
      var tags = document.getElementsByTagName('script');
      for (var i = tags.length; i >= 0; i--){
        if (tags[i] && tags[i].getAttribute('src') != null && tags[i].getAttribute('src').indexOf(appName) !== -1) {
          tags[i].parentNode.removeChild(tags[i]);
        }
      }
      var script = document.createElement('script');
      script.onload = function() {
        setTimeout(function() {
          window.runningTests = false;
          hotReloadService.trigger('willHotReload', path);
        }, 10);
      };
      script.type = 'text/javascript';
      script.src = `${rootURL}assets/${appName}.js`;
      document.body.appendChild(script);

      return true;
    }
    return false;
  };
  Plugin.prototype.analyze = function() {
    return {
      disable: false
    };
  };

  return Plugin;
}
1110111
function isServerApp (app) {
  return !!(app && (app.use || app.handle) && app.get && app.post);
}
678723
def get(self, name):
        """"""
        try:
            return self.plugins[name]
        except KeyError:
            raise RuntimeError("plugin {} does not exist".format(name))
998348
function(kbox, id, app, callback) {

  if (typeof callback === 'undefined' && typeof app === 'function') {
    callback = app;
    app = undefined;
  }

  // Get global config.
  var globalConfig = kbox.core.deps.lookup('globalConfig');

  // List of dirs that we care about.
  var dirs = [
    globalConfig.srcRoot,
    globalConfig.sysPluginRoot,
    globalConfig.userPluginRoot
  ];
  if (app) {
    dirs.push(app.config.appRoot);
  }

  // Each dir could have any of these sub dirs.
  var subDirs = [
    'node_modules',
    'plugins'
  ];

  // Helper function that lodash should be ashamed for not having. :P
  var flattenMap = function(elts, iterator) {
    return _(elts)
    .chain()
    .map(iterator)
    .flatten()
    .value();
  };

  // Map dirs to full list of paths.
  var paths = flattenMap(dirs, function(dir) {
    return _.map(subDirs, function(subDir) {
      return path.join(dir, subDir, id, 'index.js');
    });
  });

  // Filter paths by existance.
  return Promise.filter(paths, fs.existsSync)
  .all()
  // Grabs the last path so that we load things from SRC -> SYS -> USER
  .then(function(paths) {
    return _.last(paths);
  })
  // If a path exists try to require it.
  .then(function(path) {
    if (path) {
      return Promise.try(function() {
        return require(path);
      })
      .catch(function(err) {
        // Decorate the error.
        throw new KboxRequireError(path, err);
      });
    }
  })
  // Return.
  .nodeify(callback);

}
571629
function getAppContextFromCwd(apps) {
  return Promise.try(function() {
    var cwd = process.cwd();
    return _.find(apps, function(app) {
      var appRoot = app.config.appRoot;
      if (cwd.replace(appRoot, '') === cwd) {
        return false;
      }
      var diff = cwd.replace(appRoot, '').substring(0, 1);
      return (!diff || diff === path.sep) ? true : false;
    });
  });
}
1374808
function getHandler(app, schema, data) {
    function handleSave(err, results, next) {
        if (!err) {
            delete DependenciesMap[schema];
            SavedSchemas.push(schema);
            _l('schema saved: ' + schema);
        }
        next(err, results);
    }

    // Default handler function
    var ret = function (next) {
        data = _.isObject(data) ? _.values(data) : data;
        DBActions.getSimpleInstance(app, schema).multipleSave(data, function (err, results) {
            handleSave(err, results, next);
        });
    };

    // Data handler provided in plugin
    var ret1 = SchemaDataHandler[schema] && function (next) {
        SchemaDataHandler[schema](app, data)(function (err, results) {
            handleSave(err, results, next);
        });
    };
    return ret1 || ret;
}
513147
public static function dispatchPluggableApplication($plugin, $uri = null, $config = array())
    {
        $plugin = ucfirst($plugin);
        $config = array_merge(array(
            'rootDir'             => '', 
            'pluginDir'           => null,
            'resetConfig'         => true, 
            'overwriteDirs'       => true, 
            'overwriteFiles'      => true, 
            'checkPluginIsLoaded' => true,
            'bootstrapFile'       => 'Application.php'
        ), $config);
        
        if ($config['checkPluginIsLoaded'] && !self::isPluginLoaded($plugin)) {
            return false;
        }
        
        $uri = $uri ?: '';
        $rootDir = rtrim('/' . trim($config['rootDir'], '/'), '/');
        if ($config['pluginDir'] === null) {
            $pluginDir = self::$plugins[$plugin];
        } else {
            $pluginDir = rtrim($config['pluginDir'], '/');
        }
        
        $appDir = $pluginDir . $rootDir;
        if (!is_dir($appDir)) {
            throw new AtomikException("To be used as an application, the plugin '$plugin' must use a directory");
        }
        
        $overrideDir = self::findFile($plugin . $rootDir, self::path(self::get('atomik.dirs.overrides')));
        if ($overrideDir === false) {
            $overrideDir = 'overrides/' . $plugin . $rootDir;
        }
        
        if (!self::has('app.running_plugin')) {
            // saves user configuration
            self::set('userapp', self::get('app'));
        }
        self::set('app.running_plugin', $plugin); 
        self::set('request_uri', $uri);
        
        // resets the configuration but keep the layout
        if ($config['resetConfig']) {
            $layout = self::get('app.layout');
            self::reset();
            self::set('app.layout', $layout);
            self::set('app.routes', array());
        }
        
        // rewrite dirs
        $dirs = self::get('atomik.dirs');
        $dirs['actions'] = array($overrideDir . '/actions', $appDir . '/actions');
        $dirs['views'] = array($overrideDir . '/views', $appDir . '/views');
        
        $overwritableDirs = array(
            'layouts'   => array($overrideDir . '/layouts', $overrideDir . '/views', 
                                    $appDir . '/layouts', $appDir . '/views')
        );
        
        if ($config['overwriteDirs']) {
            $dirs = array_merge($dirs, $overwritableDirs);
        } else {
            $dirs = array_merge_recursive($overwritableDirs, $dirs);
        }
        
        // do not overwrite helpers
        $dirs['helpers'] = array_merge(
            array($overrideDir . '/helpers', $appDir . '/helpers'),
            (array) $dirs['helpers']
        );
        
        self::set('atomik.dirs', $dirs);
        
        // rewrite files
        if ($config['overwriteFiles']) {
            $files = self::get('atomik.files');
            $files['pre_dispatch'] = $appDir . '/pre_dispatch.php';
            $files['post_dispatch'] = $appDir . '/post_dispatch.php';
            self::set('atomik.files', $files);
        }
        
        $cancel = false;
        self::fireEvent('Atomik::Dispatchpluginapplication::Ready', array($plugin, &$uri, $config, &$cancel));
        if ($cancel) {
            return true;
        }
        
        $bootstrapFile = $appDir . '/' . $config['bootstrapFile'];
        if (file_exists($bootstrapFile)) {
            $continue = include $bootstrapFile;
            if ($continue === false) {
                return true;
            }
        }
        
        $cancel = false;
        self::fireEvent('Atomik::Dispatchpluginapplication::Start', array($plugin, &$uri, $config, &$cancel));
        if ($cancel) {
            return true;
        }
        
        return self::dispatch($uri, false);
    }