miolo 0.9.20 → 0.9.21
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.
- package/dist/cli/miolo.cli.iife.bundle.js +1 -1
- package/dist/cli/miolo.cli.iife.bundle.min.js +1 -1
- package/dist/cli/miolo.cli.iife.js +1 -1
- package/dist/cli/miolo.cli.iife.min.js +1 -1
- package/dist/cli/miolo.cli.min.mjs +1 -1
- package/dist/cli/miolo.cli.mjs +1 -1
- package/dist/cli/miolo.cli.umd.bundle.js +1 -1
- package/dist/cli/miolo.cli.umd.bundle.min.js +1 -1
- package/dist/cli/miolo.cli.umd.js +1 -1
- package/dist/cli/miolo.cli.umd.min.js +1 -1
- package/dist/cli-react/miolo.cli-react.iife.bundle.js +1 -1
- package/dist/cli-react/miolo.cli-react.iife.bundle.min.js +1 -1
- package/dist/cli-react/miolo.cli-react.iife.js +1 -1
- package/dist/cli-react/miolo.cli-react.iife.min.js +1 -1
- package/dist/cli-react/miolo.cli-react.min.mjs +1 -1
- package/dist/cli-react/miolo.cli-react.mjs +1 -1
- package/dist/cli-react/miolo.cli-react.umd.bundle.js +1 -1
- package/dist/cli-react/miolo.cli-react.umd.bundle.min.js +1 -1
- package/dist/cli-react/miolo.cli-react.umd.js +1 -1
- package/dist/cli-react/miolo.cli-react.umd.min.js +1 -1
- package/dist/server/miolo.server.cjs +77 -28
- package/dist/server/miolo.server.min.mjs +2 -2
- package/dist/server/miolo.server.mjs +47 -21
- package/dist/server/miolo.server.mjs.map +1 -1
- package/dist/server/miolo.server.node.mjs +78 -29
- package/package.json +1 -1
package/dist/cli/miolo.cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* miolo v0.9.
|
|
2
|
+
* miolo v0.9.21
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Donato Lorenzo <donato@afialapis.com>
|
|
5
5
|
*
|
|
@@ -446,8 +446,19 @@ var base_config = {
|
|
|
446
446
|
// - false
|
|
447
447
|
// - true enable koa-proxies and use default options
|
|
448
448
|
// - {options} enable koa-proxies and use the custom options
|
|
449
|
-
proxy: false
|
|
449
|
+
proxy: false,
|
|
450
|
+
request: {
|
|
451
|
+
lazy: 1,
|
|
452
|
+
// seconds to consider lazy a request
|
|
453
|
+
slow: 2,
|
|
454
|
+
// seconds to consider slow a request
|
|
455
|
+
onStart: undefined,
|
|
456
|
+
// (ctx, times) => { return begin_result}
|
|
457
|
+
onDone: undefined
|
|
458
|
+
// (ctx, begin_result, times) => {}
|
|
459
|
+
}
|
|
450
460
|
},
|
|
461
|
+
|
|
451
462
|
session: {
|
|
452
463
|
salt: 'SUPER_SALTY_YES?',
|
|
453
464
|
secret: 'SUPER_SECRET_KEY_KERE',
|
|
@@ -572,10 +583,6 @@ var base_config = {
|
|
|
572
583
|
name: 'miolo',
|
|
573
584
|
from: 'miolo@mail.com',
|
|
574
585
|
to: 'errors@mail.com'
|
|
575
|
-
},
|
|
576
|
-
request: {
|
|
577
|
-
lazy: 1,
|
|
578
|
-
slow: 2
|
|
579
586
|
}
|
|
580
587
|
},
|
|
581
588
|
mail: {
|
|
@@ -1134,20 +1141,52 @@ var REQUEST_COUNTER = {
|
|
|
1134
1141
|
* Middleware for feed and log the request
|
|
1135
1142
|
*/
|
|
1136
1143
|
|
|
1137
|
-
function init_request_middleware(app,
|
|
1138
|
-
var
|
|
1139
|
-
|
|
1140
|
-
|
|
1144
|
+
function init_request_middleware(app, config) {
|
|
1145
|
+
var _def_on_begin = /*#__PURE__*/function () {
|
|
1146
|
+
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(ctx, times) {
|
|
1147
|
+
return _regeneratorRuntime().wrap(function _callee$(_context) {
|
|
1148
|
+
while (1) switch (_context.prev = _context.next) {
|
|
1149
|
+
case 0:
|
|
1150
|
+
return _context.abrupt("return", {});
|
|
1151
|
+
case 1:
|
|
1152
|
+
case "end":
|
|
1153
|
+
return _context.stop();
|
|
1154
|
+
}
|
|
1155
|
+
}, _callee);
|
|
1156
|
+
}));
|
|
1157
|
+
return function _def_on_begin(_x, _x2) {
|
|
1158
|
+
return _ref.apply(this, arguments);
|
|
1159
|
+
};
|
|
1160
|
+
}();
|
|
1161
|
+
var _def_on_done = /*#__PURE__*/function () {
|
|
1162
|
+
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ctx, begin_result, times) {
|
|
1163
|
+
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
|
|
1164
|
+
while (1) switch (_context2.prev = _context2.next) {
|
|
1165
|
+
case 0:
|
|
1166
|
+
case "end":
|
|
1167
|
+
return _context2.stop();
|
|
1168
|
+
}
|
|
1169
|
+
}, _callee2);
|
|
1170
|
+
}));
|
|
1171
|
+
return function _def_on_done(_x3, _x4, _x5) {
|
|
1172
|
+
return _ref2.apply(this, arguments);
|
|
1173
|
+
};
|
|
1174
|
+
}();
|
|
1175
|
+
var reqConfig = {
|
|
1176
|
+
lazy: (config == null ? void 0 : config.lazy) || 1,
|
|
1177
|
+
slow: (config == null ? void 0 : config.slow) || 2,
|
|
1178
|
+
onStart: (config == null ? void 0 : config.onStart) || _def_on_begin,
|
|
1179
|
+
onDone: (config == null ? void 0 : config.onDone) || _def_on_done
|
|
1141
1180
|
};
|
|
1142
|
-
function request_middleware(
|
|
1181
|
+
function request_middleware(_x6, _x7) {
|
|
1143
1182
|
return _request_middleware.apply(this, arguments);
|
|
1144
1183
|
}
|
|
1145
1184
|
function _request_middleware() {
|
|
1146
|
-
_request_middleware = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function
|
|
1185
|
+
_request_middleware = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(ctx, next) {
|
|
1147
1186
|
var _ctx$session;
|
|
1148
|
-
var logger, ip, started, clurl, sreq, sbody, user, uid_desc, status, ststr, stcolor, stdesc, elapsed, tcolor, tname, ssession, rbody;
|
|
1149
|
-
return _regeneratorRuntime().wrap(function
|
|
1150
|
-
while (1) switch (
|
|
1187
|
+
var logger, ip, started, clurl, sreq, sbody, begin_result, user, uid_desc, status, ststr, stcolor, stdesc, elapsed, tcolor, tname, ssession, rbody;
|
|
1188
|
+
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
|
|
1189
|
+
while (1) switch (_context3.prev = _context3.next) {
|
|
1151
1190
|
case 0:
|
|
1152
1191
|
logger = ctx.miolo.logger;
|
|
1153
1192
|
ip = ctx.headers["x-real-ip"] || '127.0.0.1';
|
|
@@ -1168,9 +1207,16 @@ function init_request_middleware(app, logRequest) {
|
|
|
1168
1207
|
sbody = ctx.request.body != undefined ? JSON.stringify(ctx.request.body) : '';
|
|
1169
1208
|
logger.info(sreq + " - START");
|
|
1170
1209
|
logger.debug(sreq + " - Body: " + sbody);
|
|
1171
|
-
|
|
1172
|
-
return
|
|
1210
|
+
_context3.next = 15;
|
|
1211
|
+
return reqConfig.onStart(ctx, {
|
|
1212
|
+
started: started,
|
|
1213
|
+
description: 'pending'
|
|
1214
|
+
});
|
|
1173
1215
|
case 15:
|
|
1216
|
+
begin_result = _context3.sent;
|
|
1217
|
+
_context3.next = 18;
|
|
1218
|
+
return next();
|
|
1219
|
+
case 18:
|
|
1174
1220
|
user = ctx == null || (_ctx$session = ctx.session) == null ? void 0 : _ctx$session.user;
|
|
1175
1221
|
uid_desc = '';
|
|
1176
1222
|
if (user != undefined) {
|
|
@@ -1194,22 +1240,25 @@ function init_request_middleware(app, logRequest) {
|
|
|
1194
1240
|
}
|
|
1195
1241
|
stdesc = "[" + stcolor(ststr) + "]";
|
|
1196
1242
|
elapsed = parseFloat((node_perf_hooks.performance.now() - started) / 1000.0).toFixed(2);
|
|
1197
|
-
tcolor = elapsed <
|
|
1198
|
-
tname = elapsed <
|
|
1199
|
-
ctx.request.times = {
|
|
1200
|
-
elapsed: elapsed,
|
|
1201
|
-
desciprion: tname
|
|
1202
|
-
};
|
|
1243
|
+
tcolor = elapsed < reqConfig.lazy ? tinguir.green : elapsed < reqConfig.slow ? tinguir.yellow : tinguir.red;
|
|
1244
|
+
tname = elapsed < reqConfig.lazy ? 'Ok' : elapsed < reqConfig.slow ? 'lazy' : 'slow';
|
|
1203
1245
|
ssession = ctx.session != undefined ? JSON.stringify(ctx.session) : '';
|
|
1204
1246
|
logger.debug(sreq + " - Session: " + ssession);
|
|
1205
1247
|
rbody = ctx.body != undefined ? JSON.stringify(ctx.body) : '';
|
|
1206
1248
|
logger.debug(sreq + " - Response: " + rbody);
|
|
1249
|
+
_context3.next = 34;
|
|
1250
|
+
return reqConfig.onDone(ctx, begin_result, {
|
|
1251
|
+
started: started,
|
|
1252
|
+
elapsed: elapsed,
|
|
1253
|
+
description: tname
|
|
1254
|
+
});
|
|
1255
|
+
case 34:
|
|
1207
1256
|
logger.info(sreq + " - DONE " + stdesc + uid_desc + " (" + tcolor(tname) + ": " + tcolor(elapsed) + ")");
|
|
1208
|
-
case
|
|
1257
|
+
case 35:
|
|
1209
1258
|
case "end":
|
|
1210
|
-
return
|
|
1259
|
+
return _context3.stop();
|
|
1211
1260
|
}
|
|
1212
|
-
},
|
|
1261
|
+
}, _callee3);
|
|
1213
1262
|
}));
|
|
1214
1263
|
return _request_middleware.apply(this, arguments);
|
|
1215
1264
|
}
|
|
@@ -2901,7 +2950,7 @@ function init_cron(app, custom) {
|
|
|
2901
2950
|
}
|
|
2902
2951
|
|
|
2903
2952
|
function miolo(sconfig, render) {
|
|
2904
|
-
var _config$http, _config$
|
|
2953
|
+
var _config$http, _config$http2;
|
|
2905
2954
|
var app = new Koa();
|
|
2906
2955
|
|
|
2907
2956
|
// Init some pieces
|
|
@@ -2923,7 +2972,7 @@ function miolo(sconfig, render) {
|
|
|
2923
2972
|
init_static_middleware(app, (_config$http = config.http) == null ? void 0 : _config$http["static"]);
|
|
2924
2973
|
|
|
2925
2974
|
// Feed and log request
|
|
2926
|
-
init_request_middleware(app, config == null || (_config$
|
|
2975
|
+
init_request_middleware(app, config == null || (_config$http2 = config.http) == null ? void 0 : _config$http2.request);
|
|
2927
2976
|
|
|
2928
2977
|
// attach the default robots.txt
|
|
2929
2978
|
init_route_robots(app);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* miolo v0.9.
|
|
2
|
+
* miolo v0.9.21
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Donato Lorenzo <donato@afialapis.com>
|
|
5
5
|
*
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import e from"node:http";import r from"koa";import{createHttpTerminator as t}from"http-terminator";import o from"deepmerge";import n from"node:path";import{fileURLToPath as i}from"node:url";import{getConnection as a}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import l from"nodemailer";import{uncolor as u,gray as c,magenta as s,cyan as d,yellow as f,red_light as p,red as m,cyan_light as v,green as h,blue as y,green_bold as g,yellow_bold as b}from"tinguir";import S,{promisify as E}from"node:util";import _,{transports as x,createLogger as w,format as k}from"winston";import R from"koa-better-body";import O from"koa-convert";import q from"koa-compress";import{constants as C}from"node:zlib";import M from"koa-mount";import j from"koa-static";import J from"koa-favicon";import{performance as T}from"node:perf_hooks";import A from"@koa/router";import{readFileSync as U}from"node:fs";import L from"jwt-simple";import N from"koa-passport";import P from"passport-local";import z from"koa-session";import F from"koa-redis";import V from"@koa/cors";import B from"koa-proxies";import I from"qs";import{renderToString as D}from"react-dom/server";import{CronJob as G}from"cron";import W from"node:os";import Y from"diskspace";import K from"redis";function H(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 X(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?H(Object(t),!0).forEach((function(r){$(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):H(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function Z(e,r,t,o,n,i,a){try{var l=e[i](a),u=l.value}catch(c){return void t(c)}l.done?r(u):Promise.resolve(u).then(o,n)}function Q(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){Z(i,o,n,a,l,"next",e)}function l(e){Z(i,o,n,a,l,"throw",e)}a(void 0)}))}}function $(e,r,t){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var o=t.call(e,r||"default");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:String(r)}(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var ee=i(import.meta.url),re=n.dirname(ee),te={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:n.resolve(re,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:864e5,secure:!0,sameSite:null}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{log:"silly",tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0,level:"silly"},file:{enabled:!0,level:"silly",filename:"/var/log/miolo.log"},mail:{enabled:!1,level:"warn",name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"},request:{lazy:1,slow:2}},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:[]};function oe(e){var{options:r,defaults:t,silent:o}=e,n=l.createTransport(r,t);function i(){return(i=Q((function*(e){if(!0===o)return console.info("*********************************"),console.info("This mail will not be send (emailing is disabled):"),console.info(e),console.info("*********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var r=n.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(t){return{error:t,ok:!1}}}))).apply(this,arguments)}var a={send:function(e){return i.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),n.verify((function(e,r){e?(console.error("[miolo][Verify][MAILER] Verifying ERROR"),console.error(e)):console.info("[miolo][Verify][MAILER] Verifyed OK: Server is ready to take our messages")}))},options:r,defaults:t,silent:o};return a}var{combine:ne,timestamp:ie,_label:ae,printf:le,errors:ue}=k,ce=function(e,r){var t,o,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",i={silly:c,debug:s,verbose:d,info:f,warn:p,error:m},a={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},l=le((r=>{var t,o=i[r.level],l=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),u="[".concat(n,"] ").concat(o(l)," ").concat(o(a[r.level])," ").concat(r.message);return r.stack?"".concat(u,"\n").concat(r.stack):u})),v=[];e.console.enabled&&v.push(new x.Console({humanReadableUnhandledException:!0,level:(null==e||null===(t=e.console)||void 0===t?void 0:t.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));e.file.enabled&&v.push(new x.File({filename:e.file.filename,level:(null==e||null===(o=e.file)||void 0===o?void 0:o.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0}));if(e.mail.enabled){var h=function(e,r){var t=function(t){_.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 S.inherits(t,_.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n=this,i="";try{i=t.message.split("\n")[0]}catch(c){i=t.message.toString()}i=u(i);var a=e.name+": ["+t.level.toUpperCase()+"] "+i,l={from:this.from,to:this.to,subject:a,text:u(t.message)};r.send(l,(function(){n.emit("logged"),o(null,!0)}))},t}(e.mail,r);x.MailerLogger=h,v.push(new x.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return w({level:(null==e?void 0:e.level)||"silly",format:ne(ue({stack:!0}),ie(),l),transports:v})},se=(e,r)=>{var t=oe(r.mail),o=ce(r.log,t,null==r?void 0:r.name),n=X(X({},r.db.options),{},{log:o}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},l={config:X({},r),emailer:t,logger:o,db:i};function u(){return(u=Q((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return u.apply(this,arguments)})),e.context.miolo=l},de=[401];var fe=i(import.meta.url),pe=n.dirname(fe),me=n.resolve(pe,"./miolo.ico"),ve=n.resolve(pe,"../../../.."),he={total:0};var ye=i(import.meta.url),ge=n.dirname(ye),be=U(n.resolve(ge,"./robots.txt"),"utf8");var Se=(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 L.encode(n,o)}(t||{},o)};function i(){return i=Q((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)}))},Ee=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=Q((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(u){}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(M(r,i))))},_e=new F;var xe=(e,r,t)=>r(null,e.id),we=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},ke=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},Re=(e,r,t)=>{var{get_user_id:o,find_user_by_id:n,local_auth_user:i,url_login:a,url_logout:l,url_login_redirect:u,url_logout_redirect:c}=r,s=o||xe,d=n||we,f=i||ke,p=a||"/login",m=l||"/logout",v=new P.Strategy(((r,t,o)=>{f(r,t,o,e.context.miolo)}));function h(){return(h=Q((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(t){}yield r()}))).apply(this,arguments)}!function(e,r){e.keys=[r.secret||"*secret*"];var t=X({store:_e},r.options||{});e.use(z(t,e))}(e,t),N.serializeUser(((r,t)=>{process.nextTick((function(){s(r,t,e.context.miolo)}))})),N.deserializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),N.use(v),e.use(N.initialize()),e.use(N.session()),e.use((function(e,r){return h.apply(this,arguments)}));var y=function(){var e=Q((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!=c&&e.redirect(c)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,t){return e.apply(this,arguments)}}(),g=new A;g.post(p,((e,r)=>N.authenticate("local",function(){var r=Q((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))),g.get(m,y),g.post(m,y),e.use(g.routes())},Oe=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},qe=(e,r)=>{var t=e.context.miolo.logger;Oe(r,"cors",(r=>{if("simple"==r)t.debug("Setting CORS the simple way"),e.use(function(){var e=Q((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("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("Setting CORS headers for ".concat(JSON.stringify(o))),e.use(V(o))}})),Oe(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("Setting Proxy for ".concat(o," to ").concat(n.target," ")),e.use(B(o,n))}))},Ce=function(){var e=Q((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Me=function(){var e=Q((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),je={require:!1,action:"redirect",redirect_url:"/",error_code:401},Je={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},Te=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.bodyField)||(null==e?void 0:e.bodyField),a=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ce,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Me,u=o(je,(null==e?void 0:e.auth)||{},(null==r?void 0:r.auth)||{}),c=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var f={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:o(Je,(null==d?void 0:d.useUserFields)||{}),auth:o(u,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};c.push(f)}}c.length>0&&t.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),t};function Ae(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?I.parse(r):{}}function Ue(e,r,t,o){t.map((t=>{var n=t.prefix;t.routes.map((t=>{var i=e.getModel(t.name);if(i){for(var a=function(){var e=Q((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=t.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(o.error("[miolo-router] Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(o.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(o.error("[miolo-router] Crud path ".concat(t.url," specified auth but no action")),e.body={})),i)}));return function(r,t){return e.apply(this,arguments)}}(),l=function(){var e=Q((function*(e,r,n){var i,l={};try{var u;if(!(yield a(e,r)))return void(e.body={});var c=!0;if(null!=t&&t.before&&(c=yield t.before(e)),!c)return void(e.body={});var s=null==e||null===(u=e.session)||void 0===u||null===(u=u.user)||void 0===u?void 0:u.id,d={};!0===t.useUserFields.use&&(d=t.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield n(f),null!=t&&t.after&&(l=yield t.after(e,l))}catch(p){o.error("[miolo-router] Unexpected error on CRUD ".concat(t.name,"-").concat(r)),o.error(p)}i=l,l=null==t.bodyField?i:{[t.bodyField]:i},e.body=l}));return function(r,t,o){return e.apply(this,arguments)}}(),u=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.read(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.keyList(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.find(t.id,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.distinct(t.distinct_field,t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=Q((function*(e){yield l(e,"w",function(){var r=Q((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.created_by&&(o[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(o,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=function(){var e=Q((function*(e){yield l(e,"w",function(){var r=Q((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.last_update_by&&(o[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(o,{id:o.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=function(){var e=Q((function*(e){yield l(e,"w",function(){var r=Q((function*(r){var t=e.request.fields,o={transaction:void 0};return yield i.delete({id:t.id},o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=n?"/".concat(n,"/").concat(t.url):"/".concat(t.url);v.indexOf("//")>=0;)v=v.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(t.name," to ").concat(v));var h=t.mode.indexOf("r")>=0,y=t.mode.indexOf("w")>=0,g=t.mode.indexOf("u")>=0||y;h&&(r.get("".concat(v,"/find"),(e=>s(e))),r.get("".concat(v,"/read"),(e=>u(e))),r.get("".concat(v,"/distinct"),(e=>d(e))),r.get("".concat(v,"/key_list"),(e=>c(e)))),g&&(r.post("".concat(v,"/save"),(e=>f(e))),r.post("".concat(v,"/update"),(e=>p(e)))),y&&r.post("".concat(v,"/delete"),(e=>m(e)))}else o.error("[miolo-router] Could not get model for ".concat(t.name))}))}))}var Le=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ce,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Me,l=o(je,(null==r?void 0:r.auth)||{},(null==e?void 0:e.auth)||{}),u=[];for(var c of n)if(c.url&&c.callback){var s={url:c.url,method:(null==c?void 0:c.method)||"GET",callback:c.callback,auth:o(l,(null==c?void 0:c.auth)||{}),before:(null==c?void 0:c.before)||i,after:(null==c?void 0:c.after)||a};u.push(s)}t.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),t};function Ne(e,r,t){var o=e.context.miolo.logger,n=new A;try{var i=Te(t),a=Le(t),l=i.length>0,u=a.length>0;if(!l&&!u)throw"[miolo-router] Could not get any route from the passed <routes> param";l&&Ue(r,n,i,o),u&&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,"/");t.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i));var a=function(){var e=Q((function*(e){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&&"POST"===r.method)||(n||("error"==i.action?(t.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(t.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(t.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=Q((function*(e){var o={};try{try{var n;if("GET"==r.method&&(null===(n=e.request)||void 0===n||!n.fields)&&e.request.url.indexOf("?")>0){var i=Ae(e.request.url);i&&(e.request.fields=i)}}catch(u){t.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield a(e)))return;var l=!0;if(null!=r&&r.before&&(l=yield r.before(e)),!l)return;o=yield r.callback(e),null!=r&&r.after&&(o=yield r.after(e,o))}catch(c){t.error("[miolo-router] Unexpected error on Query ".concat(r.name)),t.error(c)}return o}));return function(r){return e.apply(this,arguments)}}(),u=r.method.toLowerCase();e[u](i,(e=>l(e,r)))}))}))}(n,a,o)}catch(c){o.error(c),o.error("[miolo-router] Error initing the router. Probably config objects are not ok"),o.error("[miolo-router] connOrConfig:"),o.error(null==r?void 0:r.config),o.error("[miolo-router] routes:"),o.error(t)}e.use(n.routes())}var Pe=i(import.meta.url),ze=n.dirname(Pe),Fe=U(n.resolve(ze,"fallback_index.html"),"utf8");function Ve(e){return e?e/1e6:0}function Be(e){return e?e/1e6:0}function Ie(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(Ve(W.freemem()),2),n=Math.round(Ve(W.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")):t.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")),Y.check("/",(function(e,r){var o=Math.round(Be(r.used),2),n=Math.round(Be(r.total),2),i=Math.round(Be(r.free),2);i<1?t.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)")):t.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function De(e,r){var t=e.context.miolo,o=t.logger,n=[Ie(),...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 G((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{try{o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,t)}catch(n){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),o.error(t)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,running:!0===(null==e?void 0:e.start)})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||o.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),o.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(g("manually started!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),o.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function Ge(n,i){var a,l,u=new r,c=function(e){var r,t=o(te,e);return t.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),t.use_catcher=!(null==t||null===(r=t.http)||void 0===r||!r.catcher_url),t}(n);se(u,c),qe(u,c.http),(e=>{e.use(q({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(O(R({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(u),function(e){var r=e.context.miolo.logger;function t(){return(t=Q((function*(e){if(e){var t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),de.indexOf(t)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(t,": ").concat(e.message)):r.error(e),this.headerSent||!this.writable)return r.debug("headers were already sent, returning early"),void(e.headerSent=!0);this.type="json",this.status=t,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)}}(u),((e,r)=>{var{favicon:t,folders:o}=r,n=t||me;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(ve,""))),e.use(J(n)),Object.entries(o)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(ve,""))),e.use(M(i,j(a,{index:!1})))})(u,null===(a=c.http)||void 0===a?void 0:a.static),function(e,r){var t={lazy:(null==r?void 0:r.lazy)||1,slow:(null==r?void 0:r.slow)||2};function o(){return(o=Q((function*(e,r){var o,n=e.miolo.logger,i=e.headers["x-real-ip"]||"127.0.0.1",a=T.now();e.request.body=X(X({},e.request.fields),e.request.files),he.total+=1,he[i]=(he[i]||0)+1,e.requestId=he.total,e.request.ip=i;var l=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,u="".concat(s(i)," ").concat(d(e.request.method)," ").concat(d(l)," [").concat(v(he[i]),"/").concat(v(e.requestId),"]"),c=null!=e.request.body?JSON.stringify(e.request.body):"";n.info("".concat(u," - START")),n.debug("".concat(u," - Body: ").concat(c)),yield r();var p=null==e||null===(o=e.session)||void 0===o?void 0:o.user,y="";null!=p&&(null!=p&&p.id?y=" - uid ".concat(null==p?void 0:p.id):null!=p&&p.token&&(y=" - token ".concat(null==p?void 0:p.token)));var g,b=e.response.status,S=b;200==b?g=h:b>200&&b<=299?(g=f,e.response.redirected&&e.response.url&&(S+=" -> ".concat(e.response.url))):g=m;var E="[".concat(g(S),"]"),_=parseFloat((T.now()-a)/1e3).toFixed(2),x=_<t.lazy?h:_<t.slow?f:m,w=_<t.lazy?"Ok":_<t.slow?"lazy":"slow";e.request.times={elapsed:_,desciprion:w};var k=null!=e.session?JSON.stringify(e.session):"";n.debug("".concat(u," - Session: ").concat(k));var R=null!=e.body?JSON.stringify(e.body):"";n.debug("".concat(u," - Response: ").concat(R)),n.info("".concat(u," - DONE ").concat(E).concat(y," (").concat(x(w),": ").concat(x(_),")"))}))).apply(this,arguments)}e.use((function(e,r){return o.apply(this,arguments)}))}(u,null==c||null===(l=c.log)||void 0===l?void 0:l.request),function(e){function r(){return(r=Q((function*(e){e.body=be}))).apply(this,arguments)}var t=new A;t.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(t.routes())}(u),c.use_catcher&&function(e,r){function t(){return t=Q((function*(e){var{error:r,warning:t,path:o,agent:n}=e.request.body,i=e.miolo.logger;if(t){var a="".concat(f("[JS Warning]")," on ").concat(y(o),": ").concat(t.msg,"\n")+"".concat(f("[JS Warning]")," File => ").concat(t.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(t.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(t.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(t.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(m("[JS Error]")," on ").concat(y(o),": ").concat(r.msg,"\n")+"".concat(m("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(m("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(m("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(m("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(m("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),t.apply(this,arguments)}var o=new A;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(u,c.http.catcher_url),"guest"==c.auth_type&&Se(u,c.auth.guest,null==c?void 0:c.session),"basic"==c.auth_type&&Ee(u,c.auth.basic),"credentials"==c.auth_type&&Re(u,c.auth.credentials,null==c?void 0:c.session),"custom"==c.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 A;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,"'"))}})(u,c.auth.custom);var p=null==c?void 0:c.middlewares;if(p&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(u,p),null!=c&&c.routes){var g=u.context.miolo.db.getConnection();Ne(u,g,c.routes)}null!=(null==i?void 0:i.middleware)?u.use(i.middleware):function(e,r,t,o){var n=(null==r?void 0:r.html)||Fe;n.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),n.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var i=function(){var e=Q((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(u){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!=u&&u.stack?"".concat(u.toString(),"\n").concat(u.stack):u.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)}}(),a=(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}},l=(e,t)=>{var o="";try{var i;null!=r&&null!==(i=r.ssr)&&void 0!==i&&i.renderer?o=D(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)"),e.miolo.logger.error(a),o="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(t,null,2)).replace("{children}",o)};function u(){return(u=Q((function*(e){var r,n,u={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===(r=o.credentials)||void 0===r?void 0:r.url_login,logout_url:null==o||null===(n=o.credentials)||void 0===n?void 0:n.url_logout},c=yield i(e),s=a(e,u,c),d=l(e,s);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(d,"utf8")," bytes")),e.body=d}))).apply(this,arguments)}e.use((function(e){return u.apply(this,arguments)}))}(u,i,c.http,null==c?void 0:c.auth);var b=function(){var r=Q((function*(){var r=e.createServer(u.callback());yield((e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))})))(r,c.http.port,c.http.hostname),u.context.miolo.logger.info("miolo is listening on ".concat(c.http.hostname,":").concat(c.http.port)),u.server=r;var o=t({server:r});return u.stop_server=Q((function*(){yield o.terminate(),u.context.miolo.logger.info("miolo has been shutdowned from ".concat(c.http.hostname,":").concat(c.http.port))})),De(u,null==c?void 0:c.cron),u}));return function(){return r.apply(this,arguments)}}();return u.run=b,u}function We(e){var r=K.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(s("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof K.ReplyError?"".concat(s("REDIS")," ").concat(m("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(s("REDIS")," ").concat(m("Error "+e.code)," ").concat(e.toString())}catch(t){r="".concat(s("REDIS")," ").concat(m("Error ")," ").concat(t)}console.error(r)})),t=E(r.get).bind(r),o=E(r.exists).bind(r),n=E(r.set).bind(r),i=E(r.del).bind(r);function a(){return(a=Q((function*(e){return yield t(e)}))).apply(this,arguments)}function l(){return(l=Q((function*(e){return 1==(yield o(e))}))).apply(this,arguments)}function u(){return u=Q((function*(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:86400;return"OK"==(yield n(e,r,"EX",t))})),u.apply(this,arguments)}function c(){return(c=Q((function*(e){return(yield i(e))>=1}))).apply(this,arguments)}var d={get:function(e){return a.apply(this,arguments)},exists:function(e){return l.apply(this,arguments)},set:function(e,r){return u.apply(this,arguments)},del:function(e){return c.apply(this,arguments)}};return d}export{Ge as miolo,We as miolo_cacher,oe as miolo_emailer,ce as miolo_logger};
|
|
11
|
+
import e from"node:http";import r from"koa";import{createHttpTerminator as t}from"http-terminator";import o from"deepmerge";import n from"node:path";import{fileURLToPath as i}from"node:url";import{getConnection as a}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import l from"nodemailer";import{uncolor as u,gray as c,magenta as s,cyan as d,yellow as f,red_light as p,red as v,cyan_light as m,green as h,blue as y,green_bold as g,yellow_bold as b}from"tinguir";import S,{promisify as E}from"node:util";import _,{transports as x,createLogger as w,format as k}from"winston";import R from"koa-better-body";import O from"koa-convert";import q from"koa-compress";import{constants as C}from"node:zlib";import M from"koa-mount";import j from"koa-static";import J from"koa-favicon";import{performance as T}from"node:perf_hooks";import A from"@koa/router";import{readFileSync as U}from"node:fs";import L from"jwt-simple";import N from"koa-passport";import P from"passport-local";import z from"koa-session";import F from"koa-redis";import V from"@koa/cors";import D from"koa-proxies";import B from"qs";import{renderToString as I}from"react-dom/server";import{CronJob as G}from"cron";import W from"node:os";import Y from"diskspace";import K from"redis";function H(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 X(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?H(Object(t),!0).forEach((function(r){$(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):H(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function Z(e,r,t,o,n,i,a){try{var l=e[i](a),u=l.value}catch(c){return void t(c)}l.done?r(u):Promise.resolve(u).then(o,n)}function Q(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){Z(i,o,n,a,l,"next",e)}function l(e){Z(i,o,n,a,l,"throw",e)}a(void 0)}))}}function $(e,r,t){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var o=t.call(e,r||"default");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:String(r)}(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var ee=i(import.meta.url),re=n.dirname(ee),te={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:n.resolve(re,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,request:{lazy:1,slow:2,onStart:void 0,onDone:void 0}},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:864e5,secure:!0,sameSite:null}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{log:"silly",tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0,level:"silly"},file:{enabled:!0,level:"silly",filename:"/var/log/miolo.log"},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:[]};function oe(e){var{options:r,defaults:t,silent:o}=e,n=l.createTransport(r,t);function i(){return(i=Q((function*(e){if(!0===o)return console.info("*********************************"),console.info("This mail will not be send (emailing is disabled):"),console.info(e),console.info("*********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var r=n.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(t){return{error:t,ok:!1}}}))).apply(this,arguments)}var a={send:function(e){return i.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),n.verify((function(e,r){e?(console.error("[miolo][Verify][MAILER] Verifying ERROR"),console.error(e)):console.info("[miolo][Verify][MAILER] Verifyed OK: Server is ready to take our messages")}))},options:r,defaults:t,silent:o};return a}var{combine:ne,timestamp:ie,_label:ae,printf:le,errors:ue}=k,ce=function(e,r){var t,o,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",i={silly:c,debug:s,verbose:d,info:f,warn:p,error:v},a={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},l=le((r=>{var t,o=i[r.level],l=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),u="[".concat(n,"] ").concat(o(l)," ").concat(o(a[r.level])," ").concat(r.message);return r.stack?"".concat(u,"\n").concat(r.stack):u})),m=[];e.console.enabled&&m.push(new x.Console({humanReadableUnhandledException:!0,level:(null==e||null===(t=e.console)||void 0===t?void 0:t.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));e.file.enabled&&m.push(new x.File({filename:e.file.filename,level:(null==e||null===(o=e.file)||void 0===o?void 0:o.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0}));if(e.mail.enabled){var h=function(e,r){var t=function(t){_.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 S.inherits(t,_.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n=this,i="";try{i=t.message.split("\n")[0]}catch(c){i=t.message.toString()}i=u(i);var a=e.name+": ["+t.level.toUpperCase()+"] "+i,l={from:this.from,to:this.to,subject:a,text:u(t.message)};r.send(l,(function(){n.emit("logged"),o(null,!0)}))},t}(e.mail,r);x.MailerLogger=h,m.push(new x.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return w({level:(null==e?void 0:e.level)||"silly",format:ne(ue({stack:!0}),ie(),l),transports:m})},se=(e,r)=>{var t=oe(r.mail),o=ce(r.log,t,null==r?void 0:r.name),n=X(X({},r.db.options),{},{log:o}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},l={config:X({},r),emailer:t,logger:o,db:i};function u(){return(u=Q((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return u.apply(this,arguments)})),e.context.miolo=l},de=[401];var fe=i(import.meta.url),pe=n.dirname(fe),ve=n.resolve(pe,"./miolo.ico"),me=n.resolve(pe,"../../../.."),he={total:0};var ye=i(import.meta.url),ge=n.dirname(ye),be=U(n.resolve(ge,"./robots.txt"),"utf8");var Se=(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 L.encode(n,o)}(t||{},o)};function i(){return i=Q((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)}))},Ee=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=Q((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(u){}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(M(r,i))))},_e=new F;var xe=(e,r,t)=>r(null,e.id),we=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},ke=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},Re=(e,r,t)=>{var{get_user_id:o,find_user_by_id:n,local_auth_user:i,url_login:a,url_logout:l,url_login_redirect:u,url_logout_redirect:c}=r,s=o||xe,d=n||we,f=i||ke,p=a||"/login",v=l||"/logout",m=new P.Strategy(((r,t,o)=>{f(r,t,o,e.context.miolo)}));function h(){return(h=Q((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(t){}yield r()}))).apply(this,arguments)}!function(e,r){e.keys=[r.secret||"*secret*"];var t=X({store:_e},r.options||{});e.use(z(t,e))}(e,t),N.serializeUser(((r,t)=>{process.nextTick((function(){s(r,t,e.context.miolo)}))})),N.deserializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),N.use(m),e.use(N.initialize()),e.use(N.session()),e.use((function(e,r){return h.apply(this,arguments)}));var y=function(){var e=Q((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!=c&&e.redirect(c)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,t){return e.apply(this,arguments)}}(),g=new A;g.post(p,((e,r)=>N.authenticate("local",function(){var r=Q((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))),g.get(v,y),g.post(v,y),e.use(g.routes())},Oe=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},qe=(e,r)=>{var t=e.context.miolo.logger;Oe(r,"cors",(r=>{if("simple"==r)t.debug("Setting CORS the simple way"),e.use(function(){var e=Q((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("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("Setting CORS headers for ".concat(JSON.stringify(o))),e.use(V(o))}})),Oe(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("Setting Proxy for ".concat(o," to ").concat(n.target," ")),e.use(D(o,n))}))},Ce=function(){var e=Q((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Me=function(){var e=Q((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),je={require:!1,action:"redirect",redirect_url:"/",error_code:401},Je={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},Te=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.bodyField)||(null==e?void 0:e.bodyField),a=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ce,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Me,u=o(je,(null==e?void 0:e.auth)||{},(null==r?void 0:r.auth)||{}),c=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var f={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:o(Je,(null==d?void 0:d.useUserFields)||{}),auth:o(u,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};c.push(f)}}c.length>0&&t.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),t};function Ae(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?B.parse(r):{}}function Ue(e,r,t,o){t.map((t=>{var n=t.prefix;t.routes.map((t=>{var i=e.getModel(t.name);if(i){for(var a=function(){var e=Q((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=t.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(o.error("[miolo-router] Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(o.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(o.error("[miolo-router] Crud path ".concat(t.url," specified auth but no action")),e.body={})),i)}));return function(r,t){return e.apply(this,arguments)}}(),l=function(){var e=Q((function*(e,r,n){var i,l={};try{var u;if(!(yield a(e,r)))return void(e.body={});var c=!0;if(null!=t&&t.before&&(c=yield t.before(e)),!c)return void(e.body={});var s=null==e||null===(u=e.session)||void 0===u||null===(u=u.user)||void 0===u?void 0:u.id,d={};!0===t.useUserFields.use&&(d=t.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield n(f),null!=t&&t.after&&(l=yield t.after(e,l))}catch(p){o.error("[miolo-router] Unexpected error on CRUD ".concat(t.name,"-").concat(r)),o.error(p)}i=l,l=null==t.bodyField?i:{[t.bodyField]:i},e.body=l}));return function(r,t,o){return e.apply(this,arguments)}}(),u=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.read(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.keyList(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.find(t.id,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=Q((function*(e){yield l(e,"r",function(){var r=Q((function*(r){var t=Ae(e.request.url),o={transaction:void 0};return yield i.distinct(t.distinct_field,t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=Q((function*(e){yield l(e,"w",function(){var r=Q((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.created_by&&(o[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(o,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=function(){var e=Q((function*(e){yield l(e,"w",function(){var r=Q((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.last_update_by&&(o[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(o,{id:o.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=function(){var e=Q((function*(e){yield l(e,"w",function(){var r=Q((function*(r){var t=e.request.fields,o={transaction:void 0};return yield i.delete({id:t.id},o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=n?"/".concat(n,"/").concat(t.url):"/".concat(t.url);m.indexOf("//")>=0;)m=m.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(t.name," to ").concat(m));var h=t.mode.indexOf("r")>=0,y=t.mode.indexOf("w")>=0,g=t.mode.indexOf("u")>=0||y;h&&(r.get("".concat(m,"/find"),(e=>s(e))),r.get("".concat(m,"/read"),(e=>u(e))),r.get("".concat(m,"/distinct"),(e=>d(e))),r.get("".concat(m,"/key_list"),(e=>c(e)))),g&&(r.post("".concat(m,"/save"),(e=>f(e))),r.post("".concat(m,"/update"),(e=>p(e)))),y&&r.post("".concat(m,"/delete"),(e=>v(e)))}else o.error("[miolo-router] Could not get model for ".concat(t.name))}))}))}var Le=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ce,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Me,l=o(je,(null==r?void 0:r.auth)||{},(null==e?void 0:e.auth)||{}),u=[];for(var c of n)if(c.url&&c.callback){var s={url:c.url,method:(null==c?void 0:c.method)||"GET",callback:c.callback,auth:o(l,(null==c?void 0:c.auth)||{}),before:(null==c?void 0:c.before)||i,after:(null==c?void 0:c.after)||a};u.push(s)}t.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),t};function Ne(e,r,t){var o=e.context.miolo.logger,n=new A;try{var i=Te(t),a=Le(t),l=i.length>0,u=a.length>0;if(!l&&!u)throw"[miolo-router] Could not get any route from the passed <routes> param";l&&Ue(r,n,i,o),u&&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,"/");t.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i));var a=function(){var e=Q((function*(e){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&&"POST"===r.method)||(n||("error"==i.action?(t.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(t.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(t.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=Q((function*(e){var o={};try{try{var n;if("GET"==r.method&&(null===(n=e.request)||void 0===n||!n.fields)&&e.request.url.indexOf("?")>0){var i=Ae(e.request.url);i&&(e.request.fields=i)}}catch(u){t.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield a(e)))return;var l=!0;if(null!=r&&r.before&&(l=yield r.before(e)),!l)return;o=yield r.callback(e),null!=r&&r.after&&(o=yield r.after(e,o))}catch(c){t.error("[miolo-router] Unexpected error on Query ".concat(r.name)),t.error(c)}return o}));return function(r){return e.apply(this,arguments)}}(),u=r.method.toLowerCase();e[u](i,(e=>l(e,r)))}))}))}(n,a,o)}catch(c){o.error(c),o.error("[miolo-router] Error initing the router. Probably config objects are not ok"),o.error("[miolo-router] connOrConfig:"),o.error(null==r?void 0:r.config),o.error("[miolo-router] routes:"),o.error(t)}e.use(n.routes())}var Pe=i(import.meta.url),ze=n.dirname(Pe),Fe=U(n.resolve(ze,"fallback_index.html"),"utf8");function Ve(e){return e?e/1e6:0}function De(e){return e?e/1e6:0}function Be(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(Ve(W.freemem()),2),n=Math.round(Ve(W.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")):t.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")),Y.check("/",(function(e,r){var o=Math.round(De(r.used),2),n=Math.round(De(r.total),2),i=Math.round(De(r.free),2);i<1?t.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)")):t.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function Ie(e,r){var t=e.context.miolo,o=t.logger,n=[Be(),...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 G((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{try{o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,t)}catch(n){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),o.error(t)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,running:!0===(null==e?void 0:e.start)})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||o.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),o.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(g("manually started!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),o.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function Ge(n,i){var a,l,u=new r,c=function(e){var r,t=o(te,e);return t.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),t.use_catcher=!(null==t||null===(r=t.http)||void 0===r||!r.catcher_url),t}(n);se(u,c),qe(u,c.http),(e=>{e.use(q({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(O(R({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(u),function(e){var r=e.context.miolo.logger;function t(){return(t=Q((function*(e){if(e){var t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),de.indexOf(t)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(t,": ").concat(e.message)):r.error(e),this.headerSent||!this.writable)return r.debug("headers were already sent, returning early"),void(e.headerSent=!0);this.type="json",this.status=t,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)}}(u),((e,r)=>{var{favicon:t,folders:o}=r,n=t||ve;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(me,""))),e.use(J(n)),Object.entries(o)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(me,""))),e.use(M(i,j(a,{index:!1})))})(u,null===(a=c.http)||void 0===a?void 0:a.static),function(e,r){var t=function(){var e=Q((function*(e,r){return{}}));return function(r,t){return e.apply(this,arguments)}}(),o=function(){var e=Q((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};function i(){return(i=Q((function*(e,r){var t,o=e.miolo.logger,i=e.headers["x-real-ip"]||"127.0.0.1",a=T.now();e.request.body=X(X({},e.request.fields),e.request.files),he.total+=1,he[i]=(he[i]||0)+1,e.requestId=he.total,e.request.ip=i;var l=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,u="".concat(s(i)," ").concat(d(e.request.method)," ").concat(d(l)," [").concat(m(he[i]),"/").concat(m(e.requestId),"]"),c=null!=e.request.body?JSON.stringify(e.request.body):"";o.info("".concat(u," - START")),o.debug("".concat(u," - Body: ").concat(c));var p=yield n.onStart(e,{started:a,description:"pending"});yield r();var y=null==e||null===(t=e.session)||void 0===t?void 0:t.user,g="";null!=y&&(null!=y&&y.id?g=" - uid ".concat(null==y?void 0:y.id):null!=y&&y.token&&(g=" - token ".concat(null==y?void 0:y.token)));var b,S=e.response.status,E=S;200==S?b=h:S>200&&S<=299?(b=f,e.response.redirected&&e.response.url&&(E+=" -> ".concat(e.response.url))):b=v;var _="[".concat(b(E),"]"),x=parseFloat((T.now()-a)/1e3).toFixed(2),w=x<n.lazy?h:x<n.slow?f:v,k=x<n.lazy?"Ok":x<n.slow?"lazy":"slow",R=null!=e.session?JSON.stringify(e.session):"";o.debug("".concat(u," - Session: ").concat(R));var O=null!=e.body?JSON.stringify(e.body):"";o.debug("".concat(u," - Response: ").concat(O)),yield n.onDone(e,p,{started:a,elapsed:x,description:k}),o.info("".concat(u," - DONE ").concat(_).concat(g," (").concat(w(k),": ").concat(w(x),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(u,null==c||null===(l=c.http)||void 0===l?void 0:l.request),function(e){function r(){return(r=Q((function*(e){e.body=be}))).apply(this,arguments)}var t=new A;t.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(t.routes())}(u),c.use_catcher&&function(e,r){function t(){return t=Q((function*(e){var{error:r,warning:t,path:o,agent:n}=e.request.body,i=e.miolo.logger;if(t){var a="".concat(f("[JS Warning]")," on ").concat(y(o),": ").concat(t.msg,"\n")+"".concat(f("[JS Warning]")," File => ").concat(t.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(t.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(t.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(t.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(v("[JS Error]")," on ").concat(y(o),": ").concat(r.msg,"\n")+"".concat(v("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(v("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(v("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(v("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(v("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),t.apply(this,arguments)}var o=new A;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(u,c.http.catcher_url),"guest"==c.auth_type&&Se(u,c.auth.guest,null==c?void 0:c.session),"basic"==c.auth_type&&Ee(u,c.auth.basic),"credentials"==c.auth_type&&Re(u,c.auth.credentials,null==c?void 0:c.session),"custom"==c.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 A;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,"'"))}})(u,c.auth.custom);var p=null==c?void 0:c.middlewares;if(p&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(u,p),null!=c&&c.routes){var g=u.context.miolo.db.getConnection();Ne(u,g,c.routes)}null!=(null==i?void 0:i.middleware)?u.use(i.middleware):function(e,r,t,o){var n=(null==r?void 0:r.html)||Fe;n.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),n.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var i=function(){var e=Q((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(u){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!=u&&u.stack?"".concat(u.toString(),"\n").concat(u.stack):u.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)}}(),a=(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}},l=(e,t)=>{var o="";try{var i;null!=r&&null!==(i=r.ssr)&&void 0!==i&&i.renderer?o=I(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)"),e.miolo.logger.error(a),o="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(t,null,2)).replace("{children}",o)};function u(){return(u=Q((function*(e){var r,n,u={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===(r=o.credentials)||void 0===r?void 0:r.url_login,logout_url:null==o||null===(n=o.credentials)||void 0===n?void 0:n.url_logout},c=yield i(e),s=a(e,u,c),d=l(e,s);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(d,"utf8")," bytes")),e.body=d}))).apply(this,arguments)}e.use((function(e){return u.apply(this,arguments)}))}(u,i,c.http,null==c?void 0:c.auth);var b=function(){var r=Q((function*(){var r=e.createServer(u.callback());yield((e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))})))(r,c.http.port,c.http.hostname),u.context.miolo.logger.info("miolo is listening on ".concat(c.http.hostname,":").concat(c.http.port)),u.server=r;var o=t({server:r});return u.stop_server=Q((function*(){yield o.terminate(),u.context.miolo.logger.info("miolo has been shutdowned from ".concat(c.http.hostname,":").concat(c.http.port))})),Ie(u,null==c?void 0:c.cron),u}));return function(){return r.apply(this,arguments)}}();return u.run=b,u}function We(e){var r=K.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(s("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof K.ReplyError?"".concat(s("REDIS")," ").concat(v("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(s("REDIS")," ").concat(v("Error "+e.code)," ").concat(e.toString())}catch(t){r="".concat(s("REDIS")," ").concat(v("Error ")," ").concat(t)}console.error(r)})),t=E(r.get).bind(r),o=E(r.exists).bind(r),n=E(r.set).bind(r),i=E(r.del).bind(r);function a(){return(a=Q((function*(e){return yield t(e)}))).apply(this,arguments)}function l(){return(l=Q((function*(e){return 1==(yield o(e))}))).apply(this,arguments)}function u(){return u=Q((function*(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:86400;return"OK"==(yield n(e,r,"EX",t))})),u.apply(this,arguments)}function c(){return(c=Q((function*(e){return(yield i(e))>=1}))).apply(this,arguments)}var d={get:function(e){return a.apply(this,arguments)},exists:function(e){return l.apply(this,arguments)},set:function(e,r){return u.apply(this,arguments)},del:function(e){return c.apply(this,arguments)}};return d}export{Ge as miolo,We as miolo_cacher,oe as miolo_emailer,ce as miolo_logger};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* miolo v0.9.
|
|
2
|
+
* miolo v0.9.21
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Donato Lorenzo <donato@afialapis.com>
|
|
5
5
|
*
|
|
@@ -148,8 +148,19 @@ var base_config = {
|
|
|
148
148
|
// - false
|
|
149
149
|
// - true enable koa-proxies and use default options
|
|
150
150
|
// - {options} enable koa-proxies and use the custom options
|
|
151
|
-
proxy: false
|
|
151
|
+
proxy: false,
|
|
152
|
+
request: {
|
|
153
|
+
lazy: 1,
|
|
154
|
+
// seconds to consider lazy a request
|
|
155
|
+
slow: 2,
|
|
156
|
+
// seconds to consider slow a request
|
|
157
|
+
onStart: undefined,
|
|
158
|
+
// (ctx, times) => { return begin_result}
|
|
159
|
+
onDone: undefined
|
|
160
|
+
// (ctx, begin_result, times) => {}
|
|
161
|
+
}
|
|
152
162
|
},
|
|
163
|
+
|
|
153
164
|
session: {
|
|
154
165
|
salt: 'SUPER_SALTY_YES?',
|
|
155
166
|
secret: 'SUPER_SECRET_KEY_KERE',
|
|
@@ -274,10 +285,6 @@ var base_config = {
|
|
|
274
285
|
name: 'miolo',
|
|
275
286
|
from: 'miolo@mail.com',
|
|
276
287
|
to: 'errors@mail.com'
|
|
277
|
-
},
|
|
278
|
-
request: {
|
|
279
|
-
lazy: 1,
|
|
280
|
-
slow: 2
|
|
281
288
|
}
|
|
282
289
|
},
|
|
283
290
|
mail: {
|
|
@@ -801,12 +808,28 @@ var REQUEST_COUNTER = {
|
|
|
801
808
|
* Middleware for feed and log the request
|
|
802
809
|
*/
|
|
803
810
|
|
|
804
|
-
function init_request_middleware(app,
|
|
805
|
-
var
|
|
806
|
-
|
|
807
|
-
|
|
811
|
+
function init_request_middleware(app, config) {
|
|
812
|
+
var _def_on_begin = /*#__PURE__*/function () {
|
|
813
|
+
var _ref = _asyncToGenerator(function* (ctx, times) {
|
|
814
|
+
return {};
|
|
815
|
+
});
|
|
816
|
+
return function _def_on_begin(_x, _x2) {
|
|
817
|
+
return _ref.apply(this, arguments);
|
|
818
|
+
};
|
|
819
|
+
}();
|
|
820
|
+
var _def_on_done = /*#__PURE__*/function () {
|
|
821
|
+
var _ref2 = _asyncToGenerator(function* (ctx, begin_result, times) {});
|
|
822
|
+
return function _def_on_done(_x3, _x4, _x5) {
|
|
823
|
+
return _ref2.apply(this, arguments);
|
|
824
|
+
};
|
|
825
|
+
}();
|
|
826
|
+
var reqConfig = {
|
|
827
|
+
lazy: (config === null || config === void 0 ? void 0 : config.lazy) || 1,
|
|
828
|
+
slow: (config === null || config === void 0 ? void 0 : config.slow) || 2,
|
|
829
|
+
onStart: (config === null || config === void 0 ? void 0 : config.onStart) || _def_on_begin,
|
|
830
|
+
onDone: (config === null || config === void 0 ? void 0 : config.onDone) || _def_on_done
|
|
808
831
|
};
|
|
809
|
-
function request_middleware(
|
|
832
|
+
function request_middleware(_x6, _x7) {
|
|
810
833
|
return _request_middleware.apply(this, arguments);
|
|
811
834
|
}
|
|
812
835
|
function _request_middleware() {
|
|
@@ -833,6 +856,10 @@ function init_request_middleware(app, logRequest) {
|
|
|
833
856
|
var sbody = ctx.request.body != undefined ? JSON.stringify(ctx.request.body) : '';
|
|
834
857
|
logger.info("".concat(sreq, " - START"));
|
|
835
858
|
logger.debug("".concat(sreq, " - Body: ").concat(sbody));
|
|
859
|
+
var begin_result = yield reqConfig.onStart(ctx, {
|
|
860
|
+
started,
|
|
861
|
+
description: 'pending'
|
|
862
|
+
});
|
|
836
863
|
yield next();
|
|
837
864
|
var user = ctx === null || ctx === void 0 || (_ctx$session = ctx.session) === null || _ctx$session === void 0 ? void 0 : _ctx$session.user;
|
|
838
865
|
var uid_desc = '';
|
|
@@ -858,18 +885,17 @@ function init_request_middleware(app, logRequest) {
|
|
|
858
885
|
}
|
|
859
886
|
var stdesc = "[".concat(stcolor(ststr), "]");
|
|
860
887
|
var elapsed = parseFloat((performance.now() - started) / 1000.0).toFixed(2);
|
|
861
|
-
var tcolor = elapsed <
|
|
862
|
-
var tname = elapsed <
|
|
863
|
-
|
|
864
|
-
// Attach some info to request
|
|
865
|
-
ctx.request.times = {
|
|
866
|
-
elapsed,
|
|
867
|
-
desciprion: tname
|
|
868
|
-
};
|
|
888
|
+
var tcolor = elapsed < reqConfig.lazy ? green : elapsed < reqConfig.slow ? yellow : red;
|
|
889
|
+
var tname = elapsed < reqConfig.lazy ? 'Ok' : elapsed < reqConfig.slow ? 'lazy' : 'slow';
|
|
869
890
|
var ssession = ctx.session != undefined ? JSON.stringify(ctx.session) : '';
|
|
870
891
|
logger.debug("".concat(sreq, " - Session: ").concat(ssession));
|
|
871
892
|
var rbody = ctx.body != undefined ? JSON.stringify(ctx.body) : '';
|
|
872
893
|
logger.debug("".concat(sreq, " - Response: ").concat(rbody));
|
|
894
|
+
yield reqConfig.onDone(ctx, begin_result, {
|
|
895
|
+
started,
|
|
896
|
+
elapsed,
|
|
897
|
+
description: tname
|
|
898
|
+
});
|
|
873
899
|
logger.info("".concat(sreq, " - DONE ").concat(stdesc).concat(uid_desc, " (").concat(tcolor(tname), ": ").concat(tcolor(elapsed), ")"));
|
|
874
900
|
});
|
|
875
901
|
return _request_middleware.apply(this, arguments);
|
|
@@ -2163,7 +2189,7 @@ function init_cron(app, custom) {
|
|
|
2163
2189
|
}
|
|
2164
2190
|
|
|
2165
2191
|
function miolo(sconfig, render) {
|
|
2166
|
-
var _config$http, _config$
|
|
2192
|
+
var _config$http, _config$http2;
|
|
2167
2193
|
var app = new Koa();
|
|
2168
2194
|
|
|
2169
2195
|
// Init some pieces
|
|
@@ -2185,7 +2211,7 @@ function miolo(sconfig, render) {
|
|
|
2185
2211
|
init_static_middleware(app, (_config$http = config.http) === null || _config$http === void 0 ? void 0 : _config$http.static);
|
|
2186
2212
|
|
|
2187
2213
|
// Feed and log request
|
|
2188
|
-
init_request_middleware(app, config === null || config === void 0 || (_config$
|
|
2214
|
+
init_request_middleware(app, config === null || config === void 0 || (_config$http2 = config.http) === null || _config$http2 === void 0 ? void 0 : _config$http2.request);
|
|
2189
2215
|
|
|
2190
2216
|
// attach the default robots.txt
|
|
2191
2217
|
init_route_robots(app);
|