Create an express application.

@return {Function}
@api public
764298
function createApplication() {
  var app = connect();
  utils.merge(app, proto);
  app.request = { __proto__: req };
  app.response = { __proto__: res };
  app.init();
  return app;
}
1113013
function exportApplication(application) {
  checkForErrors(application);
  const formattedApplication = setUpApplicationStructure(application);
  writeConfigFile(formattedApplication);
  return formattedApplication;
}
1244867
function createHandler(options) {
  /**
   * Client request handler
   * Data from the incoming request (plus options) is forwarded to the AWS module
   */
  return async (ctx) => {
    const { credentials, endpoint, region } = options
    const { rawBody: body, header: headers, method, url: path } = ctx.request

    console.log(chalk.cyan(method, path))

    const params = { body, credentials, endpoint, headers, method, path, region }
    const req = createSignedAWSRequest(params)
    const res = await sendAWSRequest(req)

    ctx.status = 200
    ctx.type = 'application/json'
    ctx.response.header = stripProxyResHeaders(res)
    ctx.body = res.body
  }
}
304579
function createApp(root, options) {
  root = root || '';
  options = _.defaults(options || {}, {
    views: path.join(root, 'views', path.sep),
    public: path.join(root, 'public'),
    configdir: root,
    configOverrides: {},
    cacheviews: false,
  });
  var app = express();
  app.rootDir = root;
  if (!__theApp) {
    __theApp = app;
  }
  //options.appmethods overrides appmethods
  var methods = _.defaults(options.appmethods || {}, appmethods);
  //the express application object's prototype chain is funky so manually mix-in
  //our application methods
  Object.keys(methods).forEach( function(name) {
    app[name] = methods[name];
  });

  app.log = log; //use simple logger before log configuration

  app._beforeStart = app._setupBeforeStartListeners();
  app.addBeforeStartListener(app._connectToDb.bind(app));
  app._beforeStop = app._setupBeforeStopListeners();
  app.addBeforeStopListener(app._disconnectFromDb.bind(app));

  app.loadConfig = getConfigLoader(options);
  app.userModel = options.userModel;
  var config = app.loadConfig('app');
  app.config = config;
  if (config.settings) {
    Object.keys(config.settings).forEach( function(name) {
      app.set(name, config.settings[name]);
    });
  }
  app.initializeLogging();

  app.email = require('./email')(app);
  require('./passport')(passport, app); // pass passport for configuration
  app.passport = passport;

  app.setupViews(options);

  ///////////////install initial middleware///////////////
  app.useGracefulExiting();

  // adds req.id and req.log
  app.use(log.useReqLog(config.requests && config.requests.hideInternals));

  // configure request logging
  app.configRequestLogging();

  app.use(bodyParser.urlencoded());
  app.use(bodyParser.json());

  app._configureSession();

  app.use(passport.initialize());
  app.use(passport.session()); // persistent login sessions

  app.use(flash()); // use connect-flash for flash messages stored in session

  //now that passport is initialized expose the user to views
  app.use(function(req, res, next) {
    if (req.isAuthenticated && req.isAuthenticated())
      res.locals.user = req.user;
    if (req.session.impersonated)
      res.locals.impersonated = true;
    res.locals.query = req.query;
    //automatically expose flash messages to views, do with
    //a function instead of variable because we only want to consume the
    //flash message if the view requests it.
    res.locals.popAlertMessages = _.partial(utils.popAlertMessages, req.flash.bind(req));
    return next();
  });

  // development only
  if ('development' == app.get('env')) {
    // add development vars to res.locals (enables debug_footer)
    app.use(function debugFooterHandler(req, res, next) {
      res.locals.debug = {
        req: req
      };
      next();
    });
  }
  ////////end initial middleware (see start() for more) //////////

  app.setupPrivateMode();
  app.saveCurrentNamedRoute();
  app.setupAccessControlPolicy();
  app.createDefaultAdmin();

  app.set('dburl', config.dburl);
  if (options.public)
    app.set('publicpath', options.public);

  if (process.env.PORT || config.port)
    app.set('port', process.env.PORT || config.port);

  //set up the base app's named routes
  app.updateNamedRoutes(routes(app, passport));
  if (options.routes)
    app.updateNamedRoutes(options.routes);

  return app;
}
489051
async function setupServer() {
  return new Promise(async (resolve, reject) => {
    config = config || (await getConfig());
    config.components.individual = [];
    config.prod = true;
    config.enableCache = true;
    config.mode = 'server';
    config.env = 'pwa';
    config.sourceMaps = false;
    config.copy = [];
    config.webpackDevServer = false;
    config.buildDir = path.join(config.wwwDir, 'build-ssr');
    config.dataDir = path.join(config.wwwDir, 'build-ssr', 'data');

    app.use(express.static(path.relative(process.cwd(), config.wwwDir)));

    // generate a fresh webpack build + pass along asset data to dynamic HTML template rendered
    server = await app.listen(port);

    app.get('/ssr', function(req, res) {
      res.send(template(html || '', port, webpackStatsGenerated || []));
    });

    // handle cleaning up + shutting down the server instance
    process.on('SIGTERM', shutDownSSRServer);
    process.on('SIGINT', shutDownSSRServer);

    server.on('connection', connection => {
      connections.push(connection);
      connection.on(
        'close',
        // eslint-disable-next-line no-return-assign
        () => (connections = connections.filter(curr => curr !== connection)),
      );
    });

    resolve();
  });
}
1038707
def create_app():
    
    
    # Setup Flask and load app.config
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Setup Flask-MongoEngine
    db = MongoEngine(app)

    # Define the User document.
    # NB: Make sure to add flask_user UserMixin !!!
    class User(db.Document, UserMixin):
        active = db.BooleanField(default=True)

        # User authentication information
        username = db.StringField(default='')
        password = db.StringField()

        # User information
        first_name = db.StringField(default='')
        last_name = db.StringField(default='')

        # Relationships
        roles = db.ListField(db.StringField(), default=[])

    # Setup Flask-User and specify the User data-model
    user_manager = UserManager(app, db, User)

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users via the @login_required decorator
    @app.route('/members')
    @login_required    # User must be authenticated
    def member_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    return app
