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,MAAM,WACtB,OAAO,eAAe,MAAM,UAAW,SAAU,CAC/C,MAAO,WACL,MAAM,EAAM,CAAC,EAMb,OAJA,OAAO,oBAAoB,MAAM,SAAQ,SAAU,GAC/C,EAAI,GAAO,KAAK,EACpB,GAAG,MAEI,CACT,EACA,cAAc,EACd,UAAU,IAId,OAAO,QAAU","file":"/npm/we-core@3.1.18/src/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.37.0.\n * Original file: /npm/we-core@3.1.18/src/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/**\n * We.js main file, load we.js core and features\n */\n\n// Module dependencies.\n\n// Disable uneed bluebird warnings:\nprocess.env.BLUEBIRD_W_FORGOTTEN_RETURN = '0';\n\nconst http = require('http'),\n      _ = require('lodash'),\n      path = require('path'),\n      staticConfig = require('./staticConfig'),\n      Database = require('./Database'),\n      Hooks = require('./Hooks'),\n      PluginManager = require('./PluginManager'),\n      Router = require('./Router'),\n      Sanitizer = require('./Sanitizer'),\n      EventEmiter = require('events'),\n      unhandledErrorCatcher = require('./unhandledErrorCatcher'),\n      { readFileSync, writeFileSync, writeFile } = require('fs');\n\n/**\n * We.js object\n *\n * @type {Object}\n */\nfunction We (options) {\n  if (!options) options = {};\n\n  const we = this;\n\n  this.packageJSON = require('../package.json');\n\n  this.config = options;\n\n  this.childProcesses = [];\n\n  this.plugins = {};\n  this.pluginPaths = [];\n  this.pluginNames = [];\n  // controllers\n  this.controllers = {};\n\n  this.projectPath = options.projectPath || process.cwd();\n\n  this.projectPackageJSON = require(path.resolve(this.projectPath, 'package.json'));\n\n  this.projectConfigFolder = options.projectConfigFolder || path.join(this.projectPath, 'config');\n\n  // start configs with static configs\n  this.config = staticConfig(this.projectPath, this);\n  // enviroment config prod | dev | test\n  we.env = options.env || require('./getEnv.js')();\n  // winston logger\n  we.log = require('./log')(we);\n  // hooks and events\n  we.hooks = new Hooks();\n\n  we.events = new EventEmiter();\n  // we.js events is controlled then we will use an max of 70 listenners in every event:\n  we.events.setMaxListeners(70);\n  // we.js sanitizer\n  we.sanitizer = new Sanitizer(this);\n  // The we.js router\n  we.router = new Router(this);\n  // we.js prototypes\n  we.class = {\n    Controller: require('./class/Controller.js'),\n    Theme: require('./class/Theme.js')(we),\n    Plugin: require('./class/Plugin.js')(we)\n  };\n  // database logic and models is avaible in we.db.models\n  we.db = new Database(this);\n  // - init database\n  we.db.defaultConnection = we.db.connect(we.env);\n  //set for more compatbility with sequelize docs\n  we.db.sequelize = we.db.defaultConnection;\n  // plugin manager and plugins vars\n  we.pluginManager = new PluginManager(this);\n  // Error catcher to get unhandled erros, use this options to disable on multiple we.js instances\n  if (!we.config.disableGlobalErrorCatcher) {\n    unhandledErrorCatcher(we);\n  }\n\n  switch (we.config.bootstrapMode) {\n    case 'install':\n    case 'installation':\n    case 'update':\n      we.hooks.on('bootstrap', [\n        we.bootstrapFunctions.checkDBConnection,\n        we.bootstrapFunctions.loadCoreFeatures,\n        we.bootstrapFunctions.loadPluginFeatures,\n        we.bootstrapFunctions.initI18n,\n        we.bootstrapFunctions.loadTemplateCache,\n        we.bootstrapFunctions.instantiateModels,\n        we.bootstrapFunctions.syncModels,\n        we.bootstrapFunctions.loadControllers,\n        we.bootstrapFunctions.installAndRegisterPlugins\n      ]);\n      break;\n    case 'complete':\n    case 'full':\n    case 'test':\n      // full load, usefull for tests\n      we.hooks.on('bootstrap', [\n        we.bootstrapFunctions.checkDBConnection,\n        we.bootstrapFunctions.loadCoreFeatures,\n        we.bootstrapFunctions.loadPluginFeatures,\n        we.bootstrapFunctions.initI18n,\n        we.bootstrapFunctions.loadTemplateCache,\n        we.bootstrapFunctions.instantiateModels,\n        we.bootstrapFunctions.syncModels,\n        we.bootstrapFunctions.loadControllers,\n        we.bootstrapFunctions.installAndRegisterPlugins,\n        we.bootstrapFunctions.setExpressApp,\n        we.bootstrapFunctions.passport,\n        we.bootstrapFunctions.createDefaultFolders,\n        we.bootstrapFunctions.registerAllViewTemplates,\n        we.bootstrapFunctions.mergeRoutes,\n        we.bootstrapFunctions.bindResources,\n        we.bootstrapFunctions.bindRoutes\n      ]);\n      break;\n    default:\n      // defaults to load for run\n      we.hooks.on('bootstrap', [\n        we.bootstrapFunctions.checkDBConnection,\n        we.bootstrapFunctions.loadCoreFeatures,\n        we.bootstrapFunctions.loadPluginFeatures,\n        we.bootstrapFunctions.initI18n,\n        we.bootstrapFunctions.loadTemplateCache,\n        we.bootstrapFunctions.instantiateModels,\n        we.bootstrapFunctions.syncModels,\n        we.bootstrapFunctions.loadControllers,\n        we.bootstrapFunctions.installAndRegisterPlugins,\n        we.bootstrapFunctions.setExpressApp,\n        we.bootstrapFunctions.passport,\n        we.bootstrapFunctions.createDefaultFolders,\n        we.bootstrapFunctions.registerAllViewTemplates,\n        we.bootstrapFunctions.mergeRoutes,\n        we.bootstrapFunctions.bindResources,\n        we.bootstrapFunctions.bindRoutes\n      ]);\n  }\n}\n\nWe.prototype = {\n  /**\n   * Set config in config/configuration.json file\n   *\n   * @param {String}   variable path to the variable\n   * @param {String}   value\n   * @param {Function} cb       callback\n   */\n  setConfig(variable, value, cb) {\n    if (!cb) cb = function(){};\n\n    let cJSON,\n        cFGpath = path.join(this.projectPath, '/config/configuration.json');\n\n    try {\n      cJSON = JSON.parse(readFileSync(cFGpath));\n    } catch(e) {\n      if (e.code == 'ENOENT') {\n        writeFileSync(cFGpath, '{}');\n        cJSON = {};\n      } else {\n        return cb(e);\n      }\n    }\n\n    if (value == 'true') value = true;\n    if (value == 'false') value = false;\n\n    _.set(cJSON, variable, value);\n\n    writeFile(cFGpath, JSON.stringify(cJSON, null, 2), cb);\n  },\n\n  /**\n   * Unset config in config/configuration.json file\n   *\n   * @param {String}   variable path to the variable\n   * @param {String}   value\n   * @param {Function} cb       callback\n   */\n  unSetConfig(variable, cb) {\n    let cJSON,\n        cFGpath = path.join(this.projectPath, '/config/configuration.json');\n\n    try {\n      cJSON = JSON.parse(readFileSync(cFGpath));\n    } catch(e) {\n      if (e.code == 'ENOENT') {\n        writeFileSync(cFGpath, '{}');\n        cJSON = {};\n      } else {\n        return cb(e);\n      }\n    }\n\n    _.unset(cJSON, variable);\n\n    writeFile(cFGpath, JSON.stringify(cJSON, null, 2), cb);\n  },\n  // set bootstrap functions\n  bootstrapFunctions: require('./bootstrapFunctions'),\n  // flag to check if this we.js instance did the bootstrap\n  bootstrapStarted: false,\n  // flag to check if needs restart\n  needsRestart: false,\n  // we.utils.async, we.utils._ ... see the ./utils file\n  utils: require('./utils'),\n  // load we.js responses\n  responses: require('./responses'),\n  // save we-core path to plugin.js for update e install process\n  weCorePluginfile: path.resolve(__dirname, '../') + '/plugin.js',\n  //Overide default toString and inspect to custom infos in we.js object\n  inspect() {\n    return '\\nWe.js ;)\\n';\n  },\n  toString() {\n    return this.inspect();\n  },\n  // client side config generator\n  getAppBootstrapConfig: require('./staticConfig/getAppBootstrapConfig.js'),\n\n  /**\n   * Bootstrap and initialize the app\n   *\n   * @param  {Object}   configOnRun optional\n   * @param  {Function} cb          callback to run after load we.js\n   */\n  bootstrap(configOnRun, cb) {\n    const we = this;\n    // only bootstrap we.js one time\n    if (we.bootstrapStarted) throw new Error('We.js already did bootstrap');\n\n    we.bootstrapStarted = true;\n    // configsOnRun object is optional\n    if (!cb) {\n      cb = configOnRun;\n      configOnRun = null;\n    }\n    // configs on run extends default and file configs\n    if (configOnRun) _.merge(we.config, configOnRun);\n\n    // run the bootstrap hook\n    we.hooks.trigger('bootstrap', we, function bootstrapDone (err) {\n      if (err) {\n        console.log('Error on bootstrap: ');\n        throw err;\n      }\n\n      we.events.emit('we:bootstrap:done', we);\n\n      we.log.debug('We.js bootstrap done');\n      // set pm2 gracefullReload:\n      we.setPM2grShutdownFN(we);\n\n      return cb(null, we);\n    });\n  },\n\n  /**\n   * Start we.js server (express)\n   * use after we.bootstrap\n   *\n   * @param  {Function} cb    callback how returns with cb(err);\n   */\n  startServer(cb) {\n    if (!cb) cb = function(){}; // cb is optional\n\n    let we = this;\n\n    we.hooks.trigger('we:server:before:start', we, function afterRunBeforeServerStart (err) {\n      if (err) return cb(err);\n      /**\n       * Get port from environment and store in Express.\n       */\n      let port = normalizePort(we.config.port);\n      we.express.set('port', port);\n\n      /**\n       * Create HTTP server with suport to url alias rewrite\n       */\n      const server = http.createServer(function onCreateServer (req, res){\n        Object.defineProperty(req, 'we', {\n          get: function getWe() { return we; }\n        });\n\n        // Clean memory on end events:\n        res.on('finish', function() {\n          we.freeResponseMemory(req, res);\n        });\n        res.on('close', function() {\n          we.freeResponseMemory(req, res);\n        });\n        res.on('end', function() {\n          we.freeResponseMemory(req, res);\n        });\n\n        // suport for we.js widget API\n        // install we-plugin-widget to enable this feature\n        if (req.headers && req.headers['we-widget-action'] && req.method == 'POST') {\n          req.isWidgetAction = true;\n          req.originalMethod = req.method;\n          req.method = 'GET'; // widgets only are associated to get routes\n        }\n\n        // parse extension if not is public folder\n        if (!we.router.isPublicFolder(req.url)) {\n          req.extension = we.router.splitExtensionFromURL(req.url);\n\n          if (req.extension) {\n            let format = we.utils.mime.getType(req.extension);\n\n            if (req.we.config.responseTypes.includes(format)) {\n              // update the header response format with extension format\n              req.headers.accept = format;\n              // update the old url\n              req.url = req.url.replace('.'+req.extension, '');\n            }\n          }\n        }\n        // install we-plugin-url-alias to enable alias feature\n        if (we.plugins['we-plugin-url-alias'] && we.config.enableUrlAlias) {\n          we.router.alias.httpHandler.bind(this)(req, res);\n        } else {\n          we.express.bind(this)(req, res);\n        }\n      });\n\n      we.events.emit('we:server:after:create', { we: we, server: server });\n\n      /**\n       * Listen on provided port, on all network interfaces.\n       */\n\n      // catch 404 and forward to error handler\n      we.express.use(function routeNotFound (req, res) {\n        we.log.debug('Route not found:', {\n          method: req.method,\n          path: req.path\n        });\n        // var err = new Error('Not Found');\n        // err.status = 404;\n        return res.notFound();\n      });\n\n      server.listen(port);\n      server.on('error', onError);\n      server.on('listening', onListening);\n      /**\n       * Normalize a port into a number, string, or false.\n       */\n      function normalizePort (val) {\n        let port = parseInt(val, 10);\n\n        if (isNaN(port)) {\n          // named pipe\n          return val;\n        }\n\n        if (port >= 0) {\n          // port number\n          return port;\n        }\n\n        return false;\n      }\n\n      /**\n       * Event listener for HTTP server \"error\" event.\n       */\n      function onError (error) {\n        if (error.syscall !== 'listen') {\n          throw error;\n        }\n\n        let bind = typeof port === 'string'\n          ? 'Pipe ' + port\n          : 'Port ' + port;\n\n        // handle specific listen errors with friendly messages\n        switch (error.code) {\n          case 'EACCES':\n            console.error(bind + ' requires elevated privileges');\n            process.exit(1);\n            break;\n          case 'EADDRINUSE':\n            console.error(bind + ' is already in use');\n            process.exit(1);\n            break;\n          default:\n            throw error;\n        }\n      }\n      /**\n       * Event listener for HTTP server \"listening\" event.\n       */\n      function onListening () {\n        let addr = server.address(),\n            bind = typeof addr === 'string'\n          ? 'pipe ' + addr\n          : 'port ' + addr.port;\n        we.log.info('Run in '+we.env+' enviroment and listening on ' + bind);\n\n        if (process.send) {\n          process.send('ready');\n        }\n      }\n      // save the current http server\n      we.http = server;\n\n      // express error handlers\n      // will print stacktrace\n      we.express.use(function onExpressError (err, req, res, next) {\n        // invalid url error handling\n        if (err instanceof URIError) {\n          we.log.warn('onExpressError:URIError on:', {\n            path: req.path,\n            error: err\n          });\n\n          res.addMessage('warning', {\n            text: 'router.invalid.url'\n          });\n\n          // go to home page on invalid url request\n          return res.goTo('/');\n        }\n\n        we.log.error('onExpressError:Error on:', {\n          path: req.path,\n          error: err\n        });\n\n        res.serverError(err);\n      });\n\n      we.hooks.trigger('we:server:after:start',we, function afterHookAfterStart (err) {\n        cb(err, we);\n      });\n    });\n  },\n\n  /**\n   * Bootstrap and Start we.js server\n   *\n   * @param  {Object}   cfgs configs (optional)\n   * @param  {Function} cb   callback\n   */\n  go(cfgs, cb) {\n    if (!cb) {\n      cb = cfgs;\n      cfgs = {};\n    }\n\n    this.bootstrap(cfgs, function afterBootstrapOnWeGo (err, we) {\n      if (err) throw err;\n      we.startServer(cb);\n    });\n  },\n\n  /**\n   * Turn off process function\n   *\n   * @param  {Function} cb callback\n   */\n  exit(cb) {\n    this.isExiting = true;\n    // close db connection\n    if (this.db.defaultConnection) {\n      this.db.defaultConnection.close();\n    }\n    // close all loggers and wait for end writes\n    this.log.closeAllLoggersAndDisconnect(this, cb);\n  },\n\n  /**\n   * Helper function to delete objects from response for help GC\n   */\n  freeResponseMemory(req, res) {\n    if (res.locals) {\n      res.locals.regions = {};\n      res.locals.currentUser = {};\n    }\n\n    delete req.user;\n  },\n\n  /**\n   * Run all plugin and project cron tasks\n   *\n   * @param  {Function} cb callback\n   */\n  runCron(cb) {\n    this.cron = require('./cron');\n    this.cron.loadAndRunAllTasks(this, cb);\n  },\n\n  /**\n   * set pm2 gracefullReload\n   */\n  setPM2grShutdownFN(we) {\n    // old/windows version:\n    process.on('message', (msg)=> {\n      if (msg === 'shutdown') {\n        // disconect, and exit\n        we.exit( (err)=> { process.exit(err ? 1 : 0); });\n      }\n    });\n    // new version:\n    process.on('SIGINT', ()=> {\n      we.exit( (err)=> { process.exit(err ? 1 : 0); });\n    });\n  }\n};\n\n// Add default toJSON method in errors to get better erros:\nif (!('toJSON' in Error.prototype)) {\n  Object.defineProperty(Error.prototype, 'toJSON', {\n    value: function () {\n      const alt = {};\n\n      Object.getOwnPropertyNames(this).forEach(function (key) {\n          alt[key] = this[key];\n      }, this);\n\n      return alt;\n    },\n    configurable: true,\n    writable: true\n  });\n}\n\nmodule.exports = We;"]}