@jwn-js/common 2.3.9 → 2.3.11

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.
Files changed (62) hide show
  1. package/Memcached.d.ts +0 -44
  2. package/Memcached.js +1 -1
  3. package/Memcached.mjs +1 -1
  4. package/docs/classes/ApiError.html +2 -2
  5. package/docs/classes/AsyncJwt.html +2 -2
  6. package/docs/classes/Controller.html +2 -2
  7. package/docs/classes/Jwt.html +2 -2
  8. package/docs/classes/Memcached.html +2 -19
  9. package/docs/classes/Model.html +2 -2
  10. package/docs/classes/Server.html +2 -2
  11. package/docs/classes/Ssr.html +2 -8
  12. package/docs/classes/Web.html +2 -2
  13. package/docs/functions/action.html +1 -1
  14. package/docs/functions/allow.html +1 -1
  15. package/docs/functions/body.html +1 -1
  16. package/docs/functions/codeToStatus.html +1 -1
  17. package/docs/functions/config-1.html +1 -1
  18. package/docs/functions/connection.html +1 -1
  19. package/docs/functions/context.html +1 -1
  20. package/docs/functions/controller-1.html +1 -1
  21. package/docs/functions/cookies.html +1 -1
  22. package/docs/functions/db.html +1 -1
  23. package/docs/functions/headers.html +1 -1
  24. package/docs/functions/home.html +1 -1
  25. package/docs/functions/hostname.html +1 -1
  26. package/docs/functions/http.html +1 -1
  27. package/docs/functions/init.html +1 -1
  28. package/docs/functions/json.html +1 -1
  29. package/docs/functions/logerror.html +1 -1
  30. package/docs/functions/method.html +1 -1
  31. package/docs/functions/mixin.html +1 -1
  32. package/docs/functions/mount.html +1 -1
  33. package/docs/functions/pool.html +1 -1
  34. package/docs/functions/protocol.html +1 -1
  35. package/docs/functions/request.html +1 -1
  36. package/docs/functions/selectControllersSchema.html +1 -1
  37. package/docs/functions/stream.html +1 -1
  38. package/docs/functions/subaction.html +1 -1
  39. package/docs/functions/url.html +1 -1
  40. package/docs/functions/xml.html +1 -1
  41. package/docs/index.html +2 -2
  42. package/docs/interfaces/ApiErrorMessage.html +2 -2
  43. package/docs/interfaces/Config.html +2 -2
  44. package/docs/interfaces/ContextSsr.html +2 -2
  45. package/docs/interfaces/ContextWeb.html +2 -2
  46. package/docs/interfaces/OptionsSsr.html +2 -2
  47. package/docs/interfaces/OptionsWeb.html +2 -2
  48. package/docs/interfaces/ResponseOptions.html +2 -2
  49. package/docs/interfaces/Route.html +2 -2
  50. package/docs/interfaces/Schema.html +2 -2
  51. package/docs/interfaces/ServerHandler.html +2 -2
  52. package/docs/interfaces/ServerOptions.html +2 -2
  53. package/docs/interfaces/ServerWebsocket.html +2 -2
  54. package/docs/modules.html +2 -2
  55. package/docs/types/ServerRoutes.html +1 -1
  56. package/docs/variables/helpers.html +2 -2
  57. package/index.d.ts +1 -58
  58. package/index.js +3 -3
  59. package/index.mjs +3 -3
  60. package/package.json +1 -1
  61. package/staticBody.js +1 -1
  62. package/staticBody.mjs +1 -1
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var u=require("./ApiError.js"),y=require("./Server.js"),g=require("./Jwt-CDdbxwvH.js"),R=require("crypto"),z=require("util"),v=require("./Memcached.js"),P=require("./jsonBody.js"),S=require("stream"),B=require("./urlencodedBody.js"),M=require("./multipartBody.js"),G=require("./readConfig.js"),Y=require("./readConfigSync.js"),W=require("./cookieParse.js"),N=require("./cookieString.js"),x=require("./staticBody.js"),Z=require("fs"),D=require("path"),A=require("easy-ash"),ee=require("querystring"),O=require("xml-js"),te=require("os");require("reflect-metadata"),require("dns"),require("uWebSockets.js"),require("formidable");function j(o){var t=Object.create(null);return o&&Object.keys(o).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return o[e]}})}}),t.default=o,Object.freeze(t)}var J=j(Z),se=j(D),oe=j(te);const{subtle:T}=R.webcrypto;class ne{constructor(t,e){this.algorithm="SHA-256",this.secret=t,this.algorithm=e?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(t){if(!t)return!1;const e=t.split(".");return await this.signString(`${e[0]}.${e[1]}`)===e[2]}async sign(t){const e=g.toBase64url({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=g.toBase64url(t),n=await this.signString(`${e}.${s}`);return`${e}.${s}.${n}`}decode(t){const e=(t||"").split("."),s=g.fromBase64url(e[0]),n=g.fromBase64url(e[1]);return{head:s,body:n}}async signString(t){const e=new z.TextEncoder,s=await T.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return g.urlEncode(Buffer.from(await T.sign("HMAC",s,e.encode(t))).toString("base64"))}}const ie=o=>{const t=(o||"").split("."),e=g.fromBase64url(t[0]),s=g.fromBase64url(t[1]);return{head:e,body:s}},k=o=>new Promise((t,e)=>{re(o,s=>t(s),()=>{e(new u.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function re(o,t,e){let s=Buffer.from([]);o.onData((n,i)=>{s=Buffer.concat([s,Buffer.from(n)]),i&&t(s)}),o.onAborted(e)}const C=(o,t,e=!0)=>{o.onAborted(()=>new u.ApiError({message:"Connection aborted",code:1,statusCode:404}));const s=new S.PassThrough;return s.headers={},t.forEach((n,i)=>s.headers[n]=i),o.onData((n,i)=>{s.write(Buffer.from(Buffer.from(n))),e&&s.resume(),i&&s.end()}),s},ae=(o,t={})=>{for(const e of o){const s=se.resolve(e);Object.assign(t,JSON.parse(J.readFileSync(s).toString()))}return t};class ce{constructor(t,e,s,n){this.res=t,this.req=e,this.context=s,this.entry=n}async request(t={}){this.res.onAborted(()=>console.log("Abort is SSR handler"));const e=this.req.getQuery(),s=this.req.getUrl()+(e?`?${e}`:""),n=x.getExt(s);if(x.extensions.includes(n)){await x.staticBody(this.res,this.req,"./dist/client");return}const i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:W.cookieParse(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((c,m)=>i.headers[c]=m);const a=`${i.protocol}://${i.hostname}${i.url}`;let r,h=null;this.context.memcached&&(h=await this.context.memcached.getPage(a)),h?(r=h.data.toString(),i.headers=h.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,i.headers,r,i.memcache)),this.res.cork(()=>{this.res.writeStatus(y.codeToStatus(i.statusCode)),Object.keys(i.headers).map(c=>this.res.writeHeader(c,i.headers[c])),this.res.end(r)})}}const he=async(o,t,e)=>(await o.poolQuery({sql:`
1
+ "use strict";var u=require("./ApiError.js"),b=require("./Server.js"),_=require("./Jwt-CDdbxwvH.js"),R=require("crypto"),z=require("util"),v=require("./Memcached.js"),P=require("./jsonBody.js"),A=require("stream"),B=require("./urlencodedBody.js"),M=require("./multipartBody.js"),G=require("./readConfig.js"),Y=require("./readConfigSync.js"),W=require("./cookieParse.js"),N=require("./cookieString.js"),x=require("./staticBody.js"),Z=require("fs"),D=require("path"),$=require("easy-ash"),ee=require("querystring"),O=require("xml-js"),te=require("os");require("reflect-metadata"),require("dns"),require("uWebSockets.js"),require("formidable");function j(o){var t=Object.create(null);return o&&Object.keys(o).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return o[e]}})}}),t.default=o,Object.freeze(t)}var J=j(Z),se=j(D),oe=j(te);const{subtle:T}=R.webcrypto;class ne{constructor(t,e){this.algorithm="SHA-256",this.secret=t,this.algorithm=e?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(t){if(!t)return!1;const e=t.split(".");return await this.signString(`${e[0]}.${e[1]}`)===e[2]}async sign(t){const e=_.toBase64url({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=_.toBase64url(t),n=await this.signString(`${e}.${s}`);return`${e}.${s}.${n}`}decode(t){const e=(t||"").split("."),s=_.fromBase64url(e[0]),n=_.fromBase64url(e[1]);return{head:s,body:n}}async signString(t){const e=new z.TextEncoder,s=await T.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return _.urlEncode(Buffer.from(await T.sign("HMAC",s,e.encode(t))).toString("base64"))}}const ie=o=>{const t=(o||"").split("."),e=_.fromBase64url(t[0]),s=_.fromBase64url(t[1]);return{head:e,body:s}},k=o=>new Promise((t,e)=>{re(o,s=>t(s),()=>{e(new u.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function re(o,t,e){let s=Buffer.from([]);o.onData((n,i)=>{s=Buffer.concat([s,Buffer.from(n)]),i&&t(s)}),o.onAborted(e)}const C=(o,t,e=!0)=>{o.onAborted(()=>new u.ApiError({message:"Connection aborted",code:1,statusCode:404}));const s=new A.PassThrough;return s.headers={},t.forEach((n,i)=>s.headers[n]=i),o.onData((n,i)=>{s.write(Buffer.from(Buffer.from(n))),e&&s.resume(),i&&s.end()}),s},ae=(o,t={})=>{for(const e of o){const s=se.resolve(e);Object.assign(t,JSON.parse(J.readFileSync(s).toString()))}return t};class ce{constructor(t,e,s,n){this.res=t,this.req=e,this.context=s,this.entry=n}async request(t={}){this.res.onAborted(()=>console.log("Abort is SSR handler"));const e=this.req.getQuery(),s=this.req.getUrl()+(e?`?${e}`:""),n=x.getExt(s);if(x.extensions.includes(n)){await x.staticBody(this.res,this.req,"./dist/client");return}const i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:W.cookieParse(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((a,r)=>i.headers[a]=r);try{const a=`${i.protocol}://${i.hostname}${i.url}`;let r,c=null;this.context.memcached&&(c=await this.context.memcached.getPage(a)),c?(r=c.data.toString(),i.responseHeaders=c.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,i.headers,r,i.memcache)),this.res.cork(()=>{this.res.writeStatus(b.codeToStatus(i.statusCode)),Object.keys(i.responseHeaders).map(h=>this.res.writeHeader(h,i.responseHeaders[h])),this.res.end(r)})}catch(a){let r=b.codeToStatus(404),c=Object.assign({},i.responseHeaders||{}),h=a.message;a instanceof u.ApiError&&(r=b.codeToStatus(a.getStatusCode()),c=Object.assign(c,a.getHeaders()||{}),h=$.isObject(a.getData())&&Object.keys(a.getData()).length>0?JSON.stringify(a.getData()):h),this.res.cork(()=>{this.res.writeStatus(r),Object.keys(c).map(l=>this.res.writeHeader(l,c[l])),this.res.end(h)})}}}const he=async(o,t,e)=>(await o.poolQuery({sql:`
2
2
  SELECT c.id AS controller_id,
3
3
  c.name AS controller_name,
4
4
  c.is_active AS controller_is_active,
@@ -35,7 +35,7 @@
35
35
  FROM app_controllers c
36
36
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
37
37
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
38
- `)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),de=async(o,t,e,s,n="",i=3600)=>{const a=`${n}::routes::controllers`,r=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await ue(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),i),(c||{}).hasOwnProperty(r)?c[r]:void 0}},L=async(o,t,e,s,n,i="",a=3600)=>{let r;if(n&&n.isClient()&&n.isConnectedServers()?r=await de(o,e,s,n,i,a):r=await he(o,e,s),!r)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new u.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!h.includes(t))throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},le=async o=>{const t={},e={};return(await o.poolQuery(`
38
+ `)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),de=async(o,t,e,s,n="",i=3600)=>{const a=`${n}::routes::controllers`,r=`${t}::${e}`,c=await s.getValue(a);if(c){const h=JSON.parse(c.toString());return(h||{}).hasOwnProperty(r)?h[r]:void 0}else{const h=await ue(o);return await s.setValue(a,Buffer.from(JSON.stringify(h)),i),(h||{}).hasOwnProperty(r)?h[r]:void 0}},L=async(o,t,e,s,n,i="",a=3600)=>{let r;if(n&&n.isClient()&&n.isConnectedServers()?r=await de(o,e,s,n,i,a):r=await he(o,e,s),!r)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const c=(r?.action_method||"").split(",").map(h=>h.trim());if(r.controller_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!r.action_id)throw new u.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!c.includes(t))throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},le=async o=>{const t={},e={};return(await o.poolQuery(`
39
39
  SELECT c.id AS controller_id,
40
40
  c.name AS controller_name,
41
41
  c.is_active AS controller_is_active,
@@ -54,4 +54,4 @@
54
54
  FROM app_controllers c
55
55
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
56
56
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
57
- `)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},q=(o,t,e,s)=>{let n=o.controllers.find(h=>h.name===e);if(!n)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(n=Object.assign({isActive:!0,isSitemap:!1},n),!n.isActive)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let i=n.subactions.find(h=>h.name===s);if(!i)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(i=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},i),!i.isActive)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===i.action);if(!a)throw new u.ApiError({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new u.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:n.id,name:n.name,isActive:n.isActive,isSitemap:n.isSitemap},subaction:{id:i.id,name:i.name,isPermission:i.isPermission,isCheckMethod:i.isCheckMethod,isLog:i.isLog,isActive:i.isActive,isSync:!!i.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class me{constructor(t,e,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=t,this.req=e,this.res.onAborted(()=>new u.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,t,ee.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},schema:this.context.schema,routes:this.context.routes,getRequest:()=>n},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,m)=>this.contextWeb.headers[c]=m);const i=this.contextWeb.headers["content-type"]||"application/json";if(n.controller&&n.subaction&&this.context.schema&&(this.route=this.findRoute(n.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,q(this.context.schema,this.contextWeb.method,this.route.name,n.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)});const c=this.importControllerSync(n.controller),m=new c;if(this.injectContext(m),n.subaction in m)e=await m[n.subaction]();else throw new u.ApiError({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof v.Memcached){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const m=await c.getPage(this.memcachedKey);if(m){const{data:b,headers:w}=m;this.success({body:b.toString(),headers:w,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(i.indexOf("application/json")!==-1||i.indexOf("text/json")!==-1)Object.assign(n,await P.jsonBody(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:n.files});else if(i.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await B.urlencodedBody(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),m=O.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,m||{})}else i.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):i.indexOf("binary")!==-1?await new Promise(c=>{const m=C(this.res,this.req),b=oe.tmpdir(),w="./body_"+R.randomBytes(32).toString("hex"),_=D.resolve(b,w),d=J.createWriteStream(_);m.pipe(d),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:_}}}),m.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await L(this.contextWeb.db.home,this.contextWeb.method,this.route.name,n.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route});const a=await this.importController(n.controller),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(n.subaction in r)e=await r[n.subaction]();else throw new u.ApiError({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importController(t){let e=this.route.component.default||this.route.component;if(A.isClass(e)||(e=(await this.route.component()).default),typeof e!="function")throw new u.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}importControllerSync(t){const e=this.route.component.default||this.route.component;if(typeof e!="function")throw new u.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new u.ApiError({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const n=await t[s]();if(n)return n}}success(t){const e=t.body instanceof S.Stream,s=t.body instanceof Uint8Array,n=t.statusCode||200,i=y.codeToStatus(n),a=!s&&!e&&A.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&n===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof v.Memcached&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof u.ApiError&&t.getData()instanceof S.Stream;let s=y.codeToStatus(404),n=this.defaultResponse.headers,i=t.message;if(t instanceof u.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=y.codeToStatus(t.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?i=t.getData():i=A.isObject(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),i.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),this.res.end(i)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(e,n)):this.res.writeHeader(e,s)})}}const I={compact:!0,ignoreComment:!0,spaces:4};class E{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return N.cookieString(t,e,s)}success(t={},e){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,data:t},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,n=e.message?e.message:"Api request error",i=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:O.js2xml(Object.assign(s,{body:{...n.body}}),I),memcache:n.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:O.js2xml(Object.assign(s,{body:{...n.body}}),I),statusCode:n.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new S.PassThrough().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class U{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}const fe=async(o,t,e={},s)=>{const n=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const m=await r[c]();if(m)return m}},i=(r,h)=>{"$inject"in r&&r.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await L(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?q(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof E)return i(a,t),t.$initResponse=await n(a),a;if(a instanceof U){const r=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return i(r,t),t.$initResponse=await n(r),r.getModel()}else throw new u.ApiError({message:"Class should be an instance of Controller or Model",statusCode:400})},f=Symbol("arguments"),F=Symbol("connections"),H=Symbol("response"),K=Symbol("init"),Q=Symbol("logger"),V=Symbol("filters"),pe=o=>o.charAt(0).toUpperCase()+o.slice(1);function be(o){const t=(s,n)=>{for(const a of Reflect.ownKeys(n))Object.defineProperty(s.prototype,a,{value:n[a]});const i=Object.getPrototypeOf(n);i&&t(s,i)};function e(s){return t(s,o),s}return e}const l=(o,t,e,s,n,i)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,t,e)};function ge(){return function(o,t,e){l(f,o,t,e,"request")}}function _e(){return function(o,t,e){l(f,o,t,e,"context")}}function ye(){return function(o,t,e){l(f,o,t,e,"config")}}function xe(){return function(o,t,e){l(f,o,t,e,"method")}}function we(){return function(o,t,e){l(f,o,t,e,"cookies")}}function $e(){return function(o,t,e){l(f,o,t,e,"hostname")}}function Se(){return function(o,t,e){l(f,o,t,e,"url")}}function Ae(){return function(o,t,e){l(f,o,t,e,"protocol")}}function Ce(){return function(o,t,e){l(f,o,t,e,"db")}}function ve(){return function(o,t,e){l(f,o,t,e,"headers")}}function Oe(){return function(o,t,e){l(f,o,t,e,"controller")}}function je(){return function(o,t,e){l(f,o,t,e,"action")}}function ke(){return function(o,t,e){l(f,o,t,e,"subaction")}}function qe(){return function(o,t,e){l(f,o,t,e,"body")}}function Ee(){return function(o,t,e){l(f,o,t,e,"stream")}}function He(){return function(o,t,e){l(f,o,t,e,"home")}}function Re(o="home"){return function(t,e,s){l(f,t,e,s,"pool",o)}}function Pe(o="home"){return function(t,e,s){l(F,t,e,s,"connection",o)}}function Be(o={}){return function(t,e,s){l(H,t,e,0,"json",o)}}function Me(o={}){return function(t,e,s){l(H,t,e,0,"xml",o)}}function We(o){return function(t,e,s){l(Q,t,e,o,"logger",o)}}function Ne(o){return function(t,e,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(F,t,e)||{},m=Reflect.getOwnMetadata(Q,t,e)||{},b=Reflect.getOwnMetadata(H,t,e)?.[0]||{type:"json",params:{}},w=Reflect.getOwnMetadata(K,t,e)?.[0]||{type:"",params:{}},_=(Reflect.getOwnMetadata(V,t,e)?.[0]||{type:"allow",params:[]}).params;if(_.length&&!_.includes(this.getMethod())&&this.getMethod()!=="any")throw new u.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${_.join(",")} methods`});for(const d in h){if(!h.hasOwnProperty(d))continue;const p=`get${pe(h[d].type)}`;a[+d]=this[p](h[d].params)}for(const d in c)c.hasOwnProperty(d)&&(c[d].type,a[+d]=await this.getDb()[c[d].params].getConnection(),r.push(a[+d]));try{let d=await i.apply(this,a),p;if(Array.isArray(d)&&([d,p]=d),w.type!=="init")return n.format==="xml"||b.type==="xml"?this.successXml(d,Object.assign(b.params,p||{})):n.format==="buffer"?this.successBuffer(d,Object.assign(b.params,p||{})):this.success(d,Object.assign(b.params,p||{}))}catch(d){await Promise.all([...r.map($=>$.rollback())]);let p;n.format==="xml"||b.type==="xml"?p=this.errorXml(d):p=this.error(d);for(const $ in m){if(!m.hasOwnProperty($))continue;const X=m[$].params;await this[X].error(d,{response:A.omit(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(d=>d.release())])}}}}function De(){return function(o,t,e){l(K,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Je(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){l(V,t,e,0,"allow",o)}}const Te={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:P.jsonBody,rawBody:k,streamBody:C,urlencodedBody:B.urlencodedBody,multipartBody:M.multipartBody,readConfig:G.readConfig,readConfigSync:Y.readConfigSync,staticBody:x.staticBody,extensions:x.extensions,getExt:x.getExt,jwtDecode:ie,readJsonConfigsSync:ae};exports.ApiError=u.ApiError,exports.Server=y.Server,exports.codeToStatus=y.codeToStatus,exports.Jwt=g.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=ne,exports.Controller=E,exports.Model=U,exports.Ssr=ce,exports.Web=me,exports.action=je,exports.allow=Je,exports.body=qe,exports.config=ye,exports.connection=Pe,exports.context=_e,exports.controller=Oe,exports.cookies=we,exports.db=Ce,exports.headers=ve,exports.helpers=Te,exports.home=He,exports.hostname=$e,exports.http=Ne,exports.init=De,exports.json=Be,exports.logerror=We,exports.method=xe,exports.mixin=be,exports.mount=fe,exports.pool=Re,exports.protocol=Ae,exports.request=ge,exports.selectControllersSchema=le,exports.stream=Ee,exports.subaction=ke,exports.url=Se,exports.xml=Me;
57
+ `)).forEach(s=>{t[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},e[s.controller_name]=e[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},e[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(e),actions:Object.values(t)}},q=(o,t,e,s)=>{let n=o.controllers.find(c=>c.name===e);if(!n)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(n=Object.assign({isActive:!0,isSitemap:!1},n),!n.isActive)throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let i=n.subactions.find(c=>c.name===s);if(!i)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(i=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},i),!i.isActive)throw new u.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(c=>c.name===i.action);if(!a)throw new u.ApiError({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new u.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(c=>c.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(t))throw new u.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:n.id,name:n.name,isActive:n.isActive,isSitemap:n.isSitemap},subaction:{id:i.id,name:i.name,isPermission:i.isPermission,isCheckMethod:i.isCheckMethod,isLog:i.isLog,isActive:i.isActive,isSync:!!i.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class me{constructor(t,e,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=t,this.req=e,this.res.onAborted(()=>new u.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,t,ee.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),getRequest:()=>n,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((h,l)=>this.contextWeb.headers[h]=l);const i=this.contextWeb.headers["content-type"]||"application/json";if(n.controller&&n.subaction&&this.context.schema&&(this.route=this.findRoute(n.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,q(this.context.schema,this.contextWeb.method,this.route.name,n.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)});const h=this.importControllerSync(n.controller),l=new h;if(this.injectContext(l),n.subaction in l)e=await l[n.subaction]();else throw new u.ApiError({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});e=Object.assign({},this.defaultResponse,e),this.success(e);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof v.Memcached){const h=this.contextWeb.stack.memcached;if(h.isConnectedServers()){const l=await h.getPage(this.memcachedKey);if(l){const{data:g,headers:w}=l;this.success({body:g.toString(),headers:w,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(i.indexOf("application/json")!==-1||i.indexOf("text/json")!==-1)Object.assign(n,await P.jsonBody(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:n.files});else if(i.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await B.urlencodedBody(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const h=(await k(this.res)).toString(),l=O.xml2js(h,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,l||{})}else i.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):i.indexOf("binary")!==-1?await new Promise(h=>{const l=C(this.res,this.req),g=oe.tmpdir(),w="./body_"+R.randomBytes(32).toString("hex"),y=D.resolve(g,w),d=J.createWriteStream(y);l.pipe(d),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:y}}}),l.on("end",()=>h(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await L(this.contextWeb.db.home,this.contextWeb.method,this.route.name,n.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route});const a=await this.importController(n.controller),r=new a;this.injectContext(r);const c=await this.initComponent(r);if(typeof c>"u")if(n.subaction in r)e=await r[n.subaction]();else throw new u.ApiError({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else e=c;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importController(t){let e=this.route.component.default||this.route.component;if($.isClass(e)||(e=(await this.route.component()).default),typeof e!="function")throw new u.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}importControllerSync(t){const e=this.route.component.default||this.route.component;if(typeof e!="function")throw new u.ApiError({statusCode:404,code:12,message:`Class not found for ${t} route`});return e}findRoute(t){const e=this.context.routes.filter(s=>s.name===t&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!e)throw new u.ApiError({statusCode:404,code:11,message:`Route ${t} not found`});return e}injectContext(t){"$inject"in t&&t.$inject(this.contextWeb)}async initComponent(t){const e=[...new Set(["init",...t.$inits||[]])];for(const s of e)if(t[s]){const n=await t[s]();if(n)return n}}success(t){const e=t.body instanceof A.Stream,s=t.body instanceof Uint8Array,n=t.statusCode||200,i=b.codeToStatus(n),a=!s&&!e&&$.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&n===200&&t.memcache&&this.contextWeb?.stack?.memcached instanceof v.Memcached&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof u.ApiError&&t.getData()instanceof A.Stream;let s=b.codeToStatus(404),n=this.defaultResponse.headers,i=t.message;if(t instanceof u.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=b.codeToStatus(t.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?i=t.getData():i=$.isObject(t.getData())&&Object.keys(t.getData()).length>0?JSON.stringify(t.getData()):JSON.stringify(a)}e?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),i.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),this.res.end(i)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(e,n)):this.res.writeHeader(e,s)})}}const I={compact:!0,ignoreComment:!0,spaces:4};class E{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return N.cookieString(t,e,s)}success(t={},e){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,e?.headers||{}),body:{isError:!1,data:t},memcache:e?.memcache||null,statusCode:e?.statusCode||200}}successBuffer(t,e){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,e?.headers||{}),body:t,memcache:e?.memcache||null,statusCode:e?.statusCode||200}}error(t){const e=t,s=e.code?e.code:0,n=e.message?e.message:"Api request error",i=e.statusCode?e.statusCode:404,a=e.data?e.data:{},r=e.response?{status:e.response.status,headers:e.response.headers,config:{url:e.response.url,method:e.response.method,params:e.response.params,headers:e.response.headers},data:e.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},e.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:O.js2xml(Object.assign(s,{body:{...n.body}}),I),memcache:n.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:O.js2xml(Object.assign(s,{body:{...n.body}}),I),statusCode:n.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new A.PassThrough().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){this.responseHeaders.hasOwnProperty(t)?(this.responseHeaders[t]=Array.isArray(this.responseHeaders[t])?this.responseHeaders[t]:[this.responseHeaders[t]],this.responseHeaders[t].push(e)):this.responseHeaders[t]=e}}class U{async $create(t,...e){const s=new t(...e);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(t){return Promise.all(t.map(e=>this.$create(...e)))}$inject(t){this.$context=t}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}setResponseHeader(t,e){return this.$context.setResponseHeader(t,e)}setCookieHeader(t,e,s={}){return this.$context.setCookieHeader(t,e,s)}}const fe=async(o,t,e={},s)=>{const n=async r=>{const c=[...new Set(["init",...r.$inits||[]])];for(const h of c)if(r[h]){const l=await r[h]();if(l)return l}},i=(r,c)=>{"$inject"in r&&r.$inject(c)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await L(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?q(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof E)return i(a,t),t.$initResponse=await n(a),a;if(a instanceof U){const r=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return i(r,t),t.$initResponse=await n(r),r.getModel()}else throw new u.ApiError({message:"Class should be an instance of Controller or Model",statusCode:400})},f=Symbol("arguments"),F=Symbol("connections"),H=Symbol("response"),K=Symbol("init"),Q=Symbol("logger"),V=Symbol("filters"),pe=o=>o.charAt(0).toUpperCase()+o.slice(1);function ge(o){const t=(s,n)=>{for(const a of Reflect.ownKeys(n))Object.defineProperty(s.prototype,a,{value:n[a]});const i=Object.getPrototypeOf(n);i&&t(s,i)};function e(s){return t(s,o),s}return e}const m=(o,t,e,s,n,i)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,t,e)};function be(){return function(o,t,e){m(f,o,t,e,"request")}}function _e(){return function(o,t,e){m(f,o,t,e,"context")}}function ye(){return function(o,t,e){m(f,o,t,e,"config")}}function xe(){return function(o,t,e){m(f,o,t,e,"method")}}function we(){return function(o,t,e){m(f,o,t,e,"cookies")}}function $e(){return function(o,t,e){m(f,o,t,e,"hostname")}}function Se(){return function(o,t,e){m(f,o,t,e,"url")}}function Ae(){return function(o,t,e){m(f,o,t,e,"protocol")}}function Ce(){return function(o,t,e){m(f,o,t,e,"db")}}function ve(){return function(o,t,e){m(f,o,t,e,"headers")}}function Oe(){return function(o,t,e){m(f,o,t,e,"controller")}}function je(){return function(o,t,e){m(f,o,t,e,"action")}}function ke(){return function(o,t,e){m(f,o,t,e,"subaction")}}function qe(){return function(o,t,e){m(f,o,t,e,"body")}}function Ee(){return function(o,t,e){m(f,o,t,e,"stream")}}function He(){return function(o,t,e){m(f,o,t,e,"home")}}function Re(o="home"){return function(t,e,s){m(f,t,e,s,"pool",o)}}function Pe(o="home"){return function(t,e,s){m(F,t,e,s,"connection",o)}}function Be(o={}){return function(t,e,s){m(H,t,e,0,"json",o)}}function Me(o={}){return function(t,e,s){m(H,t,e,0,"xml",o)}}function We(o){return function(t,e,s){m(Q,t,e,o,"logger",o)}}function Ne(o){return function(t,e,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],c=Reflect.getOwnMetadata(f,t,e)||{},h=Reflect.getOwnMetadata(F,t,e)||{},l=Reflect.getOwnMetadata(Q,t,e)||{},g=Reflect.getOwnMetadata(H,t,e)?.[0]||{type:"json",params:{}},w=Reflect.getOwnMetadata(K,t,e)?.[0]||{type:"",params:{}},y=(Reflect.getOwnMetadata(V,t,e)?.[0]||{type:"allow",params:[]}).params;if(y.length&&!y.includes(this.getMethod())&&this.getMethod()!=="any")throw new u.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${y.join(",")} methods`});for(const d in c){if(!c.hasOwnProperty(d))continue;const p=`get${pe(c[d].type)}`;a[+d]=this[p](c[d].params)}for(const d in h)h.hasOwnProperty(d)&&(h[d].type,a[+d]=await this.getDb()[h[d].params].getConnection(),r.push(a[+d]));try{let d=await i.apply(this,a),p;if(Array.isArray(d)&&([d,p]=d),w.type!=="init")return n.format==="xml"||g.type==="xml"?this.successXml(d,Object.assign(g.params,p||{})):n.format==="buffer"?this.successBuffer(d,Object.assign(g.params,p||{})):this.success(d,Object.assign(g.params,p||{}))}catch(d){await Promise.all([...r.map(S=>S.rollback())]);let p;n.format==="xml"||g.type==="xml"?p=this.errorXml(d):p=this.error(d);for(const S in l){if(!l.hasOwnProperty(S))continue;const X=l[S].params;await this[X].error(d,{response:$.omit(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(d=>d.release())])}}}}function De(){return function(o,t,e){m(K,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Je(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){m(V,t,e,0,"allow",o)}}const Te={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:P.jsonBody,rawBody:k,streamBody:C,urlencodedBody:B.urlencodedBody,multipartBody:M.multipartBody,readConfig:G.readConfig,readConfigSync:Y.readConfigSync,staticBody:x.staticBody,extensions:x.extensions,getExt:x.getExt,jwtDecode:ie,readJsonConfigsSync:ae};exports.ApiError=u.ApiError,exports.Server=b.Server,exports.codeToStatus=b.codeToStatus,exports.Jwt=_.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=ne,exports.Controller=E,exports.Model=U,exports.Ssr=ce,exports.Web=me,exports.action=je,exports.allow=Je,exports.body=qe,exports.config=ye,exports.connection=Pe,exports.context=_e,exports.controller=Oe,exports.cookies=we,exports.db=Ce,exports.headers=ve,exports.helpers=Te,exports.home=He,exports.hostname=$e,exports.http=Ne,exports.init=De,exports.json=Be,exports.logerror=We,exports.method=xe,exports.mixin=ge,exports.mount=fe,exports.pool=Re,exports.protocol=Ae,exports.request=be,exports.selectControllersSchema=le,exports.stream=Ee,exports.subaction=ke,exports.url=Se,exports.xml=Me;
package/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as x}from"./Server.mjs";import{Server as _e}from"./Server.mjs";import{t as k,f as w,u as G}from"./Jwt-7tQL-rwa.js";import{J as ye}from"./Jwt-7tQL-rwa.js";import Y,{webcrypto as Z}from"crypto";import{TextEncoder as tt}from"util";import{Memcached as S}from"./Memcached.mjs";import{jsonBody as H}from"./jsonBody.mjs";import{PassThrough as R,Stream as q}from"stream";import{urlencodedBody as P}from"./urlencodedBody.mjs";import{multipartBody as W}from"./multipartBody.mjs";import{readConfig as et}from"./readConfig.mjs";import{readConfigSync as st}from"./readConfigSync.mjs";import{cookieParse as E}from"./cookieParse.mjs";import{cookieString as M}from"./cookieString.mjs";import{getExt as N,extensions as B,staticBody as D}from"./staticBody.mjs";import*as J from"fs";import*as ot from"path";import nt from"path";import{isClass as it,isObject as L,omit as rt}from"easy-ash";import at from"querystring";import C from"xml-js";import*as ct from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:T}=Z;class ht{constructor(e,t){this.algorithm="SHA-256",this.secret=e,this.algorithm=t?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(e){if(!e)return!1;const t=e.split(".");return await this.signString(`${t[0]}.${t[1]}`)===t[2]}async sign(e){const t=k({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=k(e),n=await this.signString(`${t}.${s}`);return`${t}.${s}.${n}`}decode(e){const t=(e||"").split("."),s=w(t[0]),n=w(t[1]);return{head:s,body:n}}async signString(e){const t=new tt,s=await T.importKey("raw",t.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return G(Buffer.from(await T.sign("HMAC",s,t.encode(e))).toString("base64"))}}const dt=o=>{const e=(o||"").split("."),t=w(e[0]),s=w(e[1]);return{head:t,body:s}},A=o=>new Promise((e,t)=>{ut(o,s=>e(s),()=>{t(new d({message:"Can`t parse request",code:1,statusCode:404}))})});function ut(o,e,t){let s=Buffer.from([]);o.onData((n,i)=>{s=Buffer.concat([s,Buffer.from(n)]),i&&e(s)}),o.onAborted(t)}const $=(o,e,t=!0)=>{o.onAborted(()=>new d({message:"Connection aborted",code:1,statusCode:404}));const s=new R;return s.headers={},e.forEach((n,i)=>s.headers[n]=i),o.onData((n,i)=>{s.write(Buffer.from(Buffer.from(n))),t&&s.resume(),i&&s.end()}),s},mt=(o,e={})=>{for(const t of o){const s=ot.resolve(t);Object.assign(e,JSON.parse(J.readFileSync(s).toString()))}return e};class lt{constructor(e,t,s,n){this.res=e,this.req=t,this.context=s,this.entry=n}async request(e={}){this.res.onAborted(()=>console.log("Abort is SSR handler"));const t=this.req.getQuery(),s=this.req.getUrl()+(t?`?${t}`:""),n=N(s);if(B.includes(n)){await D(this.res,this.req,"./dist/client");return}const i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:E(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((c,l)=>i.headers[c]=l);const a=`${i.protocol}://${i.hostname}${i.url}`;let r,h=null;this.context.memcached&&(h=await this.context.memcached.getPage(a)),h?(r=h.data.toString(),i.headers=h.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,i.headers,r,i.memcache)),this.res.cork(()=>{this.res.writeStatus(x(i.statusCode)),Object.keys(i.headers).map(c=>this.res.writeHeader(c,i.headers[c])),this.res.end(r)})}}const ft=async(o,e,t)=>(await o.poolQuery({sql:`
1
+ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as b}from"./Server.mjs";import{Server as _e}from"./Server.mjs";import{t as H,f as w,u as G}from"./Jwt-7tQL-rwa.js";import{J as xe}from"./Jwt-7tQL-rwa.js";import Y,{webcrypto as Z}from"crypto";import{TextEncoder as tt}from"util";import{Memcached as S}from"./Memcached.mjs";import{jsonBody as R}from"./jsonBody.mjs";import{PassThrough as q,Stream as P}from"stream";import{urlencodedBody as W}from"./urlencodedBody.mjs";import{multipartBody as E}from"./multipartBody.mjs";import{readConfig as et}from"./readConfig.mjs";import{readConfigSync as st}from"./readConfigSync.mjs";import{cookieParse as M}from"./cookieParse.mjs";import{cookieString as N}from"./cookieString.mjs";import{getExt as B,extensions as D,staticBody as J}from"./staticBody.mjs";import*as L from"fs";import*as ot from"path";import nt from"path";import{isObject as C,isClass as it,omit as rt}from"easy-ash";import at from"querystring";import A from"xml-js";import*as ct from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:T}=Z;class ht{constructor(e,t){this.algorithm="SHA-256",this.secret=e,this.algorithm=t?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(e){if(!e)return!1;const t=e.split(".");return await this.signString(`${t[0]}.${t[1]}`)===t[2]}async sign(e){const t=H({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=H(e),n=await this.signString(`${t}.${s}`);return`${t}.${s}.${n}`}decode(e){const t=(e||"").split("."),s=w(t[0]),n=w(t[1]);return{head:s,body:n}}async signString(e){const t=new tt,s=await T.importKey("raw",t.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return G(Buffer.from(await T.sign("HMAC",s,t.encode(e))).toString("base64"))}}const dt=o=>{const e=(o||"").split("."),t=w(e[0]),s=w(e[1]);return{head:t,body:s}},O=o=>new Promise((e,t)=>{ut(o,s=>e(s),()=>{t(new d({message:"Can`t parse request",code:1,statusCode:404}))})});function ut(o,e,t){let s=Buffer.from([]);o.onData((n,i)=>{s=Buffer.concat([s,Buffer.from(n)]),i&&e(s)}),o.onAborted(t)}const $=(o,e,t=!0)=>{o.onAborted(()=>new d({message:"Connection aborted",code:1,statusCode:404}));const s=new q;return s.headers={},e.forEach((n,i)=>s.headers[n]=i),o.onData((n,i)=>{s.write(Buffer.from(Buffer.from(n))),t&&s.resume(),i&&s.end()}),s},mt=(o,e={})=>{for(const t of o){const s=ot.resolve(t);Object.assign(e,JSON.parse(L.readFileSync(s).toString()))}return e};class lt{constructor(e,t,s,n){this.res=e,this.req=t,this.context=s,this.entry=n}async request(e={}){this.res.onAborted(()=>console.log("Abort is SSR handler"));const t=this.req.getQuery(),s=this.req.getUrl()+(t?`?${t}`:""),n=B(s);if(D.includes(n)){await J(this.res,this.req,"./dist/client");return}const i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:M(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((a,r)=>i.headers[a]=r);try{const a=`${i.protocol}://${i.hostname}${i.url}`;let r,c=null;this.context.memcached&&(c=await this.context.memcached.getPage(a)),c?(r=c.data.toString(),i.responseHeaders=c.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,i.headers,r,i.memcache)),this.res.cork(()=>{this.res.writeStatus(b(i.statusCode)),Object.keys(i.responseHeaders).map(h=>this.res.writeHeader(h,i.responseHeaders[h])),this.res.end(r)})}catch(a){let r=b(404),c=Object.assign({},i.responseHeaders||{}),h=a.message;a instanceof d&&(r=b(a.getStatusCode()),c=Object.assign(c,a.getHeaders()||{}),h=C(a.getData())&&Object.keys(a.getData()).length>0?JSON.stringify(a.getData()):h),this.res.cork(()=>{this.res.writeStatus(r),Object.keys(c).map(m=>this.res.writeHeader(m,c[m])),this.res.end(h)})}}}const ft=async(o,e,t)=>(await o.poolQuery({sql:`
2
2
  SELECT c.id AS controller_id,
3
3
  c.name AS controller_name,
4
4
  c.is_active AS controller_is_active,
@@ -35,7 +35,7 @@ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as x}from"./Server
35
35
  FROM app_controllers c
36
36
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
37
37
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
38
- `)).reduce((e,t)=>(e[`${t.controller_name}::${t.subaction_name}`]=t,e),{}),bt=async(o,e,t,s,n="",i=3600)=>{const a=`${n}::routes::controllers`,r=`${e}::${t}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await pt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),i),(c||{}).hasOwnProperty(r)?c[r]:void 0}},I=async(o,e,t,s,n,i="",a=3600)=>{let r;if(n&&n.isClient()&&n.isConnectedServers()?r=await bt(o,t,s,n,i,a):r=await ft(o,t,s),!r)throw new d({statusCode:404,code:11,message:`Controller ${t} not found in site schema`});const h=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new d({statusCode:404,code:11,message:`Controller ${t} not active in site schema`});if(!r.action_id)throw new d({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new d({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!h.includes(e))throw new d({statusCode:404,code:11,message:`Controller ${t} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},gt=async o=>{const e={},t={};return(await o.poolQuery(`
38
+ `)).reduce((e,t)=>(e[`${t.controller_name}::${t.subaction_name}`]=t,e),{}),gt=async(o,e,t,s,n="",i=3600)=>{const a=`${n}::routes::controllers`,r=`${e}::${t}`,c=await s.getValue(a);if(c){const h=JSON.parse(c.toString());return(h||{}).hasOwnProperty(r)?h[r]:void 0}else{const h=await pt(o);return await s.setValue(a,Buffer.from(JSON.stringify(h)),i),(h||{}).hasOwnProperty(r)?h[r]:void 0}},I=async(o,e,t,s,n,i="",a=3600)=>{let r;if(n&&n.isClient()&&n.isConnectedServers()?r=await gt(o,t,s,n,i,a):r=await ft(o,t,s),!r)throw new d({statusCode:404,code:11,message:`Controller ${t} not found in site schema`});const c=(r?.action_method||"").split(",").map(h=>h.trim());if(r.controller_is_active!==1)throw new d({statusCode:404,code:11,message:`Controller ${t} not active in site schema`});if(!r.action_id)throw new d({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new d({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!c.includes(e))throw new d({statusCode:404,code:11,message:`Controller ${t} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},bt=async o=>{const e={},t={};return(await o.poolQuery(`
39
39
  SELECT c.id AS controller_id,
40
40
  c.name AS controller_name,
41
41
  c.is_active AS controller_is_active,
@@ -54,4 +54,4 @@ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as x}from"./Server
54
54
  FROM app_controllers c
55
55
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
56
56
  LEFT JOIN app_actions a ON a.id = s.app_actions_id;
57
- `)).forEach(s=>{e[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},t[s.controller_name]=t[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},t[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(t),actions:Object.values(e)}},O=(o,e,t,s)=>{let n=o.controllers.find(h=>h.name===t);if(!n)throw new d({statusCode:404,code:11,message:`Controller ${t} not found is site schema`});if(n=Object.assign({isActive:!0,isSitemap:!1},n),!n.isActive)throw new d({statusCode:404,code:11,message:`Controller ${t} not active is site schema`});let i=n.subactions.find(h=>h.name===s);if(!i)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(i=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},i),!i.isActive)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===i.action);if(!a)throw new d({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new d({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(h=>h.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(e))throw new d({statusCode:404,code:11,message:`Controller ${t} action ${a.name} allow only ${a.method} method`});return{controller:{id:n.id,name:n.name,isActive:n.isActive,isSitemap:n.isSitemap},subaction:{id:i.id,name:i.name,isPermission:i.isPermission,isCheckMethod:i.isCheckMethod,isLog:i.isLog,isActive:i.isActive,isSync:!!i.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class _t{constructor(e,t,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=e,this.req=t,this.res.onAborted(()=>new d({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(e){return Object.assign(this.defaultRequest,e),this}async request(e={}){let t={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,e,at.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},schema:this.context.schema,routes:this.context.routes,getRequest:()=>n},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,l)=>this.contextWeb.headers[c]=l);const i=this.contextWeb.headers["content-type"]||"application/json";if(n.controller&&n.subaction&&this.context.schema&&(this.route=this.findRoute(n.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,O(this.context.schema,this.contextWeb.method,this.route.name,n.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:$(this.res,this.req,!1)});const c=this.importControllerSync(n.controller),l=new c;if(this.injectContext(l),n.subaction in l)t=await l[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});t=Object.assign({},this.defaultResponse,t),this.success(t);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const l=await c.getPage(this.memcachedKey);if(l){const{data:b,headers:_}=l;this.success({body:b.toString(),headers:_,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(i.indexOf("application/json")!==-1||i.indexOf("text/json")!==-1)Object.assign(n,await H(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await W(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:n.files});else if(i.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await P(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const c=(await A(this.res)).toString(),l=C.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,l||{})}else i.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:$(this.res,this.req,!1)}):i.indexOf("binary")!==-1?await new Promise(c=>{const l=$(this.res,this.req),b=ct.tmpdir(),_="./body_"+Y.randomBytes(32).toString("hex"),g=nt.resolve(b,_),u=J.createWriteStream(g);l.pipe(u),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:g}}}),l.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await A(this.res)});this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?O(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await I(this.contextWeb.db.home,this.contextWeb.method,this.route.name,n.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route});const a=await this.importController(n.controller),r=new a;this.injectContext(r);const h=await this.initComponent(r);if(typeof h>"u")if(n.subaction in r)t=await r[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else t=h;t=Object.assign({},this.defaultResponse,t),this.success(t)}catch(s){this.error(s)}}async importController(e){let t=this.route.component.default||this.route.component;if(it(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}importControllerSync(e){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}findRoute(e){const t=this.context.routes.filter(s=>s.name===e&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!t)throw new d({statusCode:404,code:11,message:`Route ${e} not found`});return t}injectContext(e){"$inject"in e&&e.$inject(this.contextWeb)}async initComponent(e){const t=[...new Set(["init",...e.$inits||[]])];for(const s of t)if(e[s]){const n=await e[s]();if(n)return n}}success(e){const t=e.body instanceof q,s=e.body instanceof Uint8Array,n=e.statusCode||200,i=x(n),a=!s&&!t&&L(e.body)?JSON.stringify(e.body):e.body;!s&&!t&&["get","head"].includes(this.contextWeb.method)&&n===200&&e.memcache&&this.contextWeb?.stack?.memcached instanceof S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,e.headers,a,e.memcache).then(),t?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),this.res.end(a)})}error(e){const t=e instanceof d&&e.getData()instanceof q;let s=x(404),n=this.defaultResponse.headers,i=e.message;if(e instanceof d){const a={isError:!0,code:e.getCode(),error:e.getMessage()};s=x(e.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,e.getHeaders()||{}),t?i=e.getData():i=L(e.getData())&&Object.keys(e.getData()).length>0?JSON.stringify(e.getData()):JSON.stringify(a)}t?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),i.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),this.res.end(i)})}writeHeaders(e){Object.entries(e).forEach(([t,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(t,n)):this.res.writeHeader(t,s)})}}const U={compact:!0,ignoreComment:!0,spaces:4};class v{constructor(){this.responseHeaders={}}setCookieHeader(e,t,s={}){return M(e,t,s)}success(e={},t){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,t?.headers||{}),body:{isError:!1,data:e},memcache:t?.memcache||null,statusCode:t?.statusCode||200}}successBuffer(e,t){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,t?.headers||{}),body:e,memcache:t?.memcache||null,statusCode:t?.statusCode||200}}error(e){const t=e,s=t.code?t.code:0,n=t.message?t.message:"Api request error",i=t.statusCode?t.statusCode:404,a=t.data?t.data:{},r=t.response?{status:t.response.status,headers:t.response.headers,config:{url:t.response.url,method:t.response.method,params:t.response.params,headers:t.response.headers},data:t.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},t.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?t.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(e={},t){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(e,t);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,t?.headers||{}),body:C.js2xml(Object.assign(s,{body:{...n.body}}),U),memcache:n.memcache}}errorXml(e){const t=e,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(t);return{headers:Object.assign({"content-type":"application/xml"},t.headers),body:C.js2xml(Object.assign(s,{body:{...n.body}}),U),statusCode:n.statusCode}}async $create(e,...t){const s=new e(...t);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new R().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){this.responseHeaders.hasOwnProperty(e)?(this.responseHeaders[e]=Array.isArray(this.responseHeaders[e])?this.responseHeaders[e]:[this.responseHeaders[e]],this.responseHeaders[e].push(t)):this.responseHeaders[e]=t}}class F{async $create(e,...t){const s=new e(...t);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){return this.$context.setResponseHeader(e,t)}setCookieHeader(e,t,s={}){return this.$context.setCookieHeader(e,t,s)}}const xt=async(o,e,t={},s)=>{const n=async r=>{const h=[...new Set(["init",...r.$inits||[]])];for(const c of h)if(r[c]){const l=await r[c]();if(l)return l}},i=(r,h)=>{"$inject"in r&&r.$inject(h)};e=Object.assign({config:{},getRequest:()=>t,method:"get",...t.controller&&t.subaction&&e.db?.home&&!e.schema?await I(e.db.home,e.method||"get",t.controller,t.subaction):{},...t.controller&&t.subaction&&e.schema?O(e.schema,e.method||"get",t.controller,t.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},e);const a=new o(...s||[]);if(a instanceof v)return i(a,e),e.$initResponse=await n(a),a;if(a instanceof F){const r=new class extends v{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return i(r,e),e.$initResponse=await n(r),r.getModel()}else throw new d({message:"Class should be an instance of Controller or Model",statusCode:400})},f=Symbol("arguments"),K=Symbol("connections"),j=Symbol("response"),Q=Symbol("init"),V=Symbol("logger"),X=Symbol("filters"),yt=o=>o.charAt(0).toUpperCase()+o.slice(1);function wt(o){const e=(s,n)=>{for(const a of Reflect.ownKeys(n))Object.defineProperty(s.prototype,a,{value:n[a]});const i=Object.getPrototypeOf(n);i&&e(s,i)};function t(s){return e(s,o),s}return t}const m=(o,e,t,s,n,i)=>{const a=Reflect.getOwnMetadata(o,e,t)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,e,t)};function $t(){return function(o,e,t){m(f,o,e,t,"request")}}function St(){return function(o,e,t){m(f,o,e,t,"context")}}function Ct(){return function(o,e,t){m(f,o,e,t,"config")}}function At(){return function(o,e,t){m(f,o,e,t,"method")}}function Ot(){return function(o,e,t){m(f,o,e,t,"cookies")}}function vt(){return function(o,e,t){m(f,o,e,t,"hostname")}}function jt(){return function(o,e,t){m(f,o,e,t,"url")}}function kt(){return function(o,e,t){m(f,o,e,t,"protocol")}}function Ht(){return function(o,e,t){m(f,o,e,t,"db")}}function Rt(){return function(o,e,t){m(f,o,e,t,"headers")}}function qt(){return function(o,e,t){m(f,o,e,t,"controller")}}function Pt(){return function(o,e,t){m(f,o,e,t,"action")}}function Wt(){return function(o,e,t){m(f,o,e,t,"subaction")}}function Et(){return function(o,e,t){m(f,o,e,t,"body")}}function Mt(){return function(o,e,t){m(f,o,e,t,"stream")}}function Nt(){return function(o,e,t){m(f,o,e,t,"home")}}function Bt(o="home"){return function(e,t,s){m(f,e,t,s,"pool",o)}}function Dt(o="home"){return function(e,t,s){m(K,e,t,s,"connection",o)}}function Jt(o={}){return function(e,t,s){m(j,e,t,0,"json",o)}}function Lt(o={}){return function(e,t,s){m(j,e,t,0,"xml",o)}}function Tt(o){return function(e,t,s){m(V,e,t,o,"logger",o)}}function It(o){return function(e,t,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],h=Reflect.getOwnMetadata(f,e,t)||{},c=Reflect.getOwnMetadata(K,e,t)||{},l=Reflect.getOwnMetadata(V,e,t)||{},b=Reflect.getOwnMetadata(j,e,t)?.[0]||{type:"json",params:{}},_=Reflect.getOwnMetadata(Q,e,t)?.[0]||{type:"",params:{}},g=(Reflect.getOwnMetadata(X,e,t)?.[0]||{type:"allow",params:[]}).params;if(g.length&&!g.includes(this.getMethod())&&this.getMethod()!=="any")throw new d({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${g.join(",")} methods`});for(const u in h){if(!h.hasOwnProperty(u))continue;const p=`get${yt(h[u].type)}`;a[+u]=this[p](h[u].params)}for(const u in c)c.hasOwnProperty(u)&&(c[u].type,a[+u]=await this.getDb()[c[u].params].getConnection(),r.push(a[+u]));try{let u=await i.apply(this,a),p;if(Array.isArray(u)&&([u,p]=u),_.type!=="init")return n.format==="xml"||b.type==="xml"?this.successXml(u,Object.assign(b.params,p||{})):n.format==="buffer"?this.successBuffer(u,Object.assign(b.params,p||{})):this.success(u,Object.assign(b.params,p||{}))}catch(u){await Promise.all([...r.map(y=>y.rollback())]);let p;n.format==="xml"||b.type==="xml"?p=this.errorXml(u):p=this.error(u);for(const y in l){if(!l.hasOwnProperty(y))continue;const z=l[y].params;await this[z].error(u,{response:rt(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(u=>u.release())])}}}}function Ut(){return function(o,e,t){m(Q,o,e,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(e)}}function Ft(o){return o=(Array.isArray(o)?o:[o]).map(e=>e.toLowerCase()),function(e,t,s){m(X,e,t,0,"allow",o)}}const Kt={cookieParse:E,cookieString:M,jsonBody:H,rawBody:A,streamBody:$,urlencodedBody:P,multipartBody:W,readConfig:et,readConfigSync:st,staticBody:D,extensions:B,getExt:N,jwtDecode:dt,readJsonConfigsSync:mt};export{d as ApiError,ht as AsyncJwt,v as Controller,ye as Jwt,S as Memcached,F as Model,_e as Server,lt as Ssr,_t as Web,Pt as action,Ft as allow,Et as body,x as codeToStatus,Ct as config,Dt as connection,St as context,qt as controller,Ot as cookies,Ht as db,Rt as headers,Kt as helpers,Nt as home,vt as hostname,It as http,Ut as init,Jt as json,Tt as logerror,At as method,wt as mixin,xt as mount,Bt as pool,kt as protocol,$t as request,gt as selectControllersSchema,Mt as stream,Wt as subaction,jt as url,Lt as xml};
57
+ `)).forEach(s=>{e[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},t[s.controller_name]=t[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},t[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(t),actions:Object.values(e)}},j=(o,e,t,s)=>{let n=o.controllers.find(c=>c.name===t);if(!n)throw new d({statusCode:404,code:11,message:`Controller ${t} not found is site schema`});if(n=Object.assign({isActive:!0,isSitemap:!1},n),!n.isActive)throw new d({statusCode:404,code:11,message:`Controller ${t} not active is site schema`});let i=n.subactions.find(c=>c.name===s);if(!i)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(i=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},i),!i.isActive)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(c=>c.name===i.action);if(!a)throw new d({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new d({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(c=>c.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(e))throw new d({statusCode:404,code:11,message:`Controller ${t} action ${a.name} allow only ${a.method} method`});return{controller:{id:n.id,name:n.name,isActive:n.isActive,isSitemap:n.isSitemap},subaction:{id:i.id,name:i.name,isPermission:i.isPermission,isCheckMethod:i.isCheckMethod,isLog:i.isLog,isActive:i.isActive,isSync:!!i.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class _t{constructor(e,t,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=e,this.req=t,this.res.onAborted(()=>new d({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(e){return Object.assign(this.defaultRequest,e),this}async request(e={}){let t={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,e,at.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),getRequest:()=>n,config:this.context.config,db:this.context.db,stack:this.context.stack||{},headers:{},cookies:this.req.cookies,schema:this.context.schema,routes:this.context.routes,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http"},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((h,m)=>this.contextWeb.headers[h]=m);const i=this.contextWeb.headers["content-type"]||"application/json";if(n.controller&&n.subaction&&this.context.schema&&(this.route=this.findRoute(n.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,j(this.context.schema,this.contextWeb.method,this.route.name,n.subaction)),this.contextWeb.subaction.isSync)){["get","head"].includes(this.contextWeb.method)||Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:$(this.res,this.req,!1)});const h=this.importControllerSync(n.controller),m=new h;if(this.injectContext(m),n.subaction in m)t=await m[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});t=Object.assign({},this.defaultResponse,t),this.success(t);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof S){const h=this.contextWeb.stack.memcached;if(h.isConnectedServers()){const m=await h.getPage(this.memcachedKey);if(m){const{data:g,headers:y}=m;this.success({body:g.toString(),headers:y,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(i.indexOf("application/json")!==-1||i.indexOf("text/json")!==-1)Object.assign(n,await R(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await E(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:n.files});else if(i.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await W(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const h=(await O(this.res)).toString(),m=A.xml2js(h,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,m||{})}else i.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:$(this.res,this.req,!1)}):i.indexOf("binary")!==-1?await new Promise(h=>{const m=$(this.res,this.req),g=ct.tmpdir(),y="./body_"+Y.randomBytes(32).toString("hex"),_=nt.resolve(g,y),u=L.createWriteStream(_);m.pipe(u),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:_}}}),m.on("end",()=>h(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await O(this.res)});this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?j(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await I(this.contextWeb.db.home,this.contextWeb.method,this.route.name,n.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route});const a=await this.importController(n.controller),r=new a;this.injectContext(r);const c=await this.initComponent(r);if(typeof c>"u")if(n.subaction in r)t=await r[n.subaction]();else throw new d({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else t=c;t=Object.assign({},this.defaultResponse,t),this.success(t)}catch(s){this.error(s)}}async importController(e){let t=this.route.component.default||this.route.component;if(it(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}importControllerSync(e){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}findRoute(e){const t=this.context.routes.filter(s=>s.name===e&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!t)throw new d({statusCode:404,code:11,message:`Route ${e} not found`});return t}injectContext(e){"$inject"in e&&e.$inject(this.contextWeb)}async initComponent(e){const t=[...new Set(["init",...e.$inits||[]])];for(const s of t)if(e[s]){const n=await e[s]();if(n)return n}}success(e){const t=e.body instanceof P,s=e.body instanceof Uint8Array,n=e.statusCode||200,i=b(n),a=!s&&!t&&C(e.body)?JSON.stringify(e.body):e.body;!s&&!t&&["get","head"].includes(this.contextWeb.method)&&n===200&&e.memcache&&this.contextWeb?.stack?.memcached instanceof S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,e.headers,a,e.memcache).then(),t?this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),a.on("data",r=>{this.res.write(r)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(i),this.writeHeaders(e.headers),this.res.end(a)})}error(e){const t=e instanceof d&&e.getData()instanceof P;let s=b(404),n=this.defaultResponse.headers,i=e.message;if(e instanceof d){const a={isError:!0,code:e.getCode(),error:e.getMessage()};s=b(e.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,e.getHeaders()||{}),t?i=e.getData():i=C(e.getData())&&Object.keys(e.getData()).length>0?JSON.stringify(e.getData()):JSON.stringify(a)}t?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),i.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),this.res.end(i)})}writeHeaders(e){Object.entries(e).forEach(([t,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(t,n)):this.res.writeHeader(t,s)})}}const U={compact:!0,ignoreComment:!0,spaces:4};class v{constructor(){this.responseHeaders={}}setCookieHeader(e,t,s={}){return N(e,t,s)}success(e={},t){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,t?.headers||{}),body:{isError:!1,data:e},memcache:t?.memcache||null,statusCode:t?.statusCode||200}}successBuffer(e,t){return{headers:Object.assign({"content-type":"application/octet-stream"},this.responseHeaders,t?.headers||{}),body:e,memcache:t?.memcache||null,statusCode:t?.statusCode||200}}error(e){const t=e,s=t.code?t.code:0,n=t.message?t.message:"Api request error",i=t.statusCode?t.statusCode:404,a=t.data?t.data:{},r=t.response?{status:t.response.status,headers:t.response.headers,config:{url:t.response.url,method:t.response.method,params:t.response.params,headers:t.response.headers},data:t.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},t.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?t.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(e={},t){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(e,t);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,t?.headers||{}),body:A.js2xml(Object.assign(s,{body:{...n.body}}),U),memcache:n.memcache}}errorXml(e){const t=e,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(t);return{headers:Object.assign({"content-type":"application/xml"},t.headers),body:A.js2xml(Object.assign(s,{body:{...n.body}}),U),statusCode:n.statusCode}}async $create(e,...t){const s=new e(...t);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,getUrl:this.$context.getUrl,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new q().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){this.responseHeaders.hasOwnProperty(e)?(this.responseHeaders[e]=Array.isArray(this.responseHeaders[e])?this.responseHeaders[e]:[this.responseHeaders[e]],this.responseHeaders[e].push(t)):this.responseHeaders[e]=t}}class F{async $create(e,...t){const s=new e(...t);return"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,getRequest:this.$context.getRequest,config:this.$context.config,db:this.$context.db,stack:this.$context.stack,headers:this.$context.headers,cookies:this.$context.cookies,controller:this.$context.controller,action:this.$context.action,subaction:this.$context.subaction,schema:this.$context.schema,routes:this.$context.routes,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getUrl(){return this.$context.url}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){return this.$context.setResponseHeader(e,t)}setCookieHeader(e,t,s={}){return this.$context.setCookieHeader(e,t,s)}}const yt=async(o,e,t={},s)=>{const n=async r=>{const c=[...new Set(["init",...r.$inits||[]])];for(const h of c)if(r[h]){const m=await r[h]();if(m)return m}},i=(r,c)=>{"$inject"in r&&r.$inject(c)};e=Object.assign({config:{},getRequest:()=>t,method:"get",...t.controller&&t.subaction&&e.db?.home&&!e.schema?await I(e.db.home,e.method||"get",t.controller,t.subaction):{},...t.controller&&t.subaction&&e.schema?j(e.schema,e.method||"get",t.controller,t.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},e);const a=new o(...s||[]);if(a instanceof v)return i(a,e),e.$initResponse=await n(a),a;if(a instanceof F){const r=new class extends v{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return i(r,e),e.$initResponse=await n(r),r.getModel()}else throw new d({message:"Class should be an instance of Controller or Model",statusCode:400})},f=Symbol("arguments"),K=Symbol("connections"),k=Symbol("response"),Q=Symbol("init"),V=Symbol("logger"),X=Symbol("filters"),xt=o=>o.charAt(0).toUpperCase()+o.slice(1);function wt(o){const e=(s,n)=>{for(const a of Reflect.ownKeys(n))Object.defineProperty(s.prototype,a,{value:n[a]});const i=Object.getPrototypeOf(n);i&&e(s,i)};function t(s){return e(s,o),s}return t}const l=(o,e,t,s,n,i)=>{const a=Reflect.getOwnMetadata(o,e,t)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,e,t)};function $t(){return function(o,e,t){l(f,o,e,t,"request")}}function St(){return function(o,e,t){l(f,o,e,t,"context")}}function Ct(){return function(o,e,t){l(f,o,e,t,"config")}}function At(){return function(o,e,t){l(f,o,e,t,"method")}}function Ot(){return function(o,e,t){l(f,o,e,t,"cookies")}}function jt(){return function(o,e,t){l(f,o,e,t,"hostname")}}function vt(){return function(o,e,t){l(f,o,e,t,"url")}}function kt(){return function(o,e,t){l(f,o,e,t,"protocol")}}function Ht(){return function(o,e,t){l(f,o,e,t,"db")}}function Rt(){return function(o,e,t){l(f,o,e,t,"headers")}}function qt(){return function(o,e,t){l(f,o,e,t,"controller")}}function Pt(){return function(o,e,t){l(f,o,e,t,"action")}}function Wt(){return function(o,e,t){l(f,o,e,t,"subaction")}}function Et(){return function(o,e,t){l(f,o,e,t,"body")}}function Mt(){return function(o,e,t){l(f,o,e,t,"stream")}}function Nt(){return function(o,e,t){l(f,o,e,t,"home")}}function Bt(o="home"){return function(e,t,s){l(f,e,t,s,"pool",o)}}function Dt(o="home"){return function(e,t,s){l(K,e,t,s,"connection",o)}}function Jt(o={}){return function(e,t,s){l(k,e,t,0,"json",o)}}function Lt(o={}){return function(e,t,s){l(k,e,t,0,"xml",o)}}function Tt(o){return function(e,t,s){l(V,e,t,o,"logger",o)}}function It(o){return function(e,t,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],c=Reflect.getOwnMetadata(f,e,t)||{},h=Reflect.getOwnMetadata(K,e,t)||{},m=Reflect.getOwnMetadata(V,e,t)||{},g=Reflect.getOwnMetadata(k,e,t)?.[0]||{type:"json",params:{}},y=Reflect.getOwnMetadata(Q,e,t)?.[0]||{type:"",params:{}},_=(Reflect.getOwnMetadata(X,e,t)?.[0]||{type:"allow",params:[]}).params;if(_.length&&!_.includes(this.getMethod())&&this.getMethod()!=="any")throw new d({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${_.join(",")} methods`});for(const u in c){if(!c.hasOwnProperty(u))continue;const p=`get${xt(c[u].type)}`;a[+u]=this[p](c[u].params)}for(const u in h)h.hasOwnProperty(u)&&(h[u].type,a[+u]=await this.getDb()[h[u].params].getConnection(),r.push(a[+u]));try{let u=await i.apply(this,a),p;if(Array.isArray(u)&&([u,p]=u),y.type!=="init")return n.format==="xml"||g.type==="xml"?this.successXml(u,Object.assign(g.params,p||{})):n.format==="buffer"?this.successBuffer(u,Object.assign(g.params,p||{})):this.success(u,Object.assign(g.params,p||{}))}catch(u){await Promise.all([...r.map(x=>x.rollback())]);let p;n.format==="xml"||g.type==="xml"?p=this.errorXml(u):p=this.error(u);for(const x in m){if(!m.hasOwnProperty(x))continue;const z=m[x].params;await this[z].error(u,{response:rt(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(u=>u.release())])}}}}function Ut(){return function(o,e,t){l(Q,o,e,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(e)}}function Ft(o){return o=(Array.isArray(o)?o:[o]).map(e=>e.toLowerCase()),function(e,t,s){l(X,e,t,0,"allow",o)}}const Kt={cookieParse:M,cookieString:N,jsonBody:R,rawBody:O,streamBody:$,urlencodedBody:W,multipartBody:E,readConfig:et,readConfigSync:st,staticBody:J,extensions:D,getExt:B,jwtDecode:dt,readJsonConfigsSync:mt};export{d as ApiError,ht as AsyncJwt,v as Controller,xe as Jwt,S as Memcached,F as Model,_e as Server,lt as Ssr,_t as Web,Pt as action,Ft as allow,Et as body,b as codeToStatus,Ct as config,Dt as connection,St as context,qt as controller,Ot as cookies,Ht as db,Rt as headers,Kt as helpers,Nt as home,jt as hostname,It as http,Ut as init,Jt as json,Tt as logerror,At as method,wt as mixin,yt as mount,Bt as pool,kt as protocol,$t as request,bt as selectControllersSchema,Mt as stream,Wt as subaction,vt as url,Lt as xml};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jwn-js/common",
3
3
  "private": false,
4
- "version": "2.3.9",
4
+ "version": "2.3.11",
5
5
  "description": "@jwn-js/common package",
6
6
  "main": "./index.js",
7
7
  "types": "./index.d.ts",
package/staticBody.js CHANGED
@@ -1 +1 @@
1
- "use strict";var m=require("path"),l=require("fs"),n=require("./ApiError.js");const i={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2"},s=Object.keys(i),p=t=>t.split(".").pop(),r=t=>i[t.toLowerCase()]||"application/octet-stream";async function d(t,e,o){try{t.onAborted(()=>new n.ApiError({message:"Requers is aborted",code:1,statusCode:404}));let a=e.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const c=m.resolve(o,a),x=await l.promises.readFile(c);t.cork(()=>{t.writeStatus("200 OK").writeHeader("content-type",r(p(a))).end(x)})}catch(a){t.cork(()=>{t.writeStatus("404 Not Found").end(a.message)})}}exports.extensions=s,exports.exts=i,exports.getExt=p,exports.staticBody=d;
1
+ "use strict";var x=require("path"),l=require("fs"),n=require("./ApiError.js");const i={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2",webmanifest:"application/manifest+json"},s=Object.keys(i),p=t=>t.split(".").pop(),r=t=>i[t.toLowerCase()]||"application/octet-stream";async function d(t,e,o){try{t.onAborted(()=>new n.ApiError({message:"Request is aborted",code:1,statusCode:404}));let a=e.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const c=x.resolve(o,a),m=await l.promises.readFile(c);t.cork(()=>{t.writeStatus("200 OK").writeHeader("content-type",r(p(a))).end(m)})}catch(a){t.cork(()=>{t.writeStatus("404 Not Found").end(a.message)})}}exports.extensions=s,exports.exts=i,exports.getExt=p,exports.staticBody=d;
package/staticBody.mjs CHANGED
@@ -1 +1 @@
1
- import x from"path";import{promises as l}from"fs";import{ApiError as n}from"./ApiError.mjs";const i={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2"},s=Object.keys(i),p=t=>t.split(".").pop(),r=t=>i[t.toLowerCase()]||"application/octet-stream";async function d(t,o,e){try{t.onAborted(()=>new n({message:"Requers is aborted",code:1,statusCode:404}));let a=o.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const m=x.resolve(e,a),c=await l.readFile(m);t.cork(()=>{t.writeStatus("200 OK").writeHeader("content-type",r(p(a))).end(c)})}catch(a){t.cork(()=>{t.writeStatus("404 Not Found").end(a.message)})}}export{s as extensions,i as exts,p as getExt,d as staticBody};
1
+ import x from"path";import{promises as l}from"fs";import{ApiError as n}from"./ApiError.mjs";const i={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2",webmanifest:"application/manifest+json"},s=Object.keys(i),p=t=>t.split(".").pop(),r=t=>i[t.toLowerCase()]||"application/octet-stream";async function d(t,e,o){try{t.onAborted(()=>new n({message:"Request is aborted",code:1,statusCode:404}));let a=e.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const m=x.resolve(o,a),c=await l.readFile(m);t.cork(()=>{t.writeStatus("200 OK").writeHeader("content-type",r(p(a))).end(c)})}catch(a){t.cork(()=>{t.writeStatus("404 Not Found").end(a.message)})}}export{s as extensions,i as exts,p as getExt,d as staticBody};