412078
function createServer (options, callback) {
  typeforce({
    keeper: 'Object',
    port: 'Number',
    readonly: '?Boolean'
  }, options)

  var keeper = options.keeper
  var port = options.port
  var app = express()
  if (options.readonly) {
    app.set('readonly', true)
  }

  // var mapping

  app.set('keeper', keeper)
  app.use(function (req, res, next) {
    var requestDomain = domain.create()
    requestDomain.add(req)
    requestDomain.add(res)
    requestDomain.on('error', function (err) {
      debug('Uncaught error, processing in domain error handler: ' + err.message)
      errorHandler(err, req, res)
    })

    res.on('close', requestDomain.dispose.bind(requestDomain))
    requestDomain.run(next)
  })

  app.use(function (req, res, next) {
    if (req.hostname !== 'localhost' && req.hostname !== '127.0.0.1') {
      throw utils.httpError(400, 'Only local requests permitted')
    }

    next()
  })

  /**
   * Routes
   */
  router(app)

  /**
   * Error Handling
   */
  app.use(errorHandler)

  // client.externalIp(function(err, ip) {
  //   console.log('External ip', ip)
  //   keeper.externalIp(ip)
  // })

  // var ttl = 144000

  process.on('exit', cleanup)
  process.on('SIGINT', cleanup)
  process.on('SIGTERM', cleanup)
  process.on('uncaughtException', function (err) {
    console.log('Uncaught exception, caught in process catch-all: ' + err.message)
    console.log(err.stack)
  })

  // if (require.main === global.module) {
  // run directly, not as sub-app

  // var mappingIntervalId = setInterval(createPortMapping, ttl)
  // var pubPort = port
  var privPort = port
  var serverIsUp
  // var portPromise = createPortMapping()
  // portPromise.done(checkReady)

  var server = app.listen(privPort, function () {
    serverIsUp = true
    checkReady()
  })

  function checkReady () {
    if (serverIsUp
      // && portPromise.inspect().state === 'fulfilled'
      && callback) {
      callback(null, server)
    }
  }

  function errorHandler (err, req, res, next) {
    if (res.finished) return

    var code = err.code || 500
    var msg = 'code' in err ? err.message : 'There was an error with your request. Please contact support@tradle.io'

    // log('Error:' + err.message)
    res.status(code).json({
      code: code,
      message: msg
    }, null, 2)
  }

  // function createPortMapping () {
  //   return ports.mapPort({
  //       public: pubPort,
  //       private: privPort,
  //       hijack: true
  //     })
  //     .then(function () {
  //       mapping = {
  //         public: pubPort,
  //         private: privPort
  //       }
  //     })
  //     .catch(function (err) {
  //       console.error('Failed to create port mapping, but continuing', err)
  //       clearInterval(mappingIntervalId)
  //     // process.exit()
  //     })
  // }

  function cleanup () {
    if (!server) return

    debug('CLEANUP')
    if (server) {
      try {
        server.close()
      } catch (err) {}
      server = null
    }

    // if (mapping) {
    //   clearInterval(mappingIntervalId)
    //   ports.unmapPort(mapping['public'])
    //   mapping = null
    // }

    setTimeout(process.exit.bind(process), 1000)
  }

  return server
}
1293084
function create(requestObj, callback) {
           
            var storage = this;

            callback = callback || function defaultPostCallback() {
                //setup Error Notification here
            };
            
            if ((typeof requestObj) === 'undefined' || requestObj === null) {
               callback();
               return this;
            }
            
            requestObj.data.id = this._generateUid();

			for (i = 0; i < storage.preprocessors.length; i++) {
                requestObj.data = storage.preprocessors[i](requestObj.data, requestObj);
            }
            this.storage[requestObj.data.id] = requestObj.data;
            
            var data = this.storage[requestObj.data.id];            

            for (i = 0; i < storage.processors.length; i++) {
                data = storage.processors[i](data);
            }
            callback(data);
            
            return this;
        }
