miolo 1.1.5 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -1110,7 +1110,7 @@ function _init_emailer_transporter(_ref) {
1110
1110
  send_email(email).then(function (res) {
1111
1111
  _logi(logger, "[emailer] Queued email [" + email.subject + "]sent " + (res.ok ? 'OK' : 'NOT OK'));
1112
1112
  if (res.ok) {
1113
- delete email_queue_remove_ids(res.ids);
1113
+ delete email_queue_remove_ids(email.ids);
1114
1114
  }
1115
1115
  });
1116
1116
  case 3:
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -10,4 +10,4 @@
10
10
  *
11
11
  * @license MIT
12
12
  */
13
- import e from"koa";import r from"deepmerge";import t from"node:path";import{fileURLToPath as o}from"node:url";import n from"nodemailer";import i from"node:crypto";import{uncolor as a,red as l,red_light as c,yellow as u,cyan as s,magenta as d,gray as v,green as f,cyan_light as p,blue as m,green_bold as h,yellow_bold as g}from"tinguir";import y from"node:util";import b,{format as _,transports as w,createLogger as S}from"winston";import x,{readFileSync as k}from"node:fs";import{dropConnections as O,getConnection as E}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import{cacheiro as j}from"cacheiro";export{cacheiro as miolo_cacher}from"cacheiro";import q from"koa-better-body";import I from"koa-convert";import R from"koa-compress";import{constants as C}from"node:zlib";import P from"node:http";import N from"koa-ratelimit";import T from"node:https";import J from"koa-mount";import F from"koa-static";import M from"koa-favicon";import{performance as L}from"node:perf_hooks";import{Reader as A}from"@maxmind/geoip2-node";import U from"@koa/router";import z from"jwt-simple";import D from"koa-passport";import B from"passport-local";import{createSession as G}from"koa-session";import W from"@koa/cors";import H from"koa-proxies";import K from"qs";import{renderToString as Y}from"react-dom/server";import{CronJob as Q}from"cron";import V from"node:os";import Z from"diskspace";import{createHttpTerminator as $}from"http-terminator";function X(e,r,t,o,n,i,a){try{var l=e[i](a),c=l.value}catch(e){return void t(e)}l.done?r(c):Promise.resolve(c).then(o,n)}function ee(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){X(i,o,n,a,l,"next",e)}function l(e){X(i,o,n,a,l,"throw",e)}a(void 0)}))}}function re(e,r,t){return(r=function(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var o=t.call(e,r);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}(e,"string");return"symbol"==typeof r?r:r+""}(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function te(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,o)}return t}function oe(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?te(Object(t),!0).forEach((function(r){re(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):te(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}var ne=o(import.meta.url),ie=t.dirname(ne),ae=864e6,le={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:t.resolve(ie,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,ratelimit:{max:1e3,duration:6e4,errorMessage:"Rate Limit reached",whitelist_ips:[],blacklist_ips:[],ipsum_folder:"/var/ipsum"},request:{lazy:1,slow:2,onStart:void 0,onDone:void 0,geoip:{enabled:!1,db:"/var/lib/GeoIP/GeoLite2-City.mmdb",local_ips:["127.0.0.1"]}}},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:ae,secure:!0,sameSite:"lax"}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0},file:{enabled:!0,filename:"/var/log/afialapis/%MIOLO%.log",zippedArchive:!0,maxsize:20971520,maxFiles:20,hup_patch:!1},mail:{enabled:!1,level:"warn",name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},mail:{silent:!0,options:{port:25,host:"mail.com",authMethod:"PLAIN",secure:!1,tls:{rejectUnauthorized:!1},logger:!1,debug:!1},defaults:{name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},auth:{},render:{},middlewares:[],cron:[],cache:{default:{type:"combined",redis:{host:"127.0.0.1",port:6379},version:1,clean:!1},calustra:{namespace:"miolo-calustra",ttl:864e5},session:{namespace:"miolo-session",ttl:ae},custom:{}},socket:{enabled:!1,cli:{}}};const ce=new Uint8Array(256);let ue=ce.length;function se(){return ue>ce.length-16&&(i.randomFillSync(ce),ue=0),ce.slice(ue,ue+=16)}var de=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const ve=[];for(let jr=0;jr<256;++jr)ve.push((jr+256).toString(16).substr(1));function fe(e,r=0){const t=(ve[e[r+0]]+ve[e[r+1]]+ve[e[r+2]]+ve[e[r+3]]+"-"+ve[e[r+4]]+ve[e[r+5]]+"-"+ve[e[r+6]]+ve[e[r+7]]+"-"+ve[e[r+8]]+ve[e[r+9]]+"-"+ve[e[r+10]]+ve[e[r+11]]+ve[e[r+12]]+ve[e[r+13]]+ve[e[r+14]]+ve[e[r+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&de.test(e)}(t))throw TypeError("Stringified UUID is invalid");return t}function pe(e,r,t){const o=(e=e||{}).random||(e.rng||se)();return o[6]=15&o[6]|64,o[8]=63&o[8]|128,fe(o)}var me={};function he(){return he=ee((function*(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,t=(null==r?void 0:r.info)||console.error;try{var o=pe(),n=oe(oe({id:o},e),{},{sent:!1});return me[o]=n,{ok:!0,id:o}}catch(i){return t("[emailer] Error al guardar en la cola: ".concat(i)),{ok:!1,id:null,error:i}}})),he.apply(this,arguments)}var ge=(e,r)=>null!=e&&e.info?e.info(r):console.info(r),ye=(e,r)=>null!=e&&e.error?e.info(r):console.error(r);function be(e){var{options:r,defaults:t,silent:o}=e,i=n.createTransport(r,t);function a(e){return l.apply(this,arguments)}function l(){return l=ee((function*(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;if(!0===o)return ge(r,"[emailer] *********************************"),ge(r,"[emailer] This mail will not be send (emailing is disabled):"),ge(e),ge(r,"[emailer] *********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var t=yield i.sendMail(e);return t.ok=!(null==t||!t.messageId),t}catch(n){return ye(r,"[emailer] Error sending email: ".concat((null==e?void 0:e.from)||""," => ").concat((null==e?void 0:e.to)||""," (").concat((null==e?void 0:e.subject)||"",")")),{ok:!1,silent:!1,error:n,messageId:void 0}}})),l.apply(this,arguments)}function c(){return c=ee((function*(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,t=(e={},Object.values(me).filter((e=>!e.sent)).forEach((r=>{var{id:t,from:o,to:n,subject:i}=r,a="".concat(o,"_").concat(n,"_").concat(i);e[a]||(e[a]={to_subject_key:a,from:o,to:n,subject:i,count:0,ids:[]}),e[a].count++,e[a].ids.push(t);try{me[t].sent=!0}catch(l){}})),Object.values(e));if(!(t.length<=0)){ge(r,"[emailer] Sending emails queue (".concat(t.length," emails)"));var o=function*(e){e.count>1?(ge(r,"[emailer] Sending queued and stacked email [".concat(e.subject,"](x").concat(e.count,")...")),e.subject="".concat(e.subject," (x").concat(e.count,")")):ge(r,"[emailer] Sending queued email [".concat(e.subject,"]...")),a(e).then((t=>{ge(r,"[emailer] Queued email [".concat(e.subject,"]sent ").concat(t.ok?"OK":"NOT OK")),t.ok&&t.ids.forEach((e=>{delete me[e]}))}))};for(var n of t)yield*o(n);ge(r,"[emailer] Sent emails ".concat(t.length," from queue"))}})),c.apply(this,arguments)}var u={send:a,verify:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;ge(e,"[emailer] Verifying..."),i.verify((function(r,t){r?(ye(e,"[emailer] Verifying ERROR"),ye(r)):ge(e,"[emailer] Verifyed OK: Server is ready to take our messages")}))},queue_email:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;if(!0===o)return ge(r,"[emailer] *********************************"),ge(r,"[emailer] This mail will not be send (emailing is disabled):"),ge(e),ge(r,"[emailer] *********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var t=function(e){return he.apply(this,arguments)}(e,r);return ge(r,"[emailer] Queued email: ".concat((null==e?void 0:e.from)||""," => ").concat((null==e?void 0:e.to)||""," (").concat((null==e?void 0:e.subject)||"",")")),{ok:t.ok,silent:!1,error:t.error,messageId:t.id}}catch(n){return ye(r,"[emailer] Error queueing email: ".concat((null==e?void 0:e.from)||""," => ").concat((null==e?void 0:e.to)||""," (").concat((null==e?void 0:e.subject)||"",")")),{ok:!1,silent:!1,error:n,messageId:void 0}}},queue_send_emails:function(){return c.apply(this,arguments)},options:r,defaults:t,silent:o};return u}var _e={};function we(e){var{options:r,defaults:t,silent:o}=e,n=JSON.stringify({options:r,defaults:t,silent:o});return n in _e||(_e[n]=be({options:r,defaults:t,silent:o})),_e[n]}var{combine:Se,timestamp:xe,_label:ke,printf:Oe,errors:Ee}=_,je=function(e,r){var o,n,i,f,p=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",m={silly:v,debug:d,verbose:s,info:u,warn:c,error:l},h={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},g=0,_={},k=[];!0===(null==e||null===(o=e.console)||void 0===o?void 0:o.enabled)&&k.push(new w.Console({humanReadableUnhandledException:!0,level:(null==e||null===(f=e.console)||void 0===f?void 0:f.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));if(!0===(null==e||null===(n=e.file)||void 0===n?void 0:n.enabled)){var O,E,j,q=new w.File({filename:null!=e&&null!==(O=e.file)&&void 0!==O&&O.filename?e.file.filename.replace("%MIOLO%",p):"/var/log/afialapis/miolo.log",level:(null==e||null===(E=e.file)||void 0===E?void 0:E.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0,maxRetries:10});!0===(null==e||null===(j=e.file)||void 0===j?void 0:j.hup_patch)&&function(e){process.on("SIGHUP",(function(){var r=t.join(e.dirname,e._getFile(!1));return function(){console.log("[miolo][file-logger] SIGHUP received. Reopening ".concat(r,"..."));try{e._stream&&(e._stream.end(),e._stream.destroy());var t=x.createWriteStream(r,e.options);t.setMaxListeners(1/0),e._size=0,e._stream=t,e.opening=!1,e.emit("open",r),console.log("[miolo][file-logger] Reopened ".concat(r," successfully"))}catch(o){console.error("[miolo][file-logger] Error reopening ".concat(r,": ").concat(o.toString()))}}()}))}(q),k.push(q)}if(!0===(null==e||null===(i=e.mail)||void 0===i?void 0:i.enabled)){var I=function(e,r){var t=function(t){b.Transport.call(this,t),t=t||{},this.level=e.level||"info",this.ename=(null==e?void 0:e.name)||r.defaults.name,this.to=e.to||r.defaults.to,this.from=e.from||r.defaults.from,this.humanReadableUnhandledException=t.humanReadableUnhandledException||!0,this.handleExceptions=t.handleExceptions||!0,this.json=t.json||!1,this.colorize=t.colorize||!1};return y.inherits(t,b.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n="",i="";try{try{n=t.message.split("\n")[0]}catch(u){n=t.message.toString()}n=a(n)}catch(s){n="Could not create a title for the error (".concat(s.toString(),")")}try{try{i=a(t.message)}catch(s){i=t.message.toString()}}catch(s){i="Could not create a body for the error (".concat(s.toString(),")")}try{var l="".concat(null==e?void 0:e.name," [").concat(t.level.toUpperCase(),"] ").concat(n),c={from:this.from,to:this.to,subject:l,text:i};r.queue_email(c),this.emit("logged"),o(null,!0)}catch(d){this.emit("logged"),o(null,!0)}},t}(e.mail,r);w.MailerLogger=I,k.push(new w.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}var R=S({level:(null==e?void 0:e.level)||"silly",format:Se(Ee({stack:!0}),xe(),Oe((r=>{var t,o=m[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),i="".padStart(g," "),a="[".concat(p,"] ").concat(o(n)," ").concat(o(h[r.level])," ").concat(i).concat(r.message);return r.stack?"".concat(a,"\n").concat(r.stack):a}))),transports:k}),C=(e,r)=>{var t=(r,t)=>{try{if(null!=t&&t.section)if(t.section in _){var o=parseFloat((Date.now()-_[t.section].timeStart)/1e3).toFixed(2);r="".concat(r," (time: ").concat(o,")"),g-=_[t.section].indentIncr,e(r,t),delete _[t.section]}else{_[t.section]={indentIncr:parseInt((null==t?void 0:t.indent)||4),timeStart:Date.now()};var n=Math.max(g+_[t.section].indentIncr,0);e(r,t),g=n}else e(r,t)}catch(i){console.error(i)}};return Object.defineProperty(t,"name",{value:r}),t};R.error=C(R.error,"error"),R.warn=C(R.warn,"warn"),R.info=C(R.info,"info"),R.http=C(R.http,"http"),R.verbose=C(R.verbose,"verbose"),R.debug=C(R.debug,"debug"),R.silly=C(R.silly,"silly");try{R.debug("[logger] Inited for ".concat(R.transports.map((e=>"".concat(e.name," (").concat(e.level,")").concat(e.silent?l(" SILENT!"):""))).join(",")))}catch(P){}return R};class qe{parse_value_str(e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong str value passed: ".concat(e);return r}return e.toString()}parse_field_str(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected str value not passed for ".concat(r);return o}return this.parse_value_str(e[r],t,o)}parse_value_int(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,o=parseInt(e);if(null==o||isNaN(o)){if(r)throw"Wrong int value passed: ".concat(e);return t}return o}parse_field_int(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected int value not passed for ".concat(r);return o}return this.parse_value_int(e[r],t,o)}parse_value_float(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,o=parseFloat(e);if(null==o||isNaN(o)){if(r)throw"Wrong float value passed: ".concat(e);return t}return e}parse_field_float(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected float value not passed for ".concat(r);return o}return this.parse_value_float(e[r],t,o)}parse_value_bool(e){if(null!=e&&null!=e)return!0===e||"true"===e||"True"===e||1===e||"1"===e||!1!==e&&"false"!==e&&"False"!==e&&0!==e&&"0"!==e&&(arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0);if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong bool value passed for ".concat(name)}parse_field_bool(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected bool value not passed for ".concat(r);return o}return this.parse_value_bool(e[r],t,o)}parse_value_obj(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(r)throw"Wrong obj value passed: ".concat(e);return t}if(0==Object.keys(e).length){if(r)throw"Empty obj value passed: ".concat(e);return t}if("object"!=typeof e)throw"Wrong obj value passed: ".concat(e);return e}parse_field_obj(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected obj value not passed for ".concat(r);return o}return this.parse_value_obj(e[r],t,o)}}var Ie=()=>new qe;function Re(e,r,t){var o,n,i,a,l,c,u,s,d,v,f,p,m,h,g=(null==r||null===(o=r.redis)||void 0===o?void 0:o.host)||(null==e||null===(n=e.redis)||void 0===n?void 0:n.host)||(null===(i=process.env)||void 0===i?void 0:i.REDIS_HOST)||"127.0.0.1",y=(null==r||null===(a=r.redis)||void 0===a?void 0:a.port)||(null==e||null===(l=e.redis)||void 0===l?void 0:l.port)||(null===(c=process.env)||void 0===c?void 0:c.REDIS_PORT)||6379,b=(null==r||null===(u=r.redis)||void 0===u?void 0:u.username)||(null==e||null===(s=e.redis)||void 0===s?void 0:s.username)||(null===(d=process.env)||void 0===d?void 0:d.REDIS_USERNAME)||"",_=(null==r||null===(v=r.redis)||void 0===v?void 0:v.password)||(null==e||null===(f=e.redis)||void 0===f?void 0:f.password)||(null===(p=process.env)||void 0===p?void 0:p.REDIS_PASSWORD)||"",w="";b&&(w="".concat(b).concat(_?":".concat(_):"","@"));var S=(null==r||null===(m=r.redis)||void 0===m?void 0:m.url)||(null==e||null===(h=e.redis)||void 0===h?void 0:h.url)||"redis://".concat(w).concat(g,":").concat(y);return{type:(null==r?void 0:r.type)||(null==e?void 0:e.type),redis:{url:S},namespace:(null==r?void 0:r.namespace)||(null==e?void 0:e.namespace),version:(null==r?void 0:r.version)||(null==e?void 0:e.version),clean:!0===(null==r?void 0:r.clean)||!0===(null==e?void 0:e.clean),ttl:(null==r?void 0:r.ttl)||(null==e?void 0:e.ttl),log:t}}function Ce(e,r){return Re(e.cache.default,e.cache.calustra,r)}var Pe=void 0;function Ne(e,r){var t=function(){var t=ee((function*(){if(null==Pe){Pe={};var t=function(e,r){var t=e.cache.default,o=e.cache.custom||{},n={};for(var[i,a]of Object.entries(o)){var l=Re(t,a,r);l.namespace=l.namespace||"miolo-".concat(i),n[i]=l}return n}(e,r);for(var[o,n]of Object.entries(t)){var i=yield j(n);Pe[o]=i}}return Pe}));return function(){return t.apply(this,arguments)}}(),o=function(){var e=ee((function*(e){return(yield t())[e]}));return function(r){return e.apply(this,arguments)}}(),n=function(){var e=ee((function*(){var e=yield t();return Object.keys(e)}));return function(){return e.apply(this,arguments)}}(),i=function(){var e=ee((function*(e,r){var n=yield t();r&&(yield o(e)).unsetAll();delete n[e]}));return function(r,t){return e.apply(this,arguments)}}(),a=function(){var e=ee((function*(e){if(e){var r=yield t();for(var[o,n]of Object.entries(r))yield n.unsetAll()}Pe={}}));return function(r){return e.apply(this,arguments)}}();return{get_cache:o,get_cache_names:n,drop_cache:i,drop_caches:a}}var Te=(e,r)=>{var t=we(r.mail),o=je(r.log,t,null==r?void 0:r.name),n=Ie(),i=function(e,r){var t,o,n=function(){var t=ee((function*(t){var o=oe(oe(oe({},e.db.options),t||{}),{},{log:r,cache:Ce(e,r)}),n=yield E(e.db.config,o);return n.get_model=n.getModel,n}));return function(e){return t.apply(this,arguments)}}(),i=function(){var t=ee((function*(t,o){var n=oe(oe(oe({},e.db.options),o||{}),{},{log:r});return(yield E(e.db.config,n)).get_model(t)}));return function(e,r){return t.apply(this,arguments)}}(),a={init_connection:(o=ee((function*(){return yield n({reset:!0})})),function(){return o.apply(this,arguments)}),fly_connection:(t=ee((function*(){return yield n({cache:!1})})),function(){return t.apply(this,arguments)}),get_connection:n,get_model:i,drop_connections:O};return a}(r,o),a=Ne(r,o),l={config:oe({},r),emailer:t,logger:o,parser:n,db:i,cache:a};function c(){return(c=ee((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return c.apply(this,arguments)})),e.context.miolo=l},Je=[401,403];var Fe="/var/ipsum",Me="ipsum.txt";function Le(e,r){var t=r?r.error:console.error;if(!e)return[];try{var o=[];return e.split("\n").filter((e=>e.indexOf("#")<0)).map((e=>{var[r,t]=e.split("\t");parseInt(t)>=1&&o.push(r)})),o}catch(n){return t("[cron][".concat(s("IPsum"),"] Error getting IPs from content")),[]}}function Ae(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fe,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,n=o?o.error:console.error,i=o?o.debug:console.log;if(x.existsSync(e))try{i("[cron][".concat(s("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",t=arguments.length>2?arguments[2]:void 0,o=t?t.error:console.error;T.get(r,(r=>{var t=[];r.on("data",(e=>{t.push(e)})).on("end",(()=>{var r=Buffer.concat(t).toString();e(r)}))})).on("error",(r=>{o("[cron][".concat(s("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((n=>{var a=t.join(e,Me);x.writeFileSync(a,n,{encoding:"utf8",flag:"w"});var l=n.split("\n").length,c=Le(n,o),u=c.length;i("[cron][".concat(s("IPsum"),"] File downloaded. ").concat(l," ips on the list (").concat(u," appearing in ").concat(1," or more lists)")),r&&r(c)}))}catch(a){n("[cron][".concat(s("IPsum"),"] Error ").concat(a," updating the file"))}else n("[cron][".concat(s("IPsum"),"] Folder ").concat(e," does not exist"))}function Ue(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fe,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,n=o?o.debug:console.log,i=o?o.warn:console.log,a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fe,r=arguments.length>1?arguments[1]:void 0,o=r?r.error:console.error;if(!x.existsSync(e))return r&&o("[cron][".concat(s("IPsum"),"] Folder ").concat(e," does not exist")),[];var n=t.join(e,Me);return x.existsSync(n)?Le(x.readFileSync(n,{encoding:"utf8"}),r):(r&&o("[cron][".concat(s("IPsum"),"] File ").concat(n," does not exist")),[])}(e,o);return a.length>0?(r&&r(a),n("[cron][".concat(s("IPsum"),"] File contains ").concat(a.length," ips")),a):(i("[cron][".concat(s("IPsum"),"] File is empty. Launching update...")),Ae(e,r,o),[])}var ze=["52.212.247.108","54.218.32.58","170.106.82.193","110.166.71.39","39.107.54.8","205.210.31.240 ","134.122.52.203","165.232.105.25","66.249.73.200","35.206.153.204","199.244.88.227","198.12.222.107","212.128.118.10"];var De=o(import.meta.url),Be=t.dirname(De),Ge=t.resolve(Be,"./miolo.ico"),We=t.resolve(Be,"../../../.."),He=void 0,Ke=["127.0.0.1","::1:"];var Ye=function(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(function(e){return[...Ke,...(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[])||[]].indexOf(e)>=0}(e,null==r?void 0:r.local_ips))return{local:!0,country:"",city:""};try{var o,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/var/lib/GeoIP/GeoLite2-City.mmdb",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:console;try{if(null!=He)return He;var t=x.readFileSync(e);return He=A.openBuffer(t)}catch(o){return r.error("[geoip] Error initing:"),void r.error(o)}}(null==r?void 0:r.db,t),i=n.city(e);return{country:i.country.isoCode,city:null===(o=i.city)||void 0===o||null===(o=o.names)||void 0===o?void 0:o.en}}catch(a){t.error("[geoip] Error localizing IP ".concat(e,":")),t.error(a)}return{country:"",city:""}},Qe={total:0};var Ve=o(import.meta.url),Ze=t.dirname(Ve),$e=k(t.resolve(Ze,"./robots.txt"),"utf8");var Xe=(e,r,t)=>{var o=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(t||{})}catch(n){}return function(e,r){var t=Math.random().toString(),o=null==e?void 0:e.secret;o||(o="miolo_unsafe_secret",r.error("Guest token made with an unsafe secret string. Please, configure your own through session.secret."));var n={admin:!1,buid:t};return z.encode(n,o)}(t||{},o)};function i(){return i=ee((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),o.debug("Guest token conceeded"));var a=function(e){var r,t=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(t)&&(t=86400);var o=new Date;return o.setSeconds(o.getSeconds()+t),{expires:o,httpOnly:!1}}(t);e.cookies.set("token",i,a),e.session={user:{name:"guest"},authenticated:!0,token:i},yield r()})),i.apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))},er=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=ee((function*(r,n){var i;try{i=(e=>{var r,t=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(t)try{t=t.replace("Basic ","");try{t=Buffer.from(t,"base64").toString()}catch(i){t=atob(t)}var[o,n]=t.split(":");return{username:o,password:n}}catch(i){return}})(r.request)}catch(c){}var a=()=>{r.session={user:void 0,authenticated:!1},r.body={user:void 0,authenticated:!1},r.response.status=401,r.response.headers["WWW-Authenticate"]='Basic realm="'+o.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield t(i.username,i.password,e.context.miolo);if(!1===l||null==l)return a();r.session={user:l,authenticated:!0},yield n()}))).apply(this,arguments)}o||(o="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(J(r,i))))};class rr{constructor(e,r){this.options=e,this.logger=r,this._cache=void 0}init_cache(){var e=this;return ee((function*(){return null==e._cache&&(e.logger.silly("[session-store] Initing store"),e._cache=yield j(e.options)),e._cache}))()}get(e,r,t){var o=this;return ee((function*(){var{rolling:r,ctx:n}=t,i=yield o.init_cache(),a=yield i.getItem(e);try{var l=JSON.parse(a);return o.logger.silly("[session-store] Get session for ".concat(e,": ").concat(JSON.stringify(l))),l}catch(c){return void o.logger.silly("[session-store] No session for ".concat(e))}}))()}set(e,r,t,o){var n=this;return ee((function*(){var{rolling:t,changed:i,ctx:a}=o;n.logger.silly("[session-store] Set session for ".concat(e));var l=yield n.init_cache(),c=void 0;try{c=JSON.stringify(r)}catch(u){}yield l.setItem(e,c)}))()}destroy(e,r){var t=this;return ee((function*(){var{ctx:o}=r;t.logger.silly("[session-store] Destroy session for ".concat(e));var n=yield t.init_cache();yield n.unsetItem(e)}))()}}function tr(e,r){var t=function(e,r){return Re(e.cache.default,e.cache.session,r)}({cache:e},r);return new rr(t,r)}var or=(e,r,t)=>r(null,e.id),nr=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},ir=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},ar=(e,r,t,o)=>{var{get_user_id:n,find_user_by_id:i,local_auth_user:a,url_login:l,url_logout:c,url_login_redirect:u,url_logout_redirect:s}=r,d=n||or,v=i||nr,f=a||ir,p=l||"/login",m=c||"/logout",h=new B.Strategy(((r,t,o)=>{f(r,t,o,e.context.miolo)}));function g(){return(g=ee((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(t){}yield r()}))).apply(this,arguments)}!function(e,r,t){var o=tr(t,e.context.miolo.logger);e.keys=[r.secret||"*secret*"];var n=oe({store:o},r.options||{});e.use(G(n,e))}(e,t,o),D.serializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),D.deserializeUser(((r,t)=>{process.nextTick((function(){v(r,t,e.context.miolo)}))})),D.use(h),e.use(D.initialize()),e.use(D.session()),e.use((function(e,r){return g.apply(this,arguments)}));var y=function(){var e=ee((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,yield e.logout(),e.body={user:void 0,authenticated:!1},null!=s&&e.redirect(s)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,t){return e.apply(this,arguments)}}(),b=new U;b.post(p,((e,r)=>D.authenticate("local",function(){var r=ee((function*(r,t,o,n){if(!1!==t)return e.session.user=e.state.user,e.session.authenticated=!0,e.body={user:t,authenticated:!0},null!=u&&e.redirect(u),yield e.login(t);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:o,error:r},e.response.status=401}));return function(e,t,o,n){return r.apply(this,arguments)}}())(e))),b.get(m,y),b.post(m,y),e.use(b.routes())},lr=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},cr=(e,r)=>{var t=e.context.miolo.logger;lr(r,"cors",(r=>{if("simple"==r)t.debug("[http] Setting CORS the simple way"),e.use(function(){var e=ee((function*(e,r){e.set("[http] Access-Control-Allow-Origin","*"),e.set("[http] Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,t){return e.apply(this,arguments)}}());else{var o=(e=>"object"==typeof e?e:{})(r);t.debug("[http] Setting CORS headers for ".concat(JSON.stringify(o))),e.use(W(o))}})),lr(r,"proxy",(r=>{var[o,n]=(e=>{var r,t,o,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(t=e)||void 0===t?void 0:t.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(o=e)||void 0===o?void 0:o.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);t.debug("[http] Setting Proxy for ".concat(o," to ").concat(n.target," ")),e.use(H(o,n))}))},ur=function(){var e=ee((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),sr=function(){var e=ee((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),dr={require:!1,action:"redirect",redirect_url:"/",error_code:401},vr={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}};function fr(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?K.parse(r):{}}function pr(e,r){function t(e){return o.apply(this,arguments)}function o(){return(o=ee((function*(r){var t=r.request.fields;try{r.miolo.logger.debug("[router] ".concat(e.name,"() Calling with params ").concat(JSON.stringify(t)))}catch(n){r.miolo.logger.debug("[router] ".concat(e.name,"()Calling with params (?)"))}var o=yield e(r.miolo,t);try{r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result ").concat(JSON.stringify(o)))}catch(n){r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result (?)"))}r.body=o}))).apply(this,arguments)}return Object.defineProperty(t,"name",{value:e.name,writable:!1}),t}function mr(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n=function(){var e=ee((function*(e,t){var o,n=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"w"===t)||(n||("error"==i.action?(e.miolo.logger.error("[router] Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(e.miolo.logger.warn("[router] Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(e.miolo.logger.error("[router] Crud path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r,t){return e.apply(this,arguments)}}(),i=function(){var e=ee((function*(e,t,o){var i=yield e.miolo.db.get_model(r.name);if(!i)throw e.miolo.logger.error("[router] Could not get model for ".concat(r.name)),new Error("[router] Could not get model for ".concat(r.name));var a,l={};try{var c;if(!(yield n(e,t)))return void(e.body={});var u=!0;if(null!=r&&r.before&&(u=yield r.before(e)),!u)return void(e.body={});var s=null==e||null===(c=e.session)||void 0===c||null===(c=c.user)||void 0===c?void 0:c.id,d={};!0===r.useUserFields.use&&(d=r.useUserFields.fieldNames);var v={uid:s,fieldNames:d};l=yield o(i,v),null!=r&&r.after&&(l=yield r.after(e,l))}catch(f){e.miolo.logger.error("[router] Unexpected error on CRUD ".concat(r.name,"-").concat(t)),e.miolo.logger.error(f)}a=l,l=null==r.bodyField?a:{[r.bodyField]:a},e.body=l}));return function(r,t,o){return e.apply(this,arguments)}}(),a=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.read(o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.keyList(o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.find(o.id,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.distinct(o.distinct_field,o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=ee((function*(e){yield i(e,"w",function(){var r=ee((function*(r,t){var o,n=e.request.fields;null!=t&&null!==(o=t.fieldNames)&&void 0!==o&&o.created_by&&(n[t.fieldNames.created_by]=t.uid);var i={transaction:void 0};return yield r.insert(n,i)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=ee((function*(e){yield i(e,"w",function(){var r=ee((function*(r,t){var o,n=e.request.fields;null!=t&&null!==(o=t.fieldNames)&&void 0!==o&&o.last_update_by&&(n[t.fieldNames.last_update_by]=t.uid);var i={transaction:void 0};return yield r.update(n,{id:n.id},i)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=function(){var e=ee((function*(e){yield i(e,"w",function(){var r=ee((function*(r,t){var o=e.request.fields,n={transaction:void 0};return yield r.delete({id:o.id},n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);f.indexOf("//")>=0;)f=f.replace(/\/\//g,"/");t.debug("[router] Routing table ".concat(r.name," to ").concat(f));var p=r.mode.indexOf("r")>=0,m=r.mode.indexOf("w")>=0,h=r.mode.indexOf("u")>=0||m;p&&(e.get("".concat(f,"/find"),(e=>c(e))),e.get("".concat(f,"/read"),(e=>a(e))),e.get("".concat(f,"/distinct"),(e=>u(e))),e.get("".concat(f,"/key_list"),(e=>l(e)))),h&&(e.post("".concat(f,"/save"),(e=>s(e))),e.post("".concat(f,"/update"),(e=>d(e)))),m&&e.post("".concat(f,"/delete"),(e=>v(e)))}))}))}function hr(e,t){var o=e.context.miolo.logger,n=new U;try{var i=(e=>{var t=(null==e?void 0:e.crud)||[];if(!t)return[];if(!Array.isArray(t))return[];var o=[];return t.map((t=>{var n=null==t?void 0:t.routes;if(n&&Array.isArray(n)){var i=(null==t?void 0:t.bodyField)||(null==e?void 0:e.bodyField),a=(null==t?void 0:t.before)||(null==e?void 0:e.before)||ur,l=(null==t?void 0:t.after)||(null==e?void 0:e.after)||sr,c=r.all([dr,(null==e?void 0:e.auth)||{},(null==t?void 0:t.auth)||{}]),u=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var v={name:d.name,url:(null==d?void 0:d.url)||d.name,mode:(null==d?void 0:d.mode)||"rw",bodyField:(null==d?void 0:d.bodyField)||i,useUserFields:r.all([vr,(null==d?void 0:d.useUserFields)||{}]),auth:r.all([c,(null==d?void 0:d.auth)||{}]),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};u.push(v)}}u.length>0&&o.push({prefix:(null==t?void 0:t.prefix)||"",routes:u})}})),o})(t),a=(e=>{var t=(null==e?void 0:e.queries)||[];if(!t)return[];if(!Array.isArray(t))return[];var o=[];return t.map((t=>{var n=null==t?void 0:t.routes;if(n&&Array.isArray(n)){var i=(null==t?void 0:t.before)||(null==e?void 0:e.before)||ur,a=(null==t?void 0:t.after)||(null==e?void 0:e.after)||sr,l=r.all([dr,(null==t?void 0:t.auth)||{},(null==e?void 0:e.auth)||{}]),c=[];for(var u of n)if(u.url){var s=void 0;if(u.callback||u.callback_fn){s=u.callback||pr(u.callback_fn);var d={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:s,auth:r.all([l,(null==u?void 0:u.auth)||{}]),before:(null==u?void 0:u.before)||i,after:(null==u?void 0:u.after)||a};c.push(d)}}o.push({prefix:(null==t?void 0:t.prefix)||"",routes:c})}})),o})(t),l=i.length>0,c=a.length>0;if(!l&&!c)throw"[router] Could not get any route from the passed <routes> param";l&&mr(n,i,o),c&&function(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n,i=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");var a=r.auth,l=!0===a.require||"read-only"===a.require&&"POST"===r.method;t.debug("[router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i).concat(l?" (auth)":""));var c=function(){var e=ee((function*(e){if(l){var t,o=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return o||("error"==a.action?(e.miolo.logger.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(e.miolo.logger.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(e.miolo.logger.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),o}return!0}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ee((function*(e){var t={};try{try{var o;if("GET"==r.method&&(null===(o=e.request)||void 0===o||!o.fields)&&e.request.url.indexOf("?")>0){var n=fr(e.request.url);n&&(e.request.fields=n)}}catch(u){e.miolo.logger.error("[router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield c(e)))return;var a=!0;if(null!=r&&r.before&&(a=yield r.before(e)),!a)return;t=yield r.callback(e),null!=r&&r.after&&(t=yield r.after(e,t))}catch(s){var l;e.miolo.logger.error("[router] Unexpected error on Query ".concat(null===(l=r.callback)||void 0===l?void 0:l.name," at ").concat(i)),e.miolo.logger.error(s)}return t}));return function(r){return e.apply(this,arguments)}}(),s=r.method.toLowerCase();e[s](i,(e=>u(e,r)))}))}))}(n,a,o)}catch(u){o.error("[router] Error initing the router."),o.error("[router] routes:"),o.error(t),o.error(u)}e.use(n.routes())}var gr=o(import.meta.url),yr=t.dirname(gr),br=k(t.resolve(yr,"fallback_index.html"),"utf8");function _r(e,r,t,o,n){var i=(null==r?void 0:r.html)||br;i.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),i.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var a=function(){var e=ee((function*(e){var t={};try{var o;null!=r&&null!==(o=r.ssr)&&void 0!==o&&o.loader&&(t=yield r.ssr.loader(e))}catch(c){var n,i="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(n=e.request)||void 0===n?void 0:n.fields)||{})),a=null!=c&&c.stack?"".concat(c.toString(),"\n").concat(c.stack):c.toString(),l="".concat("Error produced by loader in render.ssr middleware","\n").concat(i,"\n").concat(a);e.miolo.logger.error(l)}return t}));return function(r){return e.apply(this,arguments)}}();function l(){return(l=ee((function*(e){var n,l,c=((e,r,t)=>{var o,n,i=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated);return{config:r,user:null==e||null===(n=e.session)||void 0===n?void 0:n.user,authenticated:i,ssr_data:t,extra:null==e?void 0:e.extra}})(e,{hostname:null==t?void 0:t.hostname,port:null==t?void 0:t.port,catcher_url:null==t?void 0:t.catcher_url,login_url:null==o||null===(n=o.credentials)||void 0===n?void 0:n.url_login,logout_url:null==o||null===(l=o.credentials)||void 0===l?void 0:l.url_logout},yield a(e)),u=((e,t)=>{var o="";try{var n;null!=r&&null!==(n=r.ssr)&&void 0!==n&&n.renderer?o=Y(r.ssr.renderer(e,t)):e.miolo.logger.warn("Missing renderer in render.ssr middleware")}catch(a){e.miolo.logger.error("Error in renderer (render.ssr middleware):\n".concat(a.toString())),o="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return i.replace("{context}",JSON.stringify(t,null,2)).replace("{children}",o)})(e,c);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(u,"utf8")," bytes")),e.body=u}))).apply(this,arguments)}e.use((function(e){return l.apply(this,arguments)}))}function wr(e){return e?e/1e6:0}function Sr(e){return e?e/1e6:0}function xr(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(wr(V.freemem()),2),n=Math.round(wr(V.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[cron][".concat(s("SysCheck"),"] RAM ").concat(u(o)," MB used of ").concat(f(n)," MB (").concat(u(i)," %)")):t.info("[cron][".concat(s("SysCheck"),"] RAM ").concat(u(o)," MB used of ").concat(f(n)," MB (").concat(u(i)," %)")),Z.check("/",(function(e,r){var o=Math.round(Sr(r.used),2),n=Math.round(Sr(r.total),2),i=Math.round(Sr(r.free),2);i<1?t.error("[cron][".concat(s("SysCheck"),"] DISK ").concat(u(o)," GB used of ").concat(f(n)," GB (").concat(u(i)," GB free)")):t.info("[cron][".concat(s("SysCheck"),"] DISK ").concat(u(o)," GB used of ").concat(f(n)," GB (").concat(u(i)," GB free)"))}))},start:!0}}function kr(e,r){var t=e.context.miolo,o=t.logger,n=[xr(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{Ae(e.config.http.ratelimit.ipsum_folder||Fe,(r=>{e.logger.debug("[cron][".concat(s("IPsum"),"] File downloaded. ").concat(f(r.length)," ips will be ").concat(u("blacklisted"),"!"))}),e.logger)},start:!0},{name:"Emailer",cronTime:"* * * * *",onTick:(e,r)=>{e.emailer.queue_send_emails(e.logger)},start:!0},...r||[]],i=[];n.map((e=>{var r=e.name,o=function(e,r){var t,o=e.logger,n=null!=r&&null!==(t=r.onTick)&&void 0!==t&&t.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new Q((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{try{o.silly("[cron][Custom Job ".concat(s(i),"] ").concat(h("ticks!"))),r.onTick(e,t)}catch(n){o.error("[cron][Custom Job ".concat(s(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(o.silly("[cron][Custom Job ".concat(s(i),"] ").concat(h("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[cron][Custom Job ".concat(s(i),"] Error at onComplete()")),o.error(t)}}),!1,(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,isActive:!1})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||o.error("[cron] Job ".concat(s(e)," Not Found")),r},l=e=>{try{return e.job.start(),e.isActive=!0,o.debug("[cron][Job ".concat(s(e.name),"] ").concat(h("started!"))),1}catch(r){return o.error("[cron][Job ".concat(s(e.name),"] Error starting it")),o.error(r),0}},c=e=>{try{return e.job.stop(),e.isActive=!1,o.debug("[cron][Job ".concat(s(e.name),"] ").concat(g("stopped!"))),1}catch(r){return o.error("[cron][Job ".concat(s(e.name),"] Error stopping it")),o.error(r),0}};return e.cron={jobs:i,start_one:e=>{var r=a(e);return r?[l(r),r.name]:[0,""]},start:()=>{try{var e=[],r=[];i.map((t=>{1==l(t)?e.push(t.name):r.push(t.name)})),e.length>0&&o.info("[cron] Started ".concat(e.length," jobs: ").concat(e)),r.length>0&&o.warn("[cron] Could not start ".concat(r.length," jobs: ").concat(r))}catch(t){o.error("[cron] start() error: ".concat(t))}},stop_one:e=>{var r=a(e);return r?[c(r),r.name]:[0,""]},stop:()=>{try{var e=[],r=[];i.map((t=>{1==c(t)?e.push(t.name):r.push(t.name)})),e.length>0&&o.info("[cron] Stopped ".concat(e.length," jobs: ").concat(e)),r.length>0&&o.warn("[cron] Could not stop ".concat(r.length," jobs: ").concat(r))}catch(t){o.error("[cron] stop() error: ".concat(t))}}},e}function Or(e,r){var t,o=e.context.miolo.logger,n=function(){var t=ee((function*(){try{var t,n,i;if(null!=(null===(t=e.http)||void 0===t?void 0:t.server))return void o.warn("[http][start] Server already running on ".concat(null==e||null===(n=e.http)||void 0===n?void 0:n.hostname,":").concat(null==e||null===(i=e.http)||void 0===i?void 0:i.port));var a=P.createServer(e.callback()),l=$({server:a}),c=function(){var t=ee((function*(){try{yield l.terminate(),delete e.http.server,o.info("[http][stop] miolo has been shutdowned from ".concat(r.hostname,":").concat(r.port))}catch(t){o.error("[http][stop] error: ".concat(t))}}));return function(){return t.apply(this,arguments)}}();e.http.server=a,e.http.stop=c,yield((e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))})))(a,r.port,r.hostname),o.info("[http][start] miolo is listening on ".concat(r.hostname,":").concat(r.port))}catch(u){o.error("[http][start] error: ".concat(u))}}));return function(){return t.apply(this,arguments)}}();return e.http={server:void 0,start:n,stop:(t=ee((function*(){o.warn("[http] stop() stop() function still not attached. Is server running?")})),function(){return t.apply(this,arguments)}),hostname:r.hostname,port:r.port},e}function Er(t,o){var n,i,a,c=new e,v=function(e){var t,o=r(le,e);return o.auth_type=function(e){var r,t,o;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.credentials?"credentials":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.custom?"custom":"guest"}(e),o.use_catcher=!(null==o||null===(t=o.http)||void 0===t||!t.catcher_url),o}(t);Te(c,v),cr(c,v.http),(e=>{e.use(R({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:C.Z_SYNC_FLUSH},deflate:{flush:C.Z_SYNC_FLUSH},br:!1})),e.use(I(q({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(c),function(e){var r=e.context.miolo.logger;function t(){return(t=ee((function*(e){if(e){if(!(e instanceof Error)){var t=e;if("object"==typeof e)try{t=JSON.stringify(e)}catch(a){}var o=new Error("non-error thrown: "+t);e&&(e.name&&(o.name=e.name),e.message&&(o.message=e.message),e.stack&&(o.stack=e.stack),e.status&&(o.status=e.status),e.headers&&(o.headers=e.headers)),e=o}(this.headerSent||!this.writable)&&(e.headerSent=!0),this.app.emit("error",e,this),"ENOENT"===e.code&&(e.status=404);var n=e.status||400;this.accepts(["text","json","html"])?"number"==typeof e.status&&P.STATUS_CODES[e.status]||(e.status=500):(n=406,e.message="Unsupported type"),this.status=n;var i=this.headers["x-real-ip"]||this.headers["x-orig-ip"]||this.ip||"127.0.0.1";Je.indexOf(n)>=0?r.warn("[".concat(i,"] ").concat(this.method," ").concat(this.url," - ").concat(n,": ").concat(e.message)):r.error(e),e.headerSent?r.warn("headers were already sent, returning early"):(this.type="json",this.body=JSON.stringify(this.body||"",null,2),this.length=Buffer.byteLength(this.body),this.res.end(this.body))}}))).apply(this,arguments)}e.context.onerror=function(e){return t.apply(this,arguments)}}(c),function(e,r){var t=e.context.miolo,o=Ue(null==r?void 0:r.ipsum_folder,void 0,t.logger),n={driver:"memory",db:new Map,id:e=>e.request.ip,headers:{remaining:"Rate-Limit-Remaining",reset:"Rate-Limit-Reset",total:"Rate-Limit-Total"},disableHeader:!1,max:(null==r?void 0:r.max)||1e3,duration:(null==r?void 0:r.duration)||6e4,errorMessage:(null==r?void 0:r.errorMessage)||"Rate Limit reached",whitelist:(null==r?void 0:r.whitelist)||(e=>{var t=(null==r?void 0:r.whitelist_ips)||[];return!!t&&t.indexOf(e.request.ip)>=0}),blacklist:(null==r?void 0:r.blacklist)||(e=>{var t=e.request.ip,n=[...o,...ze,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(t)>=0;return n&&e.miolo.logger.debug("Rejecting ".concat(u("blacklisted")," ").concat(d(t))),n})};e.use(N(n))}(c,null===(n=v.http)||void 0===n?void 0:n.ratelimit),((e,r)=>{var{favicon:t,folders:o}=r,n=t||Ge;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(We,""))),e.use(M(n)),Object.entries(o)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(We,""))),e.use(J(i,F(a,{index:!1})))})(c,null===(i=v.http)||void 0===i?void 0:i.static),function(e,r){var t=function(){var e=ee((function*(e,r){return{}}));return function(r,t){return e.apply(this,arguments)}}(),o=function(){var e=ee((function*(e,r,t){}));return function(r,t,o){return e.apply(this,arguments)}}(),n={lazy:(null==r?void 0:r.lazy)||1,slow:(null==r?void 0:r.slow)||2,onStart:(null==r?void 0:r.onStart)||t,onDone:(null==r?void 0:r.onDone)||o,geoip:(null==r?void 0:r.geoip)||{enabled:!1}};function i(){return(i=ee((function*(e,r){var t,o,i,a,c,v,m=e.miolo.logger,h=(e=>{var r=[e.headers["x-real-ip"],e.headers["x-orig-ip"],e.ip,"127.0.0.1"];for(var t of r)if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(t))return t})(e),g=L.now();e.request.body=oe(oe({},e.request.fields),e.request.files),Qe.total+=1,Qe[h]=(Qe[h]||0)+1,e.requestId=Qe.total,e.request.ip=h;var y=!0===(null==n||null===(t=n.geoip)||void 0===t?void 0:t.enabled),b={};y&&(b=Ye(h,n.geoip,m)),e.request.geoip=b;var _=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,w=y?!0===(null===(o=b)||void 0===o?void 0:o.local)?"":null!==(i=b)&&void 0!==i&&i.country?null!==(a=b)&&void 0!==a&&a.city?" (".concat(null===(c=b)||void 0===c?void 0:c.city,", ").concat(b.country,")"):" (".concat(b.country,")"):"":"",S="".concat(d(h)).concat(w," ").concat(s(e.request.method)," ").concat(s(_)," [").concat(p(Qe[h]),"/").concat(p(e.requestId),"]"),x=null!=e.request.body?JSON.stringify(e.request.body):"";m.info("".concat(S," - START")),m.debug("".concat(S," - Body: ").concat(x));var k=yield n.onStart(e,{started:g,description:"pending"});yield r();var O=null==e||null===(v=e.session)||void 0===v?void 0:v.user,E="";null!=O&&(null!=O&&O.id?E=" - uid ".concat(null==O?void 0:O.id):null!=O&&O.token&&(E=" - token ".concat(null==O?void 0:O.token)));var j,q=e.response.status,I=q;200==q?j=f:q>200&&q<=299?(j=u,e.response.redirected&&e.response.url&&(I+=" -> ".concat(e.response.url))):j=l;var R="[".concat(j(I),"]"),C=parseFloat((L.now()-g)/1e3).toFixed(2),P=C<n.lazy?f:C<n.slow?u:l,N=C<n.lazy?"Ok":C<n.slow?"lazy":"slow",T=null!=e.session?JSON.stringify(e.session):"";m.debug("".concat(S," - Session: ").concat(T.slice(0,150),"...")),m.silly("".concat(S," - Session: ").concat(T));var J=null!=e.body?JSON.stringify(e.body):"";m.debug("".concat(S," - Response: ").concat(J.slice(0,150),"...")),m.silly("".concat(S," - Response: ").concat(J)),yield n.onDone(e,k,{started:g,elapsed:C,description:N}),m.info("".concat(S," - DONE ").concat(R).concat(E," (").concat(P(N),": ").concat(P(C),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(c,null==v||null===(a=v.http)||void 0===a?void 0:a.request),function(e){function r(){return(r=ee((function*(e){e.body=$e}))).apply(this,arguments)}var t=new U;t.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(t.routes())}(c),v.use_catcher&&function(e,r){function t(){return t=ee((function*(e){var{error:r,warning:t,path:o,agent:n}=e.request.body,i=e.miolo.logger;if(t){var a="".concat(u("[JS Warning]")," on ").concat(m(o),": ").concat(JSON.stringify(t.msg),"\n")+"".concat(u("[JS Warning]")," File => ").concat(t.file,"\n")+"".concat(u("[JS Warning]")," Line => ").concat(t.line,"\n")+"".concat(u("[JS Warning]")," Col => ").concat(t.col,"\n")+"".concat(u("[JS Warning]")," Error => ").concat(JSON.stringify(t.error),"\n")+"".concat(u("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var c="".concat(l("[JS Error]")," on ").concat(m(o),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(l("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(l("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(l("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(l("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(l("[JS Error]")," Agent => ").concat(n);i.error(c)}e.body={result:1}})),t.apply(this,arguments)}var o=new U;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(c,v.http.catcher_url),"guest"==v.auth_type&&Xe(c,v.auth.guest,null==v?void 0:v.session),"basic"==v.auth_type&&er(c,v.auth.basic),"credentials"==v.auth_type&&ar(c,v.auth.credentials,null==v?void 0:v.session,null==v?void 0:v.cache),"custom"==v.auth_type&&((e,r)=>{var t=e.context.miolo.logger;try{var o=r(e);if("function"==typeof o)e.use(o);else if(Array.isArray(o)){var n=new U;o.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){t.error("Custom auth error: ".concat(i,"'"))}})(c,v.auth.custom);var h=null==v?void 0:v.middlewares;return h&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(c,h),null!=v&&v.routes&&hr(c,v.routes),null!=(null==o?void 0:o.middleware)?c.use(o.middleware):_r(c,o,v.http,null==v?void 0:v.auth,null==v||v.socket),kr(c,null==v?void 0:v.cron),Or(c,null==v?void 0:v.http),c.start=ee((function*(){yield c.context.miolo.db.init_connection(),yield c.http.start(),c.cron.start()})),c.stop=ee((function*(){c.context.miolo.db.drop_connections(),yield c.http.stop(),c.cron.stop()})),c.restart=ee((function*(){yield c.stop(),yield c.start()})),c}export{Er as miolo,we as miolo_emailer,je as miolo_logger,Ie as miolo_parser};
13
+ import e from"koa";import r from"deepmerge";import t from"node:path";import{fileURLToPath as o}from"node:url";import n from"nodemailer";import i from"node:crypto";import{uncolor as a,red as l,red_light as c,yellow as u,cyan as s,magenta as d,gray as v,green as f,cyan_light as p,blue as m,green_bold as h,yellow_bold as g}from"tinguir";import y from"node:util";import b,{format as _,transports as w,createLogger as S}from"winston";import x,{readFileSync as k}from"node:fs";import{dropConnections as O,getConnection as E}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import{cacheiro as j}from"cacheiro";export{cacheiro as miolo_cacher}from"cacheiro";import q from"koa-better-body";import I from"koa-convert";import R from"koa-compress";import{constants as C}from"node:zlib";import P from"node:http";import N from"koa-ratelimit";import T from"node:https";import J from"koa-mount";import F from"koa-static";import M from"koa-favicon";import{performance as L}from"node:perf_hooks";import{Reader as A}from"@maxmind/geoip2-node";import U from"@koa/router";import z from"jwt-simple";import D from"koa-passport";import B from"passport-local";import{createSession as G}from"koa-session";import W from"@koa/cors";import H from"koa-proxies";import K from"qs";import{renderToString as Y}from"react-dom/server";import{CronJob as Q}from"cron";import V from"node:os";import Z from"diskspace";import{createHttpTerminator as $}from"http-terminator";function X(e,r,t,o,n,i,a){try{var l=e[i](a),c=l.value}catch(e){return void t(e)}l.done?r(c):Promise.resolve(c).then(o,n)}function ee(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){X(i,o,n,a,l,"next",e)}function l(e){X(i,o,n,a,l,"throw",e)}a(void 0)}))}}function re(e,r,t){return(r=function(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var o=t.call(e,r);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}(e,"string");return"symbol"==typeof r?r:r+""}(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function te(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,o)}return t}function oe(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?te(Object(t),!0).forEach((function(r){re(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):te(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}var ne=o(import.meta.url),ie=t.dirname(ne),ae=864e6,le={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:t.resolve(ie,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,ratelimit:{max:1e3,duration:6e4,errorMessage:"Rate Limit reached",whitelist_ips:[],blacklist_ips:[],ipsum_folder:"/var/ipsum"},request:{lazy:1,slow:2,onStart:void 0,onDone:void 0,geoip:{enabled:!1,db:"/var/lib/GeoIP/GeoLite2-City.mmdb",local_ips:["127.0.0.1"]}}},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:ae,secure:!0,sameSite:"lax"}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0},file:{enabled:!0,filename:"/var/log/afialapis/%MIOLO%.log",zippedArchive:!0,maxsize:20971520,maxFiles:20,hup_patch:!1},mail:{enabled:!1,level:"warn",name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},mail:{silent:!0,options:{port:25,host:"mail.com",authMethod:"PLAIN",secure:!1,tls:{rejectUnauthorized:!1},logger:!1,debug:!1},defaults:{name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},auth:{},render:{},middlewares:[],cron:[],cache:{default:{type:"combined",redis:{host:"127.0.0.1",port:6379},version:1,clean:!1},calustra:{namespace:"miolo-calustra",ttl:864e5},session:{namespace:"miolo-session",ttl:ae},custom:{}},socket:{enabled:!1,cli:{}}};const ce=new Uint8Array(256);let ue=ce.length;function se(){return ue>ce.length-16&&(i.randomFillSync(ce),ue=0),ce.slice(ue,ue+=16)}var de=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;const ve=[];for(let jr=0;jr<256;++jr)ve.push((jr+256).toString(16).substr(1));function fe(e,r=0){const t=(ve[e[r+0]]+ve[e[r+1]]+ve[e[r+2]]+ve[e[r+3]]+"-"+ve[e[r+4]]+ve[e[r+5]]+"-"+ve[e[r+6]]+ve[e[r+7]]+"-"+ve[e[r+8]]+ve[e[r+9]]+"-"+ve[e[r+10]]+ve[e[r+11]]+ve[e[r+12]]+ve[e[r+13]]+ve[e[r+14]]+ve[e[r+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&de.test(e)}(t))throw TypeError("Stringified UUID is invalid");return t}function pe(e,r,t){const o=(e=e||{}).random||(e.rng||se)();return o[6]=15&o[6]|64,o[8]=63&o[8]|128,fe(o)}var me={};function he(){return he=ee((function*(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,t=(null==r?void 0:r.info)||console.error;try{var o=pe(),n=oe(oe({id:o},e),{},{sent:!1});return me[o]=n,{ok:!0,id:o}}catch(i){return t("[emailer] Error al guardar en la cola: ".concat(i)),{ok:!1,id:null,error:i}}})),he.apply(this,arguments)}var ge=(e,r)=>null!=e&&e.info?e.info(r):console.info(r),ye=(e,r)=>null!=e&&e.error?e.info(r):console.error(r);function be(e){var{options:r,defaults:t,silent:o}=e,i=n.createTransport(r,t);function a(e){return l.apply(this,arguments)}function l(){return l=ee((function*(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;if(!0===o)return ge(r,"[emailer] *********************************"),ge(r,"[emailer] This mail will not be send (emailing is disabled):"),ge(e),ge(r,"[emailer] *********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var t=yield i.sendMail(e);return t.ok=!(null==t||!t.messageId),t}catch(n){return ye(r,"[emailer] Error sending email: ".concat((null==e?void 0:e.from)||""," => ").concat((null==e?void 0:e.to)||""," (").concat((null==e?void 0:e.subject)||"",")")),{ok:!1,silent:!1,error:n,messageId:void 0}}})),l.apply(this,arguments)}function c(){return c=ee((function*(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0,t=(e={},Object.values(me).filter((e=>!e.sent)).forEach((r=>{var{id:t,from:o,to:n,subject:i}=r,a="".concat(o,"_").concat(n,"_").concat(i);e[a]||(e[a]={to_subject_key:a,from:o,to:n,subject:i,count:0,ids:[]}),e[a].count++,e[a].ids.push(t);try{me[t].sent=!0}catch(l){}})),Object.values(e));if(!(t.length<=0)){ge(r,"[emailer] Sending emails queue (".concat(t.length," emails)"));var o=function*(e){e.count>1?(ge(r,"[emailer] Sending queued and stacked email [".concat(e.subject,"](x").concat(e.count,")...")),e.subject="".concat(e.subject," (x").concat(e.count,")")):ge(r,"[emailer] Sending queued email [".concat(e.subject,"]...")),a(e).then((t=>{ge(r,"[emailer] Queued email [".concat(e.subject,"]sent ").concat(t.ok?"OK":"NOT OK")),t.ok&&e.ids.forEach((e=>{delete me[e]}))}))};for(var n of t)yield*o(n);ge(r,"[emailer] Sent emails ".concat(t.length," from queue"))}})),c.apply(this,arguments)}var u={send:a,verify:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;ge(e,"[emailer] Verifying..."),i.verify((function(r,t){r?(ye(e,"[emailer] Verifying ERROR"),ye(r)):ge(e,"[emailer] Verifyed OK: Server is ready to take our messages")}))},queue_email:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;if(!0===o)return ge(r,"[emailer] *********************************"),ge(r,"[emailer] This mail will not be send (emailing is disabled):"),ge(e),ge(r,"[emailer] *********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var t=function(e){return he.apply(this,arguments)}(e,r);return ge(r,"[emailer] Queued email: ".concat((null==e?void 0:e.from)||""," => ").concat((null==e?void 0:e.to)||""," (").concat((null==e?void 0:e.subject)||"",")")),{ok:t.ok,silent:!1,error:t.error,messageId:t.id}}catch(n){return ye(r,"[emailer] Error queueing email: ".concat((null==e?void 0:e.from)||""," => ").concat((null==e?void 0:e.to)||""," (").concat((null==e?void 0:e.subject)||"",")")),{ok:!1,silent:!1,error:n,messageId:void 0}}},queue_send_emails:function(){return c.apply(this,arguments)},options:r,defaults:t,silent:o};return u}var _e={};function we(e){var{options:r,defaults:t,silent:o}=e,n=JSON.stringify({options:r,defaults:t,silent:o});return n in _e||(_e[n]=be({options:r,defaults:t,silent:o})),_e[n]}var{combine:Se,timestamp:xe,_label:ke,printf:Oe,errors:Ee}=_,je=function(e,r){var o,n,i,f,p=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",m={silly:v,debug:d,verbose:s,info:u,warn:c,error:l},h={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},g=0,_={},k=[];!0===(null==e||null===(o=e.console)||void 0===o?void 0:o.enabled)&&k.push(new w.Console({humanReadableUnhandledException:!0,level:(null==e||null===(f=e.console)||void 0===f?void 0:f.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));if(!0===(null==e||null===(n=e.file)||void 0===n?void 0:n.enabled)){var O,E,j,q=new w.File({filename:null!=e&&null!==(O=e.file)&&void 0!==O&&O.filename?e.file.filename.replace("%MIOLO%",p):"/var/log/afialapis/miolo.log",level:(null==e||null===(E=e.file)||void 0===E?void 0:E.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0,maxRetries:10});!0===(null==e||null===(j=e.file)||void 0===j?void 0:j.hup_patch)&&function(e){process.on("SIGHUP",(function(){var r=t.join(e.dirname,e._getFile(!1));return function(){console.log("[miolo][file-logger] SIGHUP received. Reopening ".concat(r,"..."));try{e._stream&&(e._stream.end(),e._stream.destroy());var t=x.createWriteStream(r,e.options);t.setMaxListeners(1/0),e._size=0,e._stream=t,e.opening=!1,e.emit("open",r),console.log("[miolo][file-logger] Reopened ".concat(r," successfully"))}catch(o){console.error("[miolo][file-logger] Error reopening ".concat(r,": ").concat(o.toString()))}}()}))}(q),k.push(q)}if(!0===(null==e||null===(i=e.mail)||void 0===i?void 0:i.enabled)){var I=function(e,r){var t=function(t){b.Transport.call(this,t),t=t||{},this.level=e.level||"info",this.ename=(null==e?void 0:e.name)||r.defaults.name,this.to=e.to||r.defaults.to,this.from=e.from||r.defaults.from,this.humanReadableUnhandledException=t.humanReadableUnhandledException||!0,this.handleExceptions=t.handleExceptions||!0,this.json=t.json||!1,this.colorize=t.colorize||!1};return y.inherits(t,b.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n="",i="";try{try{n=t.message.split("\n")[0]}catch(u){n=t.message.toString()}n=a(n)}catch(s){n="Could not create a title for the error (".concat(s.toString(),")")}try{try{i=a(t.message)}catch(s){i=t.message.toString()}}catch(s){i="Could not create a body for the error (".concat(s.toString(),")")}try{var l="".concat(null==e?void 0:e.name," [").concat(t.level.toUpperCase(),"] ").concat(n),c={from:this.from,to:this.to,subject:l,text:i};r.queue_email(c),this.emit("logged"),o(null,!0)}catch(d){this.emit("logged"),o(null,!0)}},t}(e.mail,r);w.MailerLogger=I,k.push(new w.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}var R=S({level:(null==e?void 0:e.level)||"silly",format:Se(Ee({stack:!0}),xe(),Oe((r=>{var t,o=m[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),i="".padStart(g," "),a="[".concat(p,"] ").concat(o(n)," ").concat(o(h[r.level])," ").concat(i).concat(r.message);return r.stack?"".concat(a,"\n").concat(r.stack):a}))),transports:k}),C=(e,r)=>{var t=(r,t)=>{try{if(null!=t&&t.section)if(t.section in _){var o=parseFloat((Date.now()-_[t.section].timeStart)/1e3).toFixed(2);r="".concat(r," (time: ").concat(o,")"),g-=_[t.section].indentIncr,e(r,t),delete _[t.section]}else{_[t.section]={indentIncr:parseInt((null==t?void 0:t.indent)||4),timeStart:Date.now()};var n=Math.max(g+_[t.section].indentIncr,0);e(r,t),g=n}else e(r,t)}catch(i){console.error(i)}};return Object.defineProperty(t,"name",{value:r}),t};R.error=C(R.error,"error"),R.warn=C(R.warn,"warn"),R.info=C(R.info,"info"),R.http=C(R.http,"http"),R.verbose=C(R.verbose,"verbose"),R.debug=C(R.debug,"debug"),R.silly=C(R.silly,"silly");try{R.debug("[logger] Inited for ".concat(R.transports.map((e=>"".concat(e.name," (").concat(e.level,")").concat(e.silent?l(" SILENT!"):""))).join(",")))}catch(P){}return R};class qe{parse_value_str(e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong str value passed: ".concat(e);return r}return e.toString()}parse_field_str(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected str value not passed for ".concat(r);return o}return this.parse_value_str(e[r],t,o)}parse_value_int(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,o=parseInt(e);if(null==o||isNaN(o)){if(r)throw"Wrong int value passed: ".concat(e);return t}return o}parse_field_int(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected int value not passed for ".concat(r);return o}return this.parse_value_int(e[r],t,o)}parse_value_float(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,o=parseFloat(e);if(null==o||isNaN(o)){if(r)throw"Wrong float value passed: ".concat(e);return t}return e}parse_field_float(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected float value not passed for ".concat(r);return o}return this.parse_value_float(e[r],t,o)}parse_value_bool(e){if(null!=e&&null!=e)return!0===e||"true"===e||"True"===e||1===e||"1"===e||!1!==e&&"false"!==e&&"False"!==e&&0!==e&&"0"!==e&&(arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0);if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong bool value passed for ".concat(name)}parse_field_bool(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected bool value not passed for ".concat(r);return o}return this.parse_value_bool(e[r],t,o)}parse_value_obj(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(r)throw"Wrong obj value passed: ".concat(e);return t}if(0==Object.keys(e).length){if(r)throw"Empty obj value passed: ".concat(e);return t}if("object"!=typeof e)throw"Wrong obj value passed: ".concat(e);return e}parse_field_obj(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected obj value not passed for ".concat(r);return o}return this.parse_value_obj(e[r],t,o)}}var Ie=()=>new qe;function Re(e,r,t){var o,n,i,a,l,c,u,s,d,v,f,p,m,h,g=(null==r||null===(o=r.redis)||void 0===o?void 0:o.host)||(null==e||null===(n=e.redis)||void 0===n?void 0:n.host)||(null===(i=process.env)||void 0===i?void 0:i.REDIS_HOST)||"127.0.0.1",y=(null==r||null===(a=r.redis)||void 0===a?void 0:a.port)||(null==e||null===(l=e.redis)||void 0===l?void 0:l.port)||(null===(c=process.env)||void 0===c?void 0:c.REDIS_PORT)||6379,b=(null==r||null===(u=r.redis)||void 0===u?void 0:u.username)||(null==e||null===(s=e.redis)||void 0===s?void 0:s.username)||(null===(d=process.env)||void 0===d?void 0:d.REDIS_USERNAME)||"",_=(null==r||null===(v=r.redis)||void 0===v?void 0:v.password)||(null==e||null===(f=e.redis)||void 0===f?void 0:f.password)||(null===(p=process.env)||void 0===p?void 0:p.REDIS_PASSWORD)||"",w="";b&&(w="".concat(b).concat(_?":".concat(_):"","@"));var S=(null==r||null===(m=r.redis)||void 0===m?void 0:m.url)||(null==e||null===(h=e.redis)||void 0===h?void 0:h.url)||"redis://".concat(w).concat(g,":").concat(y);return{type:(null==r?void 0:r.type)||(null==e?void 0:e.type),redis:{url:S},namespace:(null==r?void 0:r.namespace)||(null==e?void 0:e.namespace),version:(null==r?void 0:r.version)||(null==e?void 0:e.version),clean:!0===(null==r?void 0:r.clean)||!0===(null==e?void 0:e.clean),ttl:(null==r?void 0:r.ttl)||(null==e?void 0:e.ttl),log:t}}function Ce(e,r){return Re(e.cache.default,e.cache.calustra,r)}var Pe=void 0;function Ne(e,r){var t=function(){var t=ee((function*(){if(null==Pe){Pe={};var t=function(e,r){var t=e.cache.default,o=e.cache.custom||{},n={};for(var[i,a]of Object.entries(o)){var l=Re(t,a,r);l.namespace=l.namespace||"miolo-".concat(i),n[i]=l}return n}(e,r);for(var[o,n]of Object.entries(t)){var i=yield j(n);Pe[o]=i}}return Pe}));return function(){return t.apply(this,arguments)}}(),o=function(){var e=ee((function*(e){return(yield t())[e]}));return function(r){return e.apply(this,arguments)}}(),n=function(){var e=ee((function*(){var e=yield t();return Object.keys(e)}));return function(){return e.apply(this,arguments)}}(),i=function(){var e=ee((function*(e,r){var n=yield t();r&&(yield o(e)).unsetAll();delete n[e]}));return function(r,t){return e.apply(this,arguments)}}(),a=function(){var e=ee((function*(e){if(e){var r=yield t();for(var[o,n]of Object.entries(r))yield n.unsetAll()}Pe={}}));return function(r){return e.apply(this,arguments)}}();return{get_cache:o,get_cache_names:n,drop_cache:i,drop_caches:a}}var Te=(e,r)=>{var t=we(r.mail),o=je(r.log,t,null==r?void 0:r.name),n=Ie(),i=function(e,r){var t,o,n=function(){var t=ee((function*(t){var o=oe(oe(oe({},e.db.options),t||{}),{},{log:r,cache:Ce(e,r)}),n=yield E(e.db.config,o);return n.get_model=n.getModel,n}));return function(e){return t.apply(this,arguments)}}(),i=function(){var t=ee((function*(t,o){var n=oe(oe(oe({},e.db.options),o||{}),{},{log:r});return(yield E(e.db.config,n)).get_model(t)}));return function(e,r){return t.apply(this,arguments)}}(),a={init_connection:(o=ee((function*(){return yield n({reset:!0})})),function(){return o.apply(this,arguments)}),fly_connection:(t=ee((function*(){return yield n({cache:!1})})),function(){return t.apply(this,arguments)}),get_connection:n,get_model:i,drop_connections:O};return a}(r,o),a=Ne(r,o),l={config:oe({},r),emailer:t,logger:o,parser:n,db:i,cache:a};function c(){return(c=ee((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return c.apply(this,arguments)})),e.context.miolo=l},Je=[401,403];var Fe="/var/ipsum",Me="ipsum.txt";function Le(e,r){var t=r?r.error:console.error;if(!e)return[];try{var o=[];return e.split("\n").filter((e=>e.indexOf("#")<0)).map((e=>{var[r,t]=e.split("\t");parseInt(t)>=1&&o.push(r)})),o}catch(n){return t("[cron][".concat(s("IPsum"),"] Error getting IPs from content")),[]}}function Ae(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fe,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,n=o?o.error:console.error,i=o?o.debug:console.log;if(x.existsSync(e))try{i("[cron][".concat(s("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",t=arguments.length>2?arguments[2]:void 0,o=t?t.error:console.error;T.get(r,(r=>{var t=[];r.on("data",(e=>{t.push(e)})).on("end",(()=>{var r=Buffer.concat(t).toString();e(r)}))})).on("error",(r=>{o("[cron][".concat(s("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((n=>{var a=t.join(e,Me);x.writeFileSync(a,n,{encoding:"utf8",flag:"w"});var l=n.split("\n").length,c=Le(n,o),u=c.length;i("[cron][".concat(s("IPsum"),"] File downloaded. ").concat(l," ips on the list (").concat(u," appearing in ").concat(1," or more lists)")),r&&r(c)}))}catch(a){n("[cron][".concat(s("IPsum"),"] Error ").concat(a," updating the file"))}else n("[cron][".concat(s("IPsum"),"] Folder ").concat(e," does not exist"))}function Ue(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fe,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,n=o?o.debug:console.log,i=o?o.warn:console.log,a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fe,r=arguments.length>1?arguments[1]:void 0,o=r?r.error:console.error;if(!x.existsSync(e))return r&&o("[cron][".concat(s("IPsum"),"] Folder ").concat(e," does not exist")),[];var n=t.join(e,Me);return x.existsSync(n)?Le(x.readFileSync(n,{encoding:"utf8"}),r):(r&&o("[cron][".concat(s("IPsum"),"] File ").concat(n," does not exist")),[])}(e,o);return a.length>0?(r&&r(a),n("[cron][".concat(s("IPsum"),"] File contains ").concat(a.length," ips")),a):(i("[cron][".concat(s("IPsum"),"] File is empty. Launching update...")),Ae(e,r,o),[])}var ze=["52.212.247.108","54.218.32.58","170.106.82.193","110.166.71.39","39.107.54.8","205.210.31.240 ","134.122.52.203","165.232.105.25","66.249.73.200","35.206.153.204","199.244.88.227","198.12.222.107","212.128.118.10"];var De=o(import.meta.url),Be=t.dirname(De),Ge=t.resolve(Be,"./miolo.ico"),We=t.resolve(Be,"../../../.."),He=void 0,Ke=["127.0.0.1","::1:"];var Ye=function(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(function(e){return[...Ke,...(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[])||[]].indexOf(e)>=0}(e,null==r?void 0:r.local_ips))return{local:!0,country:"",city:""};try{var o,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/var/lib/GeoIP/GeoLite2-City.mmdb",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:console;try{if(null!=He)return He;var t=x.readFileSync(e);return He=A.openBuffer(t)}catch(o){return r.error("[geoip] Error initing:"),void r.error(o)}}(null==r?void 0:r.db,t),i=n.city(e);return{country:i.country.isoCode,city:null===(o=i.city)||void 0===o||null===(o=o.names)||void 0===o?void 0:o.en}}catch(a){t.error("[geoip] Error localizing IP ".concat(e,":")),t.error(a)}return{country:"",city:""}},Qe={total:0};var Ve=o(import.meta.url),Ze=t.dirname(Ve),$e=k(t.resolve(Ze,"./robots.txt"),"utf8");var Xe=(e,r,t)=>{var o=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(t||{})}catch(n){}return function(e,r){var t=Math.random().toString(),o=null==e?void 0:e.secret;o||(o="miolo_unsafe_secret",r.error("Guest token made with an unsafe secret string. Please, configure your own through session.secret."));var n={admin:!1,buid:t};return z.encode(n,o)}(t||{},o)};function i(){return i=ee((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),o.debug("Guest token conceeded"));var a=function(e){var r,t=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(t)&&(t=86400);var o=new Date;return o.setSeconds(o.getSeconds()+t),{expires:o,httpOnly:!1}}(t);e.cookies.set("token",i,a),e.session={user:{name:"guest"},authenticated:!0,token:i},yield r()})),i.apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))},er=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=ee((function*(r,n){var i;try{i=(e=>{var r,t=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(t)try{t=t.replace("Basic ","");try{t=Buffer.from(t,"base64").toString()}catch(i){t=atob(t)}var[o,n]=t.split(":");return{username:o,password:n}}catch(i){return}})(r.request)}catch(c){}var a=()=>{r.session={user:void 0,authenticated:!1},r.body={user:void 0,authenticated:!1},r.response.status=401,r.response.headers["WWW-Authenticate"]='Basic realm="'+o.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield t(i.username,i.password,e.context.miolo);if(!1===l||null==l)return a();r.session={user:l,authenticated:!0},yield n()}))).apply(this,arguments)}o||(o="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(J(r,i))))};class rr{constructor(e,r){this.options=e,this.logger=r,this._cache=void 0}init_cache(){var e=this;return ee((function*(){return null==e._cache&&(e.logger.silly("[session-store] Initing store"),e._cache=yield j(e.options)),e._cache}))()}get(e,r,t){var o=this;return ee((function*(){var{rolling:r,ctx:n}=t,i=yield o.init_cache(),a=yield i.getItem(e);try{var l=JSON.parse(a);return o.logger.silly("[session-store] Get session for ".concat(e,": ").concat(JSON.stringify(l))),l}catch(c){return void o.logger.silly("[session-store] No session for ".concat(e))}}))()}set(e,r,t,o){var n=this;return ee((function*(){var{rolling:t,changed:i,ctx:a}=o;n.logger.silly("[session-store] Set session for ".concat(e));var l=yield n.init_cache(),c=void 0;try{c=JSON.stringify(r)}catch(u){}yield l.setItem(e,c)}))()}destroy(e,r){var t=this;return ee((function*(){var{ctx:o}=r;t.logger.silly("[session-store] Destroy session for ".concat(e));var n=yield t.init_cache();yield n.unsetItem(e)}))()}}function tr(e,r){var t=function(e,r){return Re(e.cache.default,e.cache.session,r)}({cache:e},r);return new rr(t,r)}var or=(e,r,t)=>r(null,e.id),nr=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},ir=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},ar=(e,r,t,o)=>{var{get_user_id:n,find_user_by_id:i,local_auth_user:a,url_login:l,url_logout:c,url_login_redirect:u,url_logout_redirect:s}=r,d=n||or,v=i||nr,f=a||ir,p=l||"/login",m=c||"/logout",h=new B.Strategy(((r,t,o)=>{f(r,t,o,e.context.miolo)}));function g(){return(g=ee((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(t){}yield r()}))).apply(this,arguments)}!function(e,r,t){var o=tr(t,e.context.miolo.logger);e.keys=[r.secret||"*secret*"];var n=oe({store:o},r.options||{});e.use(G(n,e))}(e,t,o),D.serializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),D.deserializeUser(((r,t)=>{process.nextTick((function(){v(r,t,e.context.miolo)}))})),D.use(h),e.use(D.initialize()),e.use(D.session()),e.use((function(e,r){return g.apply(this,arguments)}));var y=function(){var e=ee((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,yield e.logout(),e.body={user:void 0,authenticated:!1},null!=s&&e.redirect(s)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,t){return e.apply(this,arguments)}}(),b=new U;b.post(p,((e,r)=>D.authenticate("local",function(){var r=ee((function*(r,t,o,n){if(!1!==t)return e.session.user=e.state.user,e.session.authenticated=!0,e.body={user:t,authenticated:!0},null!=u&&e.redirect(u),yield e.login(t);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:o,error:r},e.response.status=401}));return function(e,t,o,n){return r.apply(this,arguments)}}())(e))),b.get(m,y),b.post(m,y),e.use(b.routes())},lr=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},cr=(e,r)=>{var t=e.context.miolo.logger;lr(r,"cors",(r=>{if("simple"==r)t.debug("[http] Setting CORS the simple way"),e.use(function(){var e=ee((function*(e,r){e.set("[http] Access-Control-Allow-Origin","*"),e.set("[http] Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,t){return e.apply(this,arguments)}}());else{var o=(e=>"object"==typeof e?e:{})(r);t.debug("[http] Setting CORS headers for ".concat(JSON.stringify(o))),e.use(W(o))}})),lr(r,"proxy",(r=>{var[o,n]=(e=>{var r,t,o,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(t=e)||void 0===t?void 0:t.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(o=e)||void 0===o?void 0:o.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);t.debug("[http] Setting Proxy for ".concat(o," to ").concat(n.target," ")),e.use(H(o,n))}))},ur=function(){var e=ee((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),sr=function(){var e=ee((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),dr={require:!1,action:"redirect",redirect_url:"/",error_code:401},vr={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}};function fr(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?K.parse(r):{}}function pr(e,r){function t(e){return o.apply(this,arguments)}function o(){return(o=ee((function*(r){var t=r.request.fields;try{r.miolo.logger.debug("[router] ".concat(e.name,"() Calling with params ").concat(JSON.stringify(t)))}catch(n){r.miolo.logger.debug("[router] ".concat(e.name,"()Calling with params (?)"))}var o=yield e(r.miolo,t);try{r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result ").concat(JSON.stringify(o)))}catch(n){r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result (?)"))}r.body=o}))).apply(this,arguments)}return Object.defineProperty(t,"name",{value:e.name,writable:!1}),t}function mr(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n=function(){var e=ee((function*(e,t){var o,n=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"w"===t)||(n||("error"==i.action?(e.miolo.logger.error("[router] Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(e.miolo.logger.warn("[router] Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(e.miolo.logger.error("[router] Crud path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r,t){return e.apply(this,arguments)}}(),i=function(){var e=ee((function*(e,t,o){var i=yield e.miolo.db.get_model(r.name);if(!i)throw e.miolo.logger.error("[router] Could not get model for ".concat(r.name)),new Error("[router] Could not get model for ".concat(r.name));var a,l={};try{var c;if(!(yield n(e,t)))return void(e.body={});var u=!0;if(null!=r&&r.before&&(u=yield r.before(e)),!u)return void(e.body={});var s=null==e||null===(c=e.session)||void 0===c||null===(c=c.user)||void 0===c?void 0:c.id,d={};!0===r.useUserFields.use&&(d=r.useUserFields.fieldNames);var v={uid:s,fieldNames:d};l=yield o(i,v),null!=r&&r.after&&(l=yield r.after(e,l))}catch(f){e.miolo.logger.error("[router] Unexpected error on CRUD ".concat(r.name,"-").concat(t)),e.miolo.logger.error(f)}a=l,l=null==r.bodyField?a:{[r.bodyField]:a},e.body=l}));return function(r,t,o){return e.apply(this,arguments)}}(),a=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.read(o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.keyList(o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.find(o.id,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ee((function*(e){yield i(e,"r",function(){var r=ee((function*(r,t){var o=fr(e.request.url),n={transaction:void 0};return yield r.distinct(o.distinct_field,o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=ee((function*(e){yield i(e,"w",function(){var r=ee((function*(r,t){var o,n=e.request.fields;null!=t&&null!==(o=t.fieldNames)&&void 0!==o&&o.created_by&&(n[t.fieldNames.created_by]=t.uid);var i={transaction:void 0};return yield r.insert(n,i)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=ee((function*(e){yield i(e,"w",function(){var r=ee((function*(r,t){var o,n=e.request.fields;null!=t&&null!==(o=t.fieldNames)&&void 0!==o&&o.last_update_by&&(n[t.fieldNames.last_update_by]=t.uid);var i={transaction:void 0};return yield r.update(n,{id:n.id},i)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=function(){var e=ee((function*(e){yield i(e,"w",function(){var r=ee((function*(r,t){var o=e.request.fields,n={transaction:void 0};return yield r.delete({id:o.id},n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);f.indexOf("//")>=0;)f=f.replace(/\/\//g,"/");t.debug("[router] Routing table ".concat(r.name," to ").concat(f));var p=r.mode.indexOf("r")>=0,m=r.mode.indexOf("w")>=0,h=r.mode.indexOf("u")>=0||m;p&&(e.get("".concat(f,"/find"),(e=>c(e))),e.get("".concat(f,"/read"),(e=>a(e))),e.get("".concat(f,"/distinct"),(e=>u(e))),e.get("".concat(f,"/key_list"),(e=>l(e)))),h&&(e.post("".concat(f,"/save"),(e=>s(e))),e.post("".concat(f,"/update"),(e=>d(e)))),m&&e.post("".concat(f,"/delete"),(e=>v(e)))}))}))}function hr(e,t){var o=e.context.miolo.logger,n=new U;try{var i=(e=>{var t=(null==e?void 0:e.crud)||[];if(!t)return[];if(!Array.isArray(t))return[];var o=[];return t.map((t=>{var n=null==t?void 0:t.routes;if(n&&Array.isArray(n)){var i=(null==t?void 0:t.bodyField)||(null==e?void 0:e.bodyField),a=(null==t?void 0:t.before)||(null==e?void 0:e.before)||ur,l=(null==t?void 0:t.after)||(null==e?void 0:e.after)||sr,c=r.all([dr,(null==e?void 0:e.auth)||{},(null==t?void 0:t.auth)||{}]),u=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var v={name:d.name,url:(null==d?void 0:d.url)||d.name,mode:(null==d?void 0:d.mode)||"rw",bodyField:(null==d?void 0:d.bodyField)||i,useUserFields:r.all([vr,(null==d?void 0:d.useUserFields)||{}]),auth:r.all([c,(null==d?void 0:d.auth)||{}]),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};u.push(v)}}u.length>0&&o.push({prefix:(null==t?void 0:t.prefix)||"",routes:u})}})),o})(t),a=(e=>{var t=(null==e?void 0:e.queries)||[];if(!t)return[];if(!Array.isArray(t))return[];var o=[];return t.map((t=>{var n=null==t?void 0:t.routes;if(n&&Array.isArray(n)){var i=(null==t?void 0:t.before)||(null==e?void 0:e.before)||ur,a=(null==t?void 0:t.after)||(null==e?void 0:e.after)||sr,l=r.all([dr,(null==t?void 0:t.auth)||{},(null==e?void 0:e.auth)||{}]),c=[];for(var u of n)if(u.url){var s=void 0;if(u.callback||u.callback_fn){s=u.callback||pr(u.callback_fn);var d={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:s,auth:r.all([l,(null==u?void 0:u.auth)||{}]),before:(null==u?void 0:u.before)||i,after:(null==u?void 0:u.after)||a};c.push(d)}}o.push({prefix:(null==t?void 0:t.prefix)||"",routes:c})}})),o})(t),l=i.length>0,c=a.length>0;if(!l&&!c)throw"[router] Could not get any route from the passed <routes> param";l&&mr(n,i,o),c&&function(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n,i=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");var a=r.auth,l=!0===a.require||"read-only"===a.require&&"POST"===r.method;t.debug("[router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i).concat(l?" (auth)":""));var c=function(){var e=ee((function*(e){if(l){var t,o=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return o||("error"==a.action?(e.miolo.logger.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(e.miolo.logger.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(e.miolo.logger.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),o}return!0}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=ee((function*(e){var t={};try{try{var o;if("GET"==r.method&&(null===(o=e.request)||void 0===o||!o.fields)&&e.request.url.indexOf("?")>0){var n=fr(e.request.url);n&&(e.request.fields=n)}}catch(u){e.miolo.logger.error("[router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield c(e)))return;var a=!0;if(null!=r&&r.before&&(a=yield r.before(e)),!a)return;t=yield r.callback(e),null!=r&&r.after&&(t=yield r.after(e,t))}catch(s){var l;e.miolo.logger.error("[router] Unexpected error on Query ".concat(null===(l=r.callback)||void 0===l?void 0:l.name," at ").concat(i)),e.miolo.logger.error(s)}return t}));return function(r){return e.apply(this,arguments)}}(),s=r.method.toLowerCase();e[s](i,(e=>u(e,r)))}))}))}(n,a,o)}catch(u){o.error("[router] Error initing the router."),o.error("[router] routes:"),o.error(t),o.error(u)}e.use(n.routes())}var gr=o(import.meta.url),yr=t.dirname(gr),br=k(t.resolve(yr,"fallback_index.html"),"utf8");function _r(e,r,t,o,n){var i=(null==r?void 0:r.html)||br;i.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),i.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var a=function(){var e=ee((function*(e){var t={};try{var o;null!=r&&null!==(o=r.ssr)&&void 0!==o&&o.loader&&(t=yield r.ssr.loader(e))}catch(c){var n,i="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(n=e.request)||void 0===n?void 0:n.fields)||{})),a=null!=c&&c.stack?"".concat(c.toString(),"\n").concat(c.stack):c.toString(),l="".concat("Error produced by loader in render.ssr middleware","\n").concat(i,"\n").concat(a);e.miolo.logger.error(l)}return t}));return function(r){return e.apply(this,arguments)}}();function l(){return(l=ee((function*(e){var n,l,c=((e,r,t)=>{var o,n,i=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated);return{config:r,user:null==e||null===(n=e.session)||void 0===n?void 0:n.user,authenticated:i,ssr_data:t,extra:null==e?void 0:e.extra}})(e,{hostname:null==t?void 0:t.hostname,port:null==t?void 0:t.port,catcher_url:null==t?void 0:t.catcher_url,login_url:null==o||null===(n=o.credentials)||void 0===n?void 0:n.url_login,logout_url:null==o||null===(l=o.credentials)||void 0===l?void 0:l.url_logout},yield a(e)),u=((e,t)=>{var o="";try{var n;null!=r&&null!==(n=r.ssr)&&void 0!==n&&n.renderer?o=Y(r.ssr.renderer(e,t)):e.miolo.logger.warn("Missing renderer in render.ssr middleware")}catch(a){e.miolo.logger.error("Error in renderer (render.ssr middleware):\n".concat(a.toString())),o="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return i.replace("{context}",JSON.stringify(t,null,2)).replace("{children}",o)})(e,c);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(u,"utf8")," bytes")),e.body=u}))).apply(this,arguments)}e.use((function(e){return l.apply(this,arguments)}))}function wr(e){return e?e/1e6:0}function Sr(e){return e?e/1e6:0}function xr(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(wr(V.freemem()),2),n=Math.round(wr(V.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[cron][".concat(s("SysCheck"),"] RAM ").concat(u(o)," MB used of ").concat(f(n)," MB (").concat(u(i)," %)")):t.info("[cron][".concat(s("SysCheck"),"] RAM ").concat(u(o)," MB used of ").concat(f(n)," MB (").concat(u(i)," %)")),Z.check("/",(function(e,r){var o=Math.round(Sr(r.used),2),n=Math.round(Sr(r.total),2),i=Math.round(Sr(r.free),2);i<1?t.error("[cron][".concat(s("SysCheck"),"] DISK ").concat(u(o)," GB used of ").concat(f(n)," GB (").concat(u(i)," GB free)")):t.info("[cron][".concat(s("SysCheck"),"] DISK ").concat(u(o)," GB used of ").concat(f(n)," GB (").concat(u(i)," GB free)"))}))},start:!0}}function kr(e,r){var t=e.context.miolo,o=t.logger,n=[xr(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{Ae(e.config.http.ratelimit.ipsum_folder||Fe,(r=>{e.logger.debug("[cron][".concat(s("IPsum"),"] File downloaded. ").concat(f(r.length)," ips will be ").concat(u("blacklisted"),"!"))}),e.logger)},start:!0},{name:"Emailer",cronTime:"* * * * *",onTick:(e,r)=>{e.emailer.queue_send_emails(e.logger)},start:!0},...r||[]],i=[];n.map((e=>{var r=e.name,o=function(e,r){var t,o=e.logger,n=null!=r&&null!==(t=r.onTick)&&void 0!==t&&t.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new Q((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{try{o.silly("[cron][Custom Job ".concat(s(i),"] ").concat(h("ticks!"))),r.onTick(e,t)}catch(n){o.error("[cron][Custom Job ".concat(s(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(o.silly("[cron][Custom Job ".concat(s(i),"] ").concat(h("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[cron][Custom Job ".concat(s(i),"] Error at onComplete()")),o.error(t)}}),!1,(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,isActive:!1})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||o.error("[cron] Job ".concat(s(e)," Not Found")),r},l=e=>{try{return e.job.start(),e.isActive=!0,o.debug("[cron][Job ".concat(s(e.name),"] ").concat(h("started!"))),1}catch(r){return o.error("[cron][Job ".concat(s(e.name),"] Error starting it")),o.error(r),0}},c=e=>{try{return e.job.stop(),e.isActive=!1,o.debug("[cron][Job ".concat(s(e.name),"] ").concat(g("stopped!"))),1}catch(r){return o.error("[cron][Job ".concat(s(e.name),"] Error stopping it")),o.error(r),0}};return e.cron={jobs:i,start_one:e=>{var r=a(e);return r?[l(r),r.name]:[0,""]},start:()=>{try{var e=[],r=[];i.map((t=>{1==l(t)?e.push(t.name):r.push(t.name)})),e.length>0&&o.info("[cron] Started ".concat(e.length," jobs: ").concat(e)),r.length>0&&o.warn("[cron] Could not start ".concat(r.length," jobs: ").concat(r))}catch(t){o.error("[cron] start() error: ".concat(t))}},stop_one:e=>{var r=a(e);return r?[c(r),r.name]:[0,""]},stop:()=>{try{var e=[],r=[];i.map((t=>{1==c(t)?e.push(t.name):r.push(t.name)})),e.length>0&&o.info("[cron] Stopped ".concat(e.length," jobs: ").concat(e)),r.length>0&&o.warn("[cron] Could not stop ".concat(r.length," jobs: ").concat(r))}catch(t){o.error("[cron] stop() error: ".concat(t))}}},e}function Or(e,r){var t,o=e.context.miolo.logger,n=function(){var t=ee((function*(){try{var t,n,i;if(null!=(null===(t=e.http)||void 0===t?void 0:t.server))return void o.warn("[http][start] Server already running on ".concat(null==e||null===(n=e.http)||void 0===n?void 0:n.hostname,":").concat(null==e||null===(i=e.http)||void 0===i?void 0:i.port));var a=P.createServer(e.callback()),l=$({server:a}),c=function(){var t=ee((function*(){try{yield l.terminate(),delete e.http.server,o.info("[http][stop] miolo has been shutdowned from ".concat(r.hostname,":").concat(r.port))}catch(t){o.error("[http][stop] error: ".concat(t))}}));return function(){return t.apply(this,arguments)}}();e.http.server=a,e.http.stop=c,yield((e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))})))(a,r.port,r.hostname),o.info("[http][start] miolo is listening on ".concat(r.hostname,":").concat(r.port))}catch(u){o.error("[http][start] error: ".concat(u))}}));return function(){return t.apply(this,arguments)}}();return e.http={server:void 0,start:n,stop:(t=ee((function*(){o.warn("[http] stop() stop() function still not attached. Is server running?")})),function(){return t.apply(this,arguments)}),hostname:r.hostname,port:r.port},e}function Er(t,o){var n,i,a,c=new e,v=function(e){var t,o=r(le,e);return o.auth_type=function(e){var r,t,o;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.credentials?"credentials":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.custom?"custom":"guest"}(e),o.use_catcher=!(null==o||null===(t=o.http)||void 0===t||!t.catcher_url),o}(t);Te(c,v),cr(c,v.http),(e=>{e.use(R({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:C.Z_SYNC_FLUSH},deflate:{flush:C.Z_SYNC_FLUSH},br:!1})),e.use(I(q({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(c),function(e){var r=e.context.miolo.logger;function t(){return(t=ee((function*(e){if(e){if(!(e instanceof Error)){var t=e;if("object"==typeof e)try{t=JSON.stringify(e)}catch(a){}var o=new Error("non-error thrown: "+t);e&&(e.name&&(o.name=e.name),e.message&&(o.message=e.message),e.stack&&(o.stack=e.stack),e.status&&(o.status=e.status),e.headers&&(o.headers=e.headers)),e=o}(this.headerSent||!this.writable)&&(e.headerSent=!0),this.app.emit("error",e,this),"ENOENT"===e.code&&(e.status=404);var n=e.status||400;this.accepts(["text","json","html"])?"number"==typeof e.status&&P.STATUS_CODES[e.status]||(e.status=500):(n=406,e.message="Unsupported type"),this.status=n;var i=this.headers["x-real-ip"]||this.headers["x-orig-ip"]||this.ip||"127.0.0.1";Je.indexOf(n)>=0?r.warn("[".concat(i,"] ").concat(this.method," ").concat(this.url," - ").concat(n,": ").concat(e.message)):r.error(e),e.headerSent?r.warn("headers were already sent, returning early"):(this.type="json",this.body=JSON.stringify(this.body||"",null,2),this.length=Buffer.byteLength(this.body),this.res.end(this.body))}}))).apply(this,arguments)}e.context.onerror=function(e){return t.apply(this,arguments)}}(c),function(e,r){var t=e.context.miolo,o=Ue(null==r?void 0:r.ipsum_folder,void 0,t.logger),n={driver:"memory",db:new Map,id:e=>e.request.ip,headers:{remaining:"Rate-Limit-Remaining",reset:"Rate-Limit-Reset",total:"Rate-Limit-Total"},disableHeader:!1,max:(null==r?void 0:r.max)||1e3,duration:(null==r?void 0:r.duration)||6e4,errorMessage:(null==r?void 0:r.errorMessage)||"Rate Limit reached",whitelist:(null==r?void 0:r.whitelist)||(e=>{var t=(null==r?void 0:r.whitelist_ips)||[];return!!t&&t.indexOf(e.request.ip)>=0}),blacklist:(null==r?void 0:r.blacklist)||(e=>{var t=e.request.ip,n=[...o,...ze,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(t)>=0;return n&&e.miolo.logger.debug("Rejecting ".concat(u("blacklisted")," ").concat(d(t))),n})};e.use(N(n))}(c,null===(n=v.http)||void 0===n?void 0:n.ratelimit),((e,r)=>{var{favicon:t,folders:o}=r,n=t||Ge;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(We,""))),e.use(M(n)),Object.entries(o)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(We,""))),e.use(J(i,F(a,{index:!1})))})(c,null===(i=v.http)||void 0===i?void 0:i.static),function(e,r){var t=function(){var e=ee((function*(e,r){return{}}));return function(r,t){return e.apply(this,arguments)}}(),o=function(){var e=ee((function*(e,r,t){}));return function(r,t,o){return e.apply(this,arguments)}}(),n={lazy:(null==r?void 0:r.lazy)||1,slow:(null==r?void 0:r.slow)||2,onStart:(null==r?void 0:r.onStart)||t,onDone:(null==r?void 0:r.onDone)||o,geoip:(null==r?void 0:r.geoip)||{enabled:!1}};function i(){return(i=ee((function*(e,r){var t,o,i,a,c,v,m=e.miolo.logger,h=(e=>{var r=[e.headers["x-real-ip"],e.headers["x-orig-ip"],e.ip,"127.0.0.1"];for(var t of r)if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(t))return t})(e),g=L.now();e.request.body=oe(oe({},e.request.fields),e.request.files),Qe.total+=1,Qe[h]=(Qe[h]||0)+1,e.requestId=Qe.total,e.request.ip=h;var y=!0===(null==n||null===(t=n.geoip)||void 0===t?void 0:t.enabled),b={};y&&(b=Ye(h,n.geoip,m)),e.request.geoip=b;var _=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,w=y?!0===(null===(o=b)||void 0===o?void 0:o.local)?"":null!==(i=b)&&void 0!==i&&i.country?null!==(a=b)&&void 0!==a&&a.city?" (".concat(null===(c=b)||void 0===c?void 0:c.city,", ").concat(b.country,")"):" (".concat(b.country,")"):"":"",S="".concat(d(h)).concat(w," ").concat(s(e.request.method)," ").concat(s(_)," [").concat(p(Qe[h]),"/").concat(p(e.requestId),"]"),x=null!=e.request.body?JSON.stringify(e.request.body):"";m.info("".concat(S," - START")),m.debug("".concat(S," - Body: ").concat(x));var k=yield n.onStart(e,{started:g,description:"pending"});yield r();var O=null==e||null===(v=e.session)||void 0===v?void 0:v.user,E="";null!=O&&(null!=O&&O.id?E=" - uid ".concat(null==O?void 0:O.id):null!=O&&O.token&&(E=" - token ".concat(null==O?void 0:O.token)));var j,q=e.response.status,I=q;200==q?j=f:q>200&&q<=299?(j=u,e.response.redirected&&e.response.url&&(I+=" -> ".concat(e.response.url))):j=l;var R="[".concat(j(I),"]"),C=parseFloat((L.now()-g)/1e3).toFixed(2),P=C<n.lazy?f:C<n.slow?u:l,N=C<n.lazy?"Ok":C<n.slow?"lazy":"slow",T=null!=e.session?JSON.stringify(e.session):"";m.debug("".concat(S," - Session: ").concat(T.slice(0,150),"...")),m.silly("".concat(S," - Session: ").concat(T));var J=null!=e.body?JSON.stringify(e.body):"";m.debug("".concat(S," - Response: ").concat(J.slice(0,150),"...")),m.silly("".concat(S," - Response: ").concat(J)),yield n.onDone(e,k,{started:g,elapsed:C,description:N}),m.info("".concat(S," - DONE ").concat(R).concat(E," (").concat(P(N),": ").concat(P(C),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(c,null==v||null===(a=v.http)||void 0===a?void 0:a.request),function(e){function r(){return(r=ee((function*(e){e.body=$e}))).apply(this,arguments)}var t=new U;t.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(t.routes())}(c),v.use_catcher&&function(e,r){function t(){return t=ee((function*(e){var{error:r,warning:t,path:o,agent:n}=e.request.body,i=e.miolo.logger;if(t){var a="".concat(u("[JS Warning]")," on ").concat(m(o),": ").concat(JSON.stringify(t.msg),"\n")+"".concat(u("[JS Warning]")," File => ").concat(t.file,"\n")+"".concat(u("[JS Warning]")," Line => ").concat(t.line,"\n")+"".concat(u("[JS Warning]")," Col => ").concat(t.col,"\n")+"".concat(u("[JS Warning]")," Error => ").concat(JSON.stringify(t.error),"\n")+"".concat(u("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var c="".concat(l("[JS Error]")," on ").concat(m(o),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(l("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(l("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(l("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(l("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(l("[JS Error]")," Agent => ").concat(n);i.error(c)}e.body={result:1}})),t.apply(this,arguments)}var o=new U;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(c,v.http.catcher_url),"guest"==v.auth_type&&Xe(c,v.auth.guest,null==v?void 0:v.session),"basic"==v.auth_type&&er(c,v.auth.basic),"credentials"==v.auth_type&&ar(c,v.auth.credentials,null==v?void 0:v.session,null==v?void 0:v.cache),"custom"==v.auth_type&&((e,r)=>{var t=e.context.miolo.logger;try{var o=r(e);if("function"==typeof o)e.use(o);else if(Array.isArray(o)){var n=new U;o.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){t.error("Custom auth error: ".concat(i,"'"))}})(c,v.auth.custom);var h=null==v?void 0:v.middlewares;return h&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(c,h),null!=v&&v.routes&&hr(c,v.routes),null!=(null==o?void 0:o.middleware)?c.use(o.middleware):_r(c,o,v.http,null==v?void 0:v.auth,null==v||v.socket),kr(c,null==v?void 0:v.cron),Or(c,null==v?void 0:v.http),c.start=ee((function*(){yield c.context.miolo.db.init_connection(),yield c.http.start(),c.cron.start()})),c.stop=ee((function*(){c.context.miolo.db.drop_connections(),yield c.http.stop(),c.cron.stop()})),c.restart=ee((function*(){yield c.stop(),yield c.start()})),c}export{Er as miolo,we as miolo_emailer,je as miolo_logger,Ie as miolo_parser};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v1.1.5
2
+ * miolo v1.1.6
3
3
  *
4
4
  * https://www.afialapis.com/os/miolo
5
5
  *
@@ -765,7 +765,7 @@ function _init_emailer_transporter(_ref) {
765
765
  send_email(email).then(res => {
766
766
  _logi(logger, "[emailer] Queued email [".concat(email.subject, "]sent ").concat(res.ok ? 'OK' : 'NOT OK'));
767
767
  if (res.ok) {
768
- delete email_queue_remove_ids(res.ids);
768
+ delete email_queue_remove_ids(email.ids);
769
769
  }
770
770
  });
771
771
  };