417583
function initExpress (config) {
    // disable x-powered-by header
    config.express.disable('x-powered-by')
    // enable strict (trailing-slashes) and case-sensitive routing
    config.express.enable('strict routing')
    config.express.enable('case sensitive routing')
    // add each assets dir in reverse order which allows assets from modules
    // to be overridden by app
    _.each(_.reverse(config.dir.assets), dir => {
        config.express.use('/assets', express.static(dir))
    })
    // add requestId and requestCreateTime to req object
    config.express.use(requestIdMiddleware)
    // parse json
    config.express.use(bodyParser.json())
    // parse application/x-www-form-urlencoded
    config.express.use(bodyParser.urlencoded({
        extended: true,
    }))
    // parse cookies
    config.express.use(cookieParser())
    // add logger
    if (config.log) {
        config.express.use(morgan(isProd ? 'combined' : 'dev'))
    }
    // use any additional middleware set in config
    _.each(config.use, use => {
        // if use value is array then use array as args
        if (_.isArray(use)) {
            config.express.use.apply(config.express, use)
        }
        // otherwise value should be function
        else {
            config.express.use(use)
        }
    })
}
612721
function create(requestObj, callback) {

            var i, requestConfig, storage;

            storage = this;

            callback = callback || function(){};

            if ((typeof requestObj) === 'undefined' || requestObj === null) {
                callback(null);
                return this;
            }
            
            requestObj.config = {};
            requestObj.config.url = requestObj.config.url || this.url.post;
            requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_POST;

			for (i = 0; i < storage.preprocessors.length; i++) {
                requestObj.data = storage.preprocessors[i](requestObj.data, requestObj);
            }

            this.constructor._sendRequest(requestObj, function(data){
                for (i = 0; i < storage.processors.length; i++) {
                    data = storage.processors[i](data, requestObj);
                }
                callback(data);
            });

            return this;
        }
1111885
function create(req, res, next) {
  var body = req.body;
  body.user_id = req.session.user.id;

  db.posts.create(req.body, function(err, post) {
    if(err) { return next(err); }

    res.json(201, post);
    signals.emit('post:create', post);
  });
}
1370706
function Application(options) {
  var self = this;

  if (!(self instanceof Application)) {
    return new Application(options);
  }

  stream.Duplex.call(self, { objectMode: true });

  self.id = hat();
  self.server = net.createServer(self._handleInbound.bind(self));
  self.options = merge(Object.create(Application.DEFAULTS), options);
  self.connections = { inbound: [], outbound: [] };

  // setup middlware stack with initial entry a simple passthrough
  self.stack = [function(socket) {
    return through(function(data) {
      this.queue(data);
    });
  }];

  Object.defineProperty(self, 'log', {
    value: this.options.logger || {
      info: NOOP, warn: NOOP, error: NOOP
    }
  });

  // connect to seeds
  self._enterNetwork();
  setInterval(self._enterNetwork.bind(self), self.options.retryInterval);
}
1288192
function createMiddleware(options, archiveFormat) {
  /**
   * Express middleware handling GitHub API archive link requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/contents/#get-archive-link
   */
  return (req, res) => {
    // GET /repos/:owner/:repo/:archive_format/:ref
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refName = req.params.ref || 'master';

    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
    const location = `${req.protocol}://${host}/codeload/${owner}/${repoName}/${archiveFormat}/${refName}`;

    res.writeHead(302, {
      Location: location,
    });
    res.end();
  };
}
801716
function create(req, res, next) {
  var body = req.body;

  db.users.create(body, function(err, user) {
    if(err) { return next(err); }
    res.json(201, user);
  });
}
106739
function create(options) {
  console.log('Creating app: ', options.name);

  if (!options.status)
    options.status = (code, msg) => {
      console.log(msg);
    };
  if (!options.type) options.type = 'rekit-react';

  const prjDir = path.join(options.location || process.cwd(), options.name);
  return new Promise(async (resolve, reject) => {
    try {
      if (fs.existsSync(prjDir)) {
        reject('FOLDER_EXISTS');
        return;
      }
      fs.mkdirSync(prjDir);
      let gitRepo;
      if (options.source) {
        if (/^https?:/.test(options.source)) {
          // It's a git repo
          gitRepo = options.source;
        } else {
          // It's a local folder
          const srcDir = path.isAbsolute(options.source)
            ? options.source
            : path.join(process.cwd(), options.source);
          options.status('CREATE_APP_COPY_FILES', `Copy files from ${srcDir}...`);
          await fs.copy(srcDir, prjDir, {
            filter: src => !/\/(\.git|node_modules\/|node_modules$)/.test(src) || path.basename(src) === '.gitignore',
          });
        }
      } else if (options.type) {
        // Get gitRepo
        options.status(
          'QUERY_APP_TYPES_GIT_REPO',
          `Looking for the git repo for app type ${options.type}...`,
        );
        const appTypes = await getAppTypes();
        const appType = _.find(appTypes, { id: options.type });
        if (!appType) reject('APP_TYPE_NOT_SUPPORTED');
        gitRepo = appType.repo;
      } else {
        await fs.remove(prjDir);
        reject('NO_SOURCE_OR_APP_TYPE');
      }

      if (gitRepo) {
        options.status('CLONE_PROJECT', `Downloading project from ${gitRepo}...`);
        await cloneRepo(gitRepo, prjDir);
      }

      postCreate(prjDir, options);
      options.status('CREATION_SUCCESS', '😃App creation success.');
      resolve();
    } catch (err) {
      console.log('Failed to create project.');
      fs.removeSync(prjDir);
      reject(err);
    }
  });
}
1210574
async function start() {
  if (server) return server;
  server = express();
  server.use(errorOverlayMiddleware());
  server.use(express.static(path.resolve(__dirname, '../public')));

  // Configure client-side hot module replacement
  const clientConfig = webpackConfig.find(config => config.name === 'client');
  clientConfig.entry.client = ['./tools/lib/webpackHotDevClient']
    .concat(clientConfig.entry.client)
    .sort((a, b) => b.includes('polyfill') - a.includes('polyfill'));
  clientConfig.output.filename = clientConfig.output.filename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.output.chunkFilename = clientConfig.output.chunkFilename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.module.rules = clientConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure server-side hot module replacement
  const serverConfig = webpackConfig.find(config => config.name === 'server');
  serverConfig.output.hotUpdateMainFilename = 'updates/[hash].hot-update.json';
  serverConfig.output.hotUpdateChunkFilename =
    'updates/[id].[hash].hot-update.js';
  serverConfig.module.rules = serverConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure compilation
  await run(clean);
  const multiCompiler = webpack(webpackConfig);
  const clientCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'client',
  );
  const serverCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'server',
  );
  const clientPromise = createCompilationPromise(
    'client',
    clientCompiler,
    clientConfig,
  );
  const serverPromise = createCompilationPromise(
    'server',
    serverCompiler,
    serverConfig,
  );

  // https://github.com/webpack/webpack-dev-middleware
  server.use(
    webpackDevMiddleware(clientCompiler, {
      publicPath: clientConfig.output.publicPath,
      logLevel: 'silent',
      watchOptions,
    }),
  );

  // https://github.com/glenjamin/webpack-hot-middleware
  server.use(webpackHotMiddleware(clientCompiler, { log: false }));

  let appPromise;
  let appPromiseResolve;
  let appPromiseIsResolved = true;
  serverCompiler.hooks.compile.tap('server', () => {
    if (!appPromiseIsResolved) return;
    appPromiseIsResolved = false;
    // eslint-disable-next-line no-return-assign
    appPromise = new Promise(resolve => (appPromiseResolve = resolve));
  });

  let app;
  server.use((req, res) => {
    appPromise
      .then(() => app.handle(req, res))
      .catch(error => console.error(error));
  });

  function checkForUpdate(fromUpdate) {
    const hmrPrefix = '[\x1b[35mHMR\x1b[0m] ';
    if (!app.hot) {
      throw new Error(`${hmrPrefix}Hot Module Replacement is disabled.`);
    }
    if (app.hot.status() !== 'idle') {
      return Promise.resolve();
    }
    return app.hot
      .check(true)
      .then(updatedModules => {
        if (!updatedModules) {
          if (fromUpdate) {
            console.info(`${hmrPrefix}Update applied.`);
          }
          return;
        }
        if (updatedModules.length === 0) {
          console.info(`${hmrPrefix}Nothing hot updated.`);
        } else {
          console.info(`${hmrPrefix}Updated modules:`);
          updatedModules.forEach(moduleId =>
            console.info(`${hmrPrefix} - ${moduleId}`),
          );
          checkForUpdate(true);
        }
      })
      .catch(error => {
        if (['abort', 'fail'].includes(app.hot.status())) {
          console.warn(`${hmrPrefix}Cannot apply update.`);
          delete require.cache[require.resolve('../build/server')];
          // eslint-disable-next-line global-require, import/no-unresolved
          app = require('../build/server').default;
          console.warn(`${hmrPrefix}App has been reloaded.`);
        } else {
          console.warn(
            `${hmrPrefix}Update failed: ${error.stack || error.message}`,
          );
        }
      });
  }

  serverCompiler.watch(watchOptions, (error, stats) => {
    if (app && !error && !stats.hasErrors()) {
      checkForUpdate().then(() => {
        appPromiseIsResolved = true;
        appPromiseResolve();
      });
    }
  });

  // Wait until both client-side and server-side bundles are ready
  await clientPromise;
  await serverPromise;

  const timeStart = new Date();
  console.info(`[${format(timeStart)}] Launching server...`);

  // Load compiled src/server.js as a middleware
  // eslint-disable-next-line global-require, import/no-unresolved
  app = require('../build/server').default;
  appPromiseIsResolved = true;
  appPromiseResolve();

  // Launch the development server with Browsersync and HMR
  await new Promise((resolve, reject) =>
    browserSync.create().init(
      {
        // https://www.browsersync.io/docs/options
        server: 'src/server.js',
        middleware: [server],
        open: !process.argv.includes('--silent'),
        ...(isDebug ? {} : { notify: false, ui: false }),
      },
      (error, bs) => (error ? reject(error) : resolve(bs)),
    ),
  );

  const timeEnd = new Date();
  const time = timeEnd.getTime() - timeStart.getTime();
  console.info(`[${format(timeEnd)}] Server launched after ${time} ms`);
  return server;
}
1334892
function create(hbs, env) {
  if (env) process.env.NODE_ENV = env;

  var express = require('express');
  var app = express();
  var fs = require('fs');
  var fp = require('path');

  function relative(path) {
    return fp.join(__dirname, path);
  }

  var viewsDir = relative('views');

  app.use(express.static(relative('public')));

  // Hook in express-hbs and tell it where known directories reside
  app.engine('hbs', hbs.express4({
    partialsDir: [relative('views/partials'), relative('views/partials-other')],
    defaultLayout: relative('views/layout/default.hbs')
  }));
  app.set('view engine', 'hbs');
  app.set('views', viewsDir);

  // Register sync helper
  hbs.registerHelper('link', function(text, options) {
    var attrs = [];
    for (var prop in options.hash) {
      attrs.push(prop + '="' + options.hash[prop] + '"');
    }
    return new hbs.SafeString(
      '<a ' + attrs.join(' ') + '>' + text + '</a>'
    );
  });

  // Register Async helpers
  hbs.registerAsyncHelper('readFile', function(filename, cb) {
    fs.readFile(fp.join(viewsDir, filename), 'utf8', function(err, content) {
      if (err) console.error(err);
      cb(new hbs.SafeString(content));
    });
  });

  var fruits = [
    {name: 'apple'},
    {name: 'orange'},
    {name: 'pear'}
  ];

  var veggies = [
    {name: 'asparagus'},
    {name: 'carrot'},
    {name: 'spinach'}
  ];

  app.get('/', function(req, res) {
    res.render('index', {
      title: 'express-hbs example'
    });
  });

  app.get('/replace', function(req, res) {
    res.render('replace', {
      title: 'express-hbs example'
    });
  });

  app.get('/fruits', function(req, res) {
    res.render('fruits/index', {
      title: 'My favorite fruits',
      fruits: fruits
    });
  });

  app.get('/fruits/:name', function(req, res) {
    res.render('fruits/details', {
      fruit: req.params.name
    });
  });

  app.get('/veggies', function(req, res) {
    res.render('veggies', {
      title: 'My favorite veggies',
      veggies: veggies,
      layout: 'layout/veggie'
    });
  });

  app.get('/veggies/:name', function(req, res) {
    res.render('veggies/details', {
      veggie: req.params.name,
      layout: 'layout/veggie-details'
    });
  });

  return app;
}