@jwn-js/common 2.4.2 → 2.4.4

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/docs/assets/search.js +1 -1
  2. package/docs/classes/ApiError.html +2 -2
  3. package/docs/classes/AsyncJwt.html +2 -2
  4. package/docs/classes/Binding.html +2 -2
  5. package/docs/classes/Controller.html +2 -2
  6. package/docs/classes/Jwt.html +2 -2
  7. package/docs/classes/Memcached.html +2 -2
  8. package/docs/classes/Model.html +2 -2
  9. package/docs/classes/Server.html +2 -2
  10. package/docs/classes/Ssr.html +2 -2
  11. package/docs/classes/Web.html +2 -2
  12. package/docs/functions/action.html +1 -1
  13. package/docs/functions/allow.html +1 -1
  14. package/docs/functions/body.html +1 -1
  15. package/docs/functions/codeToStatus.html +1 -1
  16. package/docs/functions/config-1.html +1 -1
  17. package/docs/functions/connection.html +1 -1
  18. package/docs/functions/context.html +1 -1
  19. package/docs/functions/controller-1.html +1 -1
  20. package/docs/functions/cookies.html +1 -1
  21. package/docs/functions/db.html +1 -1
  22. package/docs/functions/headers.html +1 -1
  23. package/docs/functions/home.html +1 -1
  24. package/docs/functions/hostname.html +1 -1
  25. package/docs/functions/http.html +1 -1
  26. package/docs/functions/init.html +1 -1
  27. package/docs/functions/inject.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/remote.html +1 -1
  36. package/docs/functions/request.html +1 -1
  37. package/docs/functions/selectControllersSchema.html +1 -1
  38. package/docs/functions/stream.html +1 -1
  39. package/docs/functions/subaction.html +1 -1
  40. package/docs/functions/url.html +1 -1
  41. package/docs/functions/xml.html +1 -1
  42. package/docs/index.html +2 -2
  43. package/docs/interfaces/ApiErrorMessage.html +2 -2
  44. package/docs/interfaces/Config.html +2 -2
  45. package/docs/interfaces/ContextSsr.html +2 -2
  46. package/docs/interfaces/ContextWeb.html +2 -2
  47. package/docs/interfaces/OptionsSsr.html +2 -2
  48. package/docs/interfaces/OptionsWeb.html +2 -2
  49. package/docs/interfaces/ResponseOptions.html +2 -2
  50. package/docs/interfaces/Route.html +2 -2
  51. package/docs/interfaces/Schema.html +2 -2
  52. package/docs/interfaces/ServerHandler.html +2 -2
  53. package/docs/interfaces/ServerOptions.html +2 -2
  54. package/docs/interfaces/ServerWebsocket.html +2 -2
  55. package/docs/modules.html +2 -2
  56. package/docs/types/ServerRoutes.html +1 -1
  57. package/docs/variables/helpers.html +9 -10
  58. package/index.d.ts +5 -1
  59. package/index.js +4 -4
  60. package/index.mjs +4 -4
  61. package/jsonBody.d.ts +0 -5
  62. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -330,6 +330,7 @@ declare class Web {
330
330
  private readonly res;
331
331
  private readonly req;
332
332
  private readonly context;
333
+ private opts;
333
334
  private defaultRequest;
334
335
  private readonly defaultResponse;
335
336
  private readonly defaultControllerSubaction;
@@ -338,7 +339,9 @@ declare class Web {
338
339
  contextWeb: ContextWebController & {
339
340
  [key: string]: any;
340
341
  };
341
- constructor(res: HttpResponse, req: HttpRequest, context: OptionsWeb);
342
+ constructor(res: HttpResponse, req: HttpRequest, context: OptionsWeb, opts?: {
343
+ raw?: boolean;
344
+ });
342
345
  setDefaultRequest(params: DefaultRequestParams): this;
343
346
  request(input?: Request): Promise<void>;
344
347
  private importBinding;
@@ -628,6 +631,7 @@ declare const helpers: {
628
631
  cookieParse: (str: string) => Record<string, any>;
629
632
  cookieString: (name: string, value: any, options?: Record<string, any>) => string;
630
633
  jsonBody: (res: uWebSockets_js.HttpResponse) => Promise<any>;
634
+ jsonBodyRaw: (res: uWebSockets_js.HttpResponse) => Promise<any>;
631
635
  rawBody: (res: uWebSockets_js.HttpResponse) => Promise<Buffer>;
632
636
  streamBody: (res: uWebSockets_js.HttpResponse, req: uWebSockets_js.HttpRequest, resume?: boolean) => stream$1.Stream;
633
637
  urlencodedBody: (res: uWebSockets_js.HttpResponse) => Promise<any>;
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var d=require("./ApiError.js"),x=require("./Server.js"),$=require("./Jwt-CDdbxwvH.js"),R=require("crypto"),G=require("util"),v=require("./Memcached.js"),P=require("./jsonBody.js"),A=require("stream"),B=require("./urlencodedBody.js"),M=require("./multipartBody.js"),Y=require("./readConfig.js"),Z=require("./readConfigSync.js"),W=require("./cookieParse.js"),N=require("./cookieString.js"),y=require("./staticBody.js"),tt=require("fs"),D=require("path"),w=require("easy-ash"),et=require("querystring"),O=require("xml-js"),st=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(tt),ot=j(D),it=j(st);const{subtle:T}=R.webcrypto;class nt{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),i=await this.signString(`${e}.${s}`);return`${e}.${s}.${i}`}decode(t){const e=(t||"").split("."),s=$.fromBase64url(e[0]),i=$.fromBase64url(e[1]);return{head:s,body:i}}async signString(t){const e=new G.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 rt=o=>{const t=(o||"").split("."),e=$.fromBase64url(t[0]),s=$.fromBase64url(t[1]);return{head:e,body:s}},k=o=>new Promise((t,e)=>{at(o,s=>t(s),()=>{e(new d.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function at(o,t,e){let s=Buffer.from([]);o.onData((i,r)=>{s=Buffer.concat([s,Buffer.from(i)]),r&&t(s)}),o.onAborted(e)}const C=(o,t,e=!0)=>{o.onAborted(()=>new d.ApiError({message:"Connection aborted",code:1,statusCode:404}));const s=new A.PassThrough;return s.headers={},t.forEach((i,r)=>s.headers[i]=r),o.onData((i,r)=>{s.write(Buffer.from(Buffer.from(i))),e&&s.resume(),r&&s.end()}),s},ct=(o,t={})=>{for(const e of o){const s=ot.resolve(e);Object.assign(t,JSON.parse(J.readFileSync(s).toString()))}return t};class ht{constructor(t,e,s,i){this.res=t,this.req=e,this.context=s,this.entry=i}async request(t={}){this.res.onAborted(()=>console.log("Abort is SSR handler"));const e=this.req.getQuery(),s=this.req.getUrl()+(e?`?${e}`:""),i=y.getExt(s);if(y.extensions.includes(i)){await y.staticBody(this.res,this.req,"./dist/client");return}const r=this.context.ssrManifest||this.context.manifest,a=this.context.manifest,n={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((h,c)=>n.headers[h]=c);try{const h=`${n.protocol}://${n.hostname}${n.url}`;let c,u=null;this.context.memcached&&(u=await this.context.memcached.getPage(h)),u?(c=u.data.toString(),n.responseHeaders=u.headers):({html:c}=await this.entry(s,{manifest:a,ssrManifest:r,res:this.res,req:this.req,context:n}),n.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(h,n.headers,c,n.memcache)),this.res.cork(()=>{this.res.writeStatus(x.codeToStatus(n.statusCode)),Object.keys(n.responseHeaders).map(g=>this.res.writeHeader(g,n.responseHeaders[g])),this.res.end(c)})}catch(h){let c=x.codeToStatus(404),u=Object.assign({},n.responseHeaders||{}),g=h.message;h instanceof d.ApiError&&(c=x.codeToStatus(h.getStatusCode()),u=Object.assign(u,h.getHeaders()||{}),g=w.isObject(h.getData())&&Object.keys(h.getData()).length>0?JSON.stringify(h.getData()):g),this.res.cork(()=>{this.res.writeStatus(c),Object.keys(u).map(b=>this.res.writeHeader(b,u[b])),this.res.end(g)})}}}const ut=async(o,t,e)=>(await o.poolQuery({sql:`
1
+ "use strict";var d=require("./ApiError.js"),x=require("./Server.js"),$=require("./Jwt-CDdbxwvH.js"),H=require("crypto"),Y=require("util"),v=require("./Memcached.js"),P=require("./jsonBody.js"),A=require("stream"),B=require("./urlencodedBody.js"),M=require("./multipartBody.js"),Z=require("./readConfig.js"),tt=require("./readConfigSync.js"),W=require("./cookieParse.js"),N=require("./cookieString.js"),_=require("./staticBody.js"),et=require("fs"),D=require("path"),w=require("easy-ash"),st=require("querystring"),O=require("xml-js"),ot=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(et),it=j(D),nt=j(ot);const{subtle:T}=H.webcrypto;class rt{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),i=await this.signString(`${e}.${s}`);return`${e}.${s}.${i}`}decode(t){const e=(t||"").split("."),s=$.fromBase64url(e[0]),i=$.fromBase64url(e[1]);return{head:s,body:i}}async signString(t){const e=new Y.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 at=o=>{const t=(o||"").split("."),e=$.fromBase64url(t[0]),s=$.fromBase64url(t[1]);return{head:e,body:s}},L=o=>new Promise((t,e)=>{ct(o,s=>t(s),()=>{e(new d.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function ct(o,t,e){let s=Buffer.from([]);o.onData((i,r)=>{s=Buffer.concat([s,Buffer.from(i)]),r&&t(s.toString())}),o.onAborted(e)}const k=o=>new Promise((t,e)=>{ht(o,s=>t(s),()=>{e(new d.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function ht(o,t,e){let s=Buffer.from([]);o.onData((i,r)=>{s=Buffer.concat([s,Buffer.from(i)]),r&&t(s)}),o.onAborted(e)}const C=(o,t,e=!0)=>{o.onAborted(()=>new d.ApiError({message:"Connection aborted",code:1,statusCode:404}));const s=new A.PassThrough;return s.headers={},t.forEach((i,r)=>s.headers[i]=r),o.onData((i,r)=>{s.write(Buffer.from(Buffer.from(i))),e&&s.resume(),r&&s.end()}),s},ut=(o,t={})=>{for(const e of o){const s=it.resolve(e);Object.assign(t,JSON.parse(J.readFileSync(s).toString()))}return t};class dt{constructor(t,e,s,i){this.res=t,this.req=e,this.context=s,this.entry=i}async request(t={}){this.res.onAborted(()=>console.log("Abort is SSR handler"));const e=this.req.getQuery(),s=this.req.getUrl()+(e?`?${e}`:""),i=_.getExt(s);if(_.extensions.includes(i)){await _.staticBody(this.res,this.req,"./dist/client");return}const r=this.context.ssrManifest||this.context.manifest,a=this.context.manifest,n={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((h,c)=>n.headers[h]=c);try{const h=`${n.protocol}://${n.hostname}${n.url}`;let c,u=null;this.context.memcached&&(u=await this.context.memcached.getPage(h)),u?(c=u.data.toString(),n.responseHeaders=u.headers):({html:c}=await this.entry(s,{manifest:a,ssrManifest:r,res:this.res,req:this.req,context:n}),n.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(h,n.headers,c,n.memcache)),this.res.cork(()=>{this.res.writeStatus(x.codeToStatus(n.statusCode)),Object.keys(n.responseHeaders).map(g=>this.res.writeHeader(g,n.responseHeaders[g])),this.res.end(c)})}catch(h){let c=x.codeToStatus(404),u=Object.assign({},n.responseHeaders||{}),g=h.message;h instanceof d.ApiError&&(c=x.codeToStatus(h.getStatusCode()),u=Object.assign(u,h.getHeaders()||{}),g=w.isObject(h.getData())&&Object.keys(h.getData()).length>0?JSON.stringify(h.getData()):g),this.res.cork(()=>{this.res.writeStatus(c),Object.keys(u).map(p=>this.res.writeHeader(p,u[p])),this.res.end(g)})}}}const lt=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,
@@ -17,7 +17,7 @@
17
17
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
18
18
  LEFT JOIN app_actions a ON a.id = s.app_actions_id
19
19
  WHERE c.name = :name AND s.name = :subaction
20
- `,namedPlaceholders:!0},{name:t,subaction:e}))?.[0],dt=async o=>(await o.poolQuery(`
20
+ `,namedPlaceholders:!0},{name:t,subaction:e}))?.[0],mt=async o=>(await o.poolQuery(`
21
21
  SELECT c.id AS controller_id,
22
22
  c.name AS controller_name,
23
23
  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),{}),lt=async(o,t,e,s,i="",r=3600)=>{const a=`${i}::routes::controllers`,n=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(n)?c[n]:void 0}else{const c=await dt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),r),(c||{}).hasOwnProperty(n)?c[n]:void 0}},L=async(o,t,e,s,i,r="",a=3600)=>{let n;if(i&&i.isClient()&&i.isConnectedServers()?n=await lt(o,e,s,i,r,a):n=await ut(o,e,s),!n)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(n?.action_method||"").split(",").map(c=>c.trim());if(n.controller_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!n.action_id)throw new d.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(n.action_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Action ${n.action_name} not active in site schema`});if(!n.subaction_id)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(n.subaction_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(n.subaction_is_check_method!==0&&n.action_method!=="any"&&!h.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${n.action_name} allow only ${n.action_method} method`});return{controller:{id:+n.controller_id,name:n.controller_name,isActive:!!n.controller_is_active,isSitemap:!!n.controller_is_sitemap},action:{id:+n.action_id,name:n.action_name,isActive:!!n.action_is_active,method:n.action_method},subaction:{id:+n.subaction_id,name:n.subaction_name,isPermission:!!n.subaction_is_permission,isCheckMethod:!!n.subaction_is_check_method,isLog:!!n.subaction_is_log,isActive:!!n.subaction_is_active,isSync:!1}}},mt=async o=>{const t={},e={};return(await o.poolQuery(`
38
+ `)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),ft=async(o,t,e,s,i="",r=3600)=>{const a=`${i}::routes::controllers`,n=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(n)?c[n]:void 0}else{const c=await mt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),r),(c||{}).hasOwnProperty(n)?c[n]:void 0}},I=async(o,t,e,s,i,r="",a=3600)=>{let n;if(i&&i.isClient()&&i.isConnectedServers()?n=await ft(o,e,s,i,r,a):n=await lt(o,e,s),!n)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(n?.action_method||"").split(",").map(c=>c.trim());if(n.controller_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!n.action_id)throw new d.ApiError({statusCode:404,code:11,message:"Action not found in site schema"});if(n.action_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Action ${n.action_name} not active in site schema`});if(!n.subaction_id)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(n.subaction_is_active!==1)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(n.subaction_is_check_method!==0&&n.action_method!=="any"&&!h.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${n.action_name} allow only ${n.action_method} method`});return{controller:{id:+n.controller_id,name:n.controller_name,isActive:!!n.controller_is_active,isSitemap:!!n.controller_is_sitemap},action:{id:+n.action_id,name:n.action_name,isActive:!!n.action_is_active,method:n.action_method},subaction:{id:+n.subaction_id,name:n.subaction_name,isPermission:!!n.subaction_is_permission,isCheckMethod:!!n.subaction_is_check_method,isLog:!!n.subaction_is_log,isActive:!!n.subaction_is_active,isSync:!1}}},gt=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 i=o.controllers.find(h=>h.name===e);if(!i)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let r=i.subactions.find(h=>h.name===s);if(!r)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(r=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},r),!r.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===r.action);if(!a)throw new d.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 d.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const n=(a?.method||"").split(",").map(h=>h.trim());if(r.isCheckMethod&&a.method!=="any"&&!n.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:r.id,name:r.name,isPermission:r.isPermission,isCheckMethod:r.isCheckMethod,isLog:r.isLog,isActive:r.isActive,isSync:!!r.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class ft{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 d.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(i=>({name:i.name,method:i.method,component:i.component,binding:i.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,et.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,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,$di:{},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((c,u)=>this.contextWeb.headers[c]=u);const r=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.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,i.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(),u=new c;if(this.injectContext(u),i.subaction in u)e=await u[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.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 u=await c.getPage(this.memcachedKey);if(u){const{data:g,headers:b}=u;this.success({body:g.toString(),headers:b,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(r.indexOf("application/json")!==-1||r.indexOf("text/json")!==-1)Object.assign(i,await P.jsonBody(this.res));else if(r.indexOf("multipart/form-data")!==-1)Object.assign(i,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(r.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await B.urlencodedBody(this.res));else if(r.indexOf("application/xml")!==-1||r.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),u=O.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,u||{})}else r.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):r.indexOf("binary")!==-1?await new Promise(c=>{const u=C(this.res,this.req),g=it.tmpdir(),b="./body_"+R.randomBytes(32).toString("hex"),_=D.resolve(g,b),l=J.createWriteStream(_);u.pipe(l),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:_}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await L(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.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}),this.route.binding){const c=await this.importBinding(),u=new c;this.injectContext(u),this.contextWeb.$di=await this.initComponent(u)}const a=await this.importController(),n=new a;this.injectContext(n);const h=await this.initComponent(n);if(typeof h>"u")if(i.subaction in n)e=await n[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importBinding(){let t=this.route.binding.default||this.route.binding;if(w.isClass(t)||(t=(await this.route.binding()).default),typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return t}async importController(){let t=this.route.component.default||this.route.component;if(w.isClass(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}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 d.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 i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof A.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,r=x.codeToStatus(i),a=!s&&!e&&w.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===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(r),this.writeHeaders(t.headers),a.on("data",n=>{this.res.write(n)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(r),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d.ApiError&&t.getData()instanceof A.Stream;let s=x.codeToStatus(404),i=this.defaultResponse.headers,r=t.message;if(t instanceof d.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x.codeToStatus(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?r=t.getData():r=w.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(i),r.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(r)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):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,i=e.message?e.message:"Api request error",r=e.statusCode?e.statusCode:404,a=e.data?e.data:{},n=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:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?n:{}},statusCode:r}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:O.js2xml(Object.assign(s,{body:{...i.body}}),I),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:O.js2xml(Object.assign(s,{body:{...i.body}}),I),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,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:(r,a)=>this.setResponseHeader(r,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const i=["init",...s.$inits||[]];for(const r of i)s[r]&&await s[r]();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}getRemote(){return this.$context.remote}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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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)}}class F{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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const gt=async(o,t,e={},s)=>{const i=async n=>{const h=[...new Set(["init",...n.$inits||[]])];for(const c of h)if(n[c]){const u=await n[c]();if(u)return u}},r=(n,h)=>{"$inject"in n&&n.$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 r(a,t),t.$initResponse=await i(a),a;if(a instanceof U||a instanceof F){const n=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return r(n,t),t.$initResponse=await i(n),n.getModel()}else throw new d.ApiError({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},f=Symbol("arguments"),K=Symbol("connections"),H=Symbol("response"),Q=Symbol("init"),V=Symbol("logger"),X=Symbol("filters"),pt=o=>o.charAt(0).toUpperCase()+o.slice(1);function bt(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const r=Object.getPrototypeOf(i);r&&t(s,r)};function e(s){return t(s,o),s}return e}const m=(o,t,e,s,i,r)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:r},Reflect.defineMetadata(o,a,t,e)};function xt(){return function(o,t,e){m(f,o,t,e,"request")}}function $t(){return function(o,t,e){m(f,o,t,e,"context")}}function _t(){return function(o,t,e){m(f,o,t,e,"config")}}function yt(){return function(o,t,e){m(f,o,t,e,"method")}}function wt(){return function(o,t,e){m(f,o,t,e,"remote")}}function St(){return function(o,t,e){m(f,o,t,e,"cookies")}}function At(){return function(o,t,e){m(f,o,t,e,"hostname")}}function Ct(){return function(o,t,e){m(f,o,t,e,"url")}}function vt(){return function(o,t,e){m(f,o,t,e,"protocol")}}function Ot(){return function(o,t,e){m(f,o,t,e,"db")}}function jt(){return function(o,t,e){m(f,o,t,e,"headers")}}function kt(){return function(o,t,e){m(f,o,t,e,"controller")}}function qt(){return function(o,t,e){m(f,o,t,e,"action")}}function Et(){return function(o,t,e){m(f,o,t,e,"subaction")}}function Ht(){return function(o,t,e){m(f,o,t,e,"body")}}function Rt(){return function(o,t,e){m(f,o,t,e,"stream")}}function Pt(){return function(o,t,e){m(f,o,t,e,"home")}}function Bt(o="home"){return function(t,e,s){m(f,t,e,s,"pool",o)}}function Mt(o="home"){return function(t,e,s){m(K,t,e,s,"connection",o)}}function Wt(o={}){return function(t,e,s){m(H,t,e,0,"json",o)}}function Nt(o={}){return function(t,e,s){m(H,t,e,0,"xml",o)}}function Dt(o){return function(t,e,s){m(V,t,e,o,"logger",o)}}function Jt(o){return function(t,e,s){const i={format:"json"},r=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],n=[],h=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(K,t,e)||{},u=Reflect.getOwnMetadata(V,t,e)||{},g=Reflect.getOwnMetadata(H,t,e)?.[0]||{type:"json",params:{}},b=Reflect.getOwnMetadata(Q,t,e)?.[0]||{type:"",params:{}},_=(Reflect.getOwnMetadata(X,t,e)?.[0]||{type:"allow",params:[]}).params;if(_.length&&!_.includes(this.getMethod())&&this.getMethod()!=="any")throw new d.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${_.join(",")} methods`});for(const l in h){if(!h.hasOwnProperty(l))continue;const p=`get${pt(h[l].type)}`;a[+l]=this[p](h[l].params)}for(const l in c)c.hasOwnProperty(l)&&(c[l].type,a[+l]=await this.getDb()[c[l].params].getConnection(),n.push(a[+l]));try{let l=await r.apply(this,a),p;if(Array.isArray(l)&&([l,p]=l),b.type!=="init")return i.format==="xml"||g.type==="xml"?this.successXml(l,Object.assign(g.params,p||{})):i.format==="buffer"?this.successBuffer(l,Object.assign(g.params,p||{})):this.success(l,Object.assign(g.params,p||{}))}catch(l){await Promise.all([...n.map(S=>S.rollback())]);let p;i.format==="xml"||g.type==="xml"?p=this.errorXml(l):p=this.error(l);for(const S in u){if(!u.hasOwnProperty(S))continue;const z=u[S].params;await this[z].error(l,{response:w.omit(p?.body||{},["stack"])})}return p}finally{await Promise.all([...n.map(l=>l.release())])}}}}function Tt(){return function(o,t,e){m(Q,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Lt(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){m(X,t,e,0,"allow",o)}}function It(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Ut={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:P.jsonBody,rawBody:k,streamBody:C,urlencodedBody:B.urlencodedBody,multipartBody:M.multipartBody,readConfig:Y.readConfig,readConfigSync:Z.readConfigSync,staticBody:y.staticBody,extensions:y.extensions,getExt:y.getExt,jwtDecode:rt,readJsonConfigsSync:ct};exports.ApiError=d.ApiError,exports.Server=x.Server,exports.codeToStatus=x.codeToStatus,exports.Jwt=$.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=nt,exports.Binding=F,exports.Controller=E,exports.Model=U,exports.Ssr=ht,exports.Web=ft,exports.action=qt,exports.allow=Lt,exports.body=Ht,exports.config=_t,exports.connection=Mt,exports.context=$t,exports.controller=kt,exports.cookies=St,exports.db=Ot,exports.headers=jt,exports.helpers=Ut,exports.home=Pt,exports.hostname=At,exports.http=Jt,exports.init=Tt,exports.inject=It,exports.json=Wt,exports.logerror=Dt,exports.method=yt,exports.mixin=bt,exports.mount=gt,exports.pool=Bt,exports.protocol=vt,exports.remote=wt,exports.request=xt,exports.selectControllersSchema=mt,exports.stream=Rt,exports.subaction=Et,exports.url=Ct,exports.xml=Nt;
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 i=o.controllers.find(h=>h.name===e);if(!i)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not found is site schema`});if(i=Object.assign({isActive:!0,isSitemap:!1},i),!i.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let r=i.subactions.find(h=>h.name===s);if(!r)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(r=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},r),!r.isActive)throw new d.ApiError({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===r.action);if(!a)throw new d.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 d.ApiError({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const n=(a?.method||"").split(",").map(h=>h.trim());if(r.isCheckMethod&&a.method!=="any"&&!n.includes(t))throw new d.ApiError({statusCode:404,code:11,message:`Controller ${e} action ${a.name} allow only ${a.method} method`});return{controller:{id:i.id,name:i.name,isActive:i.isActive,isSitemap:i.isSitemap},subaction:{id:r.id,name:r.name,isPermission:r.isPermission,isCheckMethod:r.isCheckMethod,isLog:r.isLog,isActive:r.isActive,isSync:!!r.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class pt{constructor(t,e,s,i={}){this.opts={},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.opts=i,this.res.onAborted(()=>new d.ApiError({message:"The connection was close",code:1,statusCode:404})),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(r=>({name:r.name,method:r.method,component:r.component,binding:r.binding})))}setDefaultRequest(t){return Object.assign(this.defaultRequest,t),this}async request(t={}){let e={};try{const s=this.req.getQuery(),i=Object.assign({},this.defaultRequest,t,st.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),getRequest:()=>i,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,$di:{},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((c,u)=>this.contextWeb.headers[c]=u);const r=this.contextWeb.headers["content-type"]||"application/json";if(i.controller&&i.subaction&&this.context.schema&&(this.route=this.findRoute(i.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,i.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(),u=new c;if(this.injectContext(u),i.subaction in u)e=await u[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.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 u=await c.getPage(this.memcachedKey);if(u){const{data:g,headers:p}=u;this.success({body:g.toString(),headers:p,statusCode:200})}}}if(i.controller=i.controller||this.defaultControllerSubaction.controller,i.subaction=i.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(r.indexOf("application/json")!==-1||r.indexOf("text/json")!==-1)if(this.opts.raw){const c=await L(this.res);let u={};try{u=JSON.parse(c)}catch{}Object.assign(i,u),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(i,await P.jsonBody(this.res));else if(r.indexOf("multipart/form-data")!==-1)Object.assign(i,await M.multipartBody(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:i.files});else if(r.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(i,await B.urlencodedBody(this.res));else if(r.indexOf("application/xml")!==-1||r.indexOf("text/xml")!==-1){const c=(await k(this.res)).toString(),u=O.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(i,u||{})}else r.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:C(this.res,this.req,!1)}):r.indexOf("binary")!==-1?await new Promise(c=>{const u=C(this.res,this.req),g=nt.tmpdir(),p="./body_"+H.randomBytes(32).toString("hex"),y=D.resolve(g,p),l=J.createWriteStream(y);u.pipe(l),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:y}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await k(this.res)});if(this.route=this.findRoute(i.controller),Object.assign(this.contextWeb,this.context.schema?q(this.context.schema,this.contextWeb.method,this.route.name,i.subaction):await I(this.contextWeb.db.home,this.contextWeb.method,this.route.name,i.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}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const u of c){const g=await this.importBinding(u),p=new g;this.injectContext(p),Object.assign(this.contextWeb.$di,await this.initComponent(p))}}const a=await this.importController(),n=new a;this.injectContext(n);const h=await this.initComponent(n);if(typeof h>"u")if(i.subaction in n)e=await n[i.subaction]();else throw new d.ApiError({statusCode:404,code:13,message:`Method ${i.subaction} not found in ${i.controller} route`});else e=h;e=Object.assign({},this.defaultResponse,e),this.success(e)}catch(s){this.error(s)}}async importBinding(t){let e=t.default||t;if(w.isClass(e)||(e=(await t()).default),typeof e!="function")throw new d.ApiError({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(w.isClass(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new d.ApiError({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}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 d.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 i=await t[s]();if(i)return i}}success(t){const e=t.body instanceof A.Stream,s=t.body instanceof Uint8Array,i=t.statusCode||200,r=x.codeToStatus(i),a=!s&&!e&&w.isObject(t.body)?JSON.stringify(t.body):t.body;!s&&!e&&["get","head"].includes(this.contextWeb.method)&&i===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(r),this.writeHeaders(t.headers),a.on("data",n=>{this.res.write(n)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(r),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d.ApiError&&t.getData()instanceof A.Stream;let s=x.codeToStatus(404),i=this.defaultResponse.headers,r=t.message;if(t instanceof d.ApiError){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x.codeToStatus(t.getStatusCode()),i=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?r=t.getData():r=w.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(i),r.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(i),this.res.end(r)})}writeHeaders(t){Object.entries(t).forEach(([e,s])=>{Array.isArray(s)?s.forEach(i=>this.res.writeHeader(e,i)):this.res.writeHeader(e,s)})}}const U={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,i=e.message?e.message:"Api request error",r=e.statusCode?e.statusCode:404,a=e.data?e.data:{},n=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:i,code:s,data:a,stack:process.env.NODE_ENV!=="production"?e.stack:"",response:process.env.NODE_ENV!=="production"?n:{}},statusCode:r}}successXml(t={},e){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.success(t,e);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,e?.headers||{}),body:O.js2xml(Object.assign(s,{body:{...i.body}}),U),memcache:i.memcache}}errorXml(t){const e=t,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},i=this.error(e);return{headers:Object.assign({"content-type":"application/xml"},e.headers),body:O.js2xml(Object.assign(s,{body:{...i.body}}),U),statusCode:i.statusCode}}async $create(t,...e){const s=new t(...e);"$inject"in s&&s.$inject({url:this.$context.url,method:this.$context.method,remote:this.$context.remote,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:(r,a)=>this.setResponseHeader(r,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const i=["init",...s.$inits||[]];for(const r of i)s[r]&&await s[r]();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}getRemote(){return this.$context.remote}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 F{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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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)}}class K{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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const bt=async(o,t,e={},s)=>{const i=async n=>{const h=[...new Set(["init",...n.$inits||[]])];for(const c of h)if(n[c]){const u=await n[c]();if(u)return u}},r=(n,h)=>{"$inject"in n&&n.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await I(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 r(a,t),t.$initResponse=await i(a),a;if(a instanceof F||a instanceof K){const n=new class extends E{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return r(n,t),t.$initResponse=await i(n),n.getModel()}else throw new d.ApiError({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},f=Symbol("arguments"),Q=Symbol("connections"),R=Symbol("response"),V=Symbol("init"),X=Symbol("logger"),z=Symbol("filters"),xt=o=>o.charAt(0).toUpperCase()+o.slice(1);function $t(o){const t=(s,i)=>{for(const a of Reflect.ownKeys(i))Object.defineProperty(s.prototype,a,{value:i[a]});const r=Object.getPrototypeOf(i);r&&t(s,r)};function e(s){return t(s,o),s}return e}const m=(o,t,e,s,i,r)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:i,params:r},Reflect.defineMetadata(o,a,t,e)};function yt(){return function(o,t,e){m(f,o,t,e,"request")}}function _t(){return function(o,t,e){m(f,o,t,e,"context")}}function wt(){return function(o,t,e){m(f,o,t,e,"config")}}function St(){return function(o,t,e){m(f,o,t,e,"method")}}function At(){return function(o,t,e){m(f,o,t,e,"remote")}}function Ct(){return function(o,t,e){m(f,o,t,e,"cookies")}}function vt(){return function(o,t,e){m(f,o,t,e,"hostname")}}function Ot(){return function(o,t,e){m(f,o,t,e,"url")}}function jt(){return function(o,t,e){m(f,o,t,e,"protocol")}}function kt(){return function(o,t,e){m(f,o,t,e,"db")}}function qt(){return function(o,t,e){m(f,o,t,e,"headers")}}function Et(){return function(o,t,e){m(f,o,t,e,"controller")}}function Rt(){return function(o,t,e){m(f,o,t,e,"action")}}function Ht(){return function(o,t,e){m(f,o,t,e,"subaction")}}function Pt(){return function(o,t,e){m(f,o,t,e,"body")}}function Bt(){return function(o,t,e){m(f,o,t,e,"stream")}}function Mt(){return function(o,t,e){m(f,o,t,e,"home")}}function Wt(o="home"){return function(t,e,s){m(f,t,e,s,"pool",o)}}function Nt(o="home"){return function(t,e,s){m(Q,t,e,s,"connection",o)}}function Dt(o={}){return function(t,e,s){m(R,t,e,0,"json",o)}}function Jt(o={}){return function(t,e,s){m(R,t,e,0,"xml",o)}}function Tt(o){return function(t,e,s){m(X,t,e,o,"logger",o)}}function Lt(o){return function(t,e,s){const i={format:"json"},r=s.value;s.value=async function(){o&&Object.assign(i,await o.apply(this)||{});const a=[],n=[],h=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(Q,t,e)||{},u=Reflect.getOwnMetadata(X,t,e)||{},g=Reflect.getOwnMetadata(R,t,e)?.[0]||{type:"json",params:{}},p=Reflect.getOwnMetadata(V,t,e)?.[0]||{type:"",params:{}},y=(Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"allow",params:[]}).params;if(y.length&&!y.includes(this.getMethod())&&this.getMethod()!=="any")throw new d.ApiError({statusCode:404,code:11,message:`Controller ${this.getController().name} subaction ${this.getSubaction().name} allow only ${y.join(",")} methods`});for(const l in h){if(!h.hasOwnProperty(l))continue;const b=`get${xt(h[l].type)}`;a[+l]=this[b](h[l].params)}for(const l in c)c.hasOwnProperty(l)&&(c[l].type,a[+l]=await this.getDb()[c[l].params].getConnection(),n.push(a[+l]));try{let l=await r.apply(this,a),b;if(Array.isArray(l)&&([l,b]=l),p.type!=="init")return i.format==="xml"||g.type==="xml"?this.successXml(l,Object.assign(g.params,b||{})):i.format==="buffer"?this.successBuffer(l,Object.assign(g.params,b||{})):this.success(l,Object.assign(g.params,b||{}))}catch(l){await Promise.all([...n.map(S=>S.rollback())]);let b;i.format==="xml"||g.type==="xml"?b=this.errorXml(l):b=this.error(l);for(const S in u){if(!u.hasOwnProperty(S))continue;const G=u[S].params;await this[G].error(l,{response:w.omit(b?.body||{},["stack"])})}return b}finally{await Promise.all([...n.map(l=>l.release())])}}}}function It(){return function(o,t,e){m(V,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Ut(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){m(z,t,e,0,"allow",o)}}function Ft(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Kt={cookieParse:W.cookieParse,cookieString:N.cookieString,jsonBody:P.jsonBody,jsonBodyRaw:L,rawBody:k,streamBody:C,urlencodedBody:B.urlencodedBody,multipartBody:M.multipartBody,readConfig:Z.readConfig,readConfigSync:tt.readConfigSync,staticBody:_.staticBody,extensions:_.extensions,getExt:_.getExt,jwtDecode:at,readJsonConfigsSync:ut};exports.ApiError=d.ApiError,exports.Server=x.Server,exports.codeToStatus=x.codeToStatus,exports.Jwt=$.Jwt,exports.Memcached=v.Memcached,exports.AsyncJwt=rt,exports.Binding=K,exports.Controller=E,exports.Model=F,exports.Ssr=dt,exports.Web=pt,exports.action=Rt,exports.allow=Ut,exports.body=Pt,exports.config=wt,exports.connection=Nt,exports.context=_t,exports.controller=Et,exports.cookies=Ct,exports.db=kt,exports.headers=qt,exports.helpers=Kt,exports.home=Mt,exports.hostname=vt,exports.http=Lt,exports.init=It,exports.inject=Ft,exports.json=Dt,exports.logerror=Tt,exports.method=St,exports.mixin=$t,exports.mount=bt,exports.pool=Wt,exports.protocol=jt,exports.remote=At,exports.request=yt,exports.selectControllersSchema=gt,exports.stream=Bt,exports.subaction=Ht,exports.url=Ot,exports.xml=Jt;
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 ye}from"./Server.mjs";import{t as H,f as y,u as Z}from"./Jwt-7tQL-rwa.js";import{J as Se}from"./Jwt-7tQL-rwa.js";import tt,{webcrypto as et}from"crypto";import{TextEncoder as st}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 M}from"./multipartBody.mjs";import{readConfig as ot}from"./readConfig.mjs";import{readConfigSync as nt}from"./readConfigSync.mjs";import{cookieParse as B}from"./cookieParse.mjs";import{cookieString as E}from"./cookieString.mjs";import{getExt as N,extensions as D,staticBody as J}from"./staticBody.mjs";import*as T from"fs";import*as it from"path";import rt from"path";import{isObject as C,isClass as L,omit as at}from"easy-ash";import ct from"querystring";import A from"xml-js";import*as ht from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:I}=et;class ut{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=H({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=H(t),n=await this.signString(`${e}.${s}`);return`${e}.${s}.${n}`}decode(t){const e=(t||"").split("."),s=y(e[0]),n=y(e[1]);return{head:s,body:n}}async signString(t){const e=new st,s=await I.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return Z(Buffer.from(await I.sign("HMAC",s,e.encode(t))).toString("base64"))}}const dt=o=>{const t=(o||"").split("."),e=y(t[0]),s=y(t[1]);return{head:e,body:s}},O=o=>new Promise((t,e)=>{mt(o,s=>t(s),()=>{e(new d({message:"Can`t parse request",code:1,statusCode:404}))})});function mt(o,t,e){let s=Buffer.from([]);o.onData((n,r)=>{s=Buffer.concat([s,Buffer.from(n)]),r&&t(s)}),o.onAborted(e)}const w=(o,t,e=!0)=>{o.onAborted(()=>new d({message:"Connection aborted",code:1,statusCode:404}));const s=new q;return s.headers={},t.forEach((n,r)=>s.headers[n]=r),o.onData((n,r)=>{s.write(Buffer.from(Buffer.from(n))),e&&s.resume(),r&&s.end()}),s},lt=(o,t={})=>{for(const e of o){const s=it.resolve(e);Object.assign(t,JSON.parse(T.readFileSync(s).toString()))}return t};class ft{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=N(s);if(D.includes(n)){await J(this.res,this.req,"./dist/client");return}const r=this.context.ssrManifest||this.context.manifest,a=this.context.manifest,i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:B(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((h,c)=>i.headers[h]=c);try{const h=`${i.protocol}://${i.hostname}${i.url}`;let c,u=null;this.context.memcached&&(u=await this.context.memcached.getPage(h)),u?(c=u.data.toString(),i.responseHeaders=u.headers):({html:c}=await this.entry(s,{manifest:a,ssrManifest:r,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(h,i.headers,c,i.memcache)),this.res.cork(()=>{this.res.writeStatus(x(i.statusCode)),Object.keys(i.responseHeaders).map(g=>this.res.writeHeader(g,i.responseHeaders[g])),this.res.end(c)})}catch(h){let c=x(404),u=Object.assign({},i.responseHeaders||{}),g=h.message;h instanceof d&&(c=x(h.getStatusCode()),u=Object.assign(u,h.getHeaders()||{}),g=C(h.getData())&&Object.keys(h.getData()).length>0?JSON.stringify(h.getData()):g),this.res.cork(()=>{this.res.writeStatus(c),Object.keys(u).map(b=>this.res.writeHeader(b,u[b])),this.res.end(g)})}}}const gt=async(o,t,e)=>(await o.poolQuery({sql:`
1
+ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as x}from"./Server.mjs";import{Server as Se}from"./Server.mjs";import{t as R,f as y,u as tt}from"./Jwt-7tQL-rwa.js";import{J as Ae}from"./Jwt-7tQL-rwa.js";import et,{webcrypto as st}from"crypto";import{TextEncoder as ot}from"util";import{Memcached as S}from"./Memcached.mjs";import{jsonBody as H}from"./jsonBody.mjs";import{PassThrough as q,Stream as P}from"stream";import{urlencodedBody as B}from"./urlencodedBody.mjs";import{multipartBody as W}from"./multipartBody.mjs";import{readConfig as nt}from"./readConfig.mjs";import{readConfigSync as it}from"./readConfigSync.mjs";import{cookieParse as M}from"./cookieParse.mjs";import{cookieString as E}from"./cookieString.mjs";import{getExt as N,extensions as D,staticBody as J}from"./staticBody.mjs";import*as T from"fs";import*as rt from"path";import at from"path";import{isObject as C,isClass as L,omit as ct}from"easy-ash";import ht from"querystring";import A from"xml-js";import*as ut from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:I}=st;class dt{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=R({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=R(t),n=await this.signString(`${e}.${s}`);return`${e}.${s}.${n}`}decode(t){const e=(t||"").split("."),s=y(e[0]),n=y(e[1]);return{head:s,body:n}}async signString(t){const e=new ot,s=await I.importKey("raw",e.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return tt(Buffer.from(await I.sign("HMAC",s,e.encode(t))).toString("base64"))}}const mt=o=>{const t=(o||"").split("."),e=y(t[0]),s=y(t[1]);return{head:e,body:s}},U=o=>new Promise((t,e)=>{lt(o,s=>t(s),()=>{e(new d({message:"Can`t parse request",code:1,statusCode:404}))})});function lt(o,t,e){let s=Buffer.from([]);o.onData((n,r)=>{s=Buffer.concat([s,Buffer.from(n)]),r&&t(s.toString())}),o.onAborted(e)}const O=o=>new Promise((t,e)=>{ft(o,s=>t(s),()=>{e(new d({message:"Can`t parse request",code:1,statusCode:404}))})});function ft(o,t,e){let s=Buffer.from([]);o.onData((n,r)=>{s=Buffer.concat([s,Buffer.from(n)]),r&&t(s)}),o.onAborted(e)}const w=(o,t,e=!0)=>{o.onAborted(()=>new d({message:"Connection aborted",code:1,statusCode:404}));const s=new q;return s.headers={},t.forEach((n,r)=>s.headers[n]=r),o.onData((n,r)=>{s.write(Buffer.from(Buffer.from(n))),e&&s.resume(),r&&s.end()}),s},gt=(o,t={})=>{for(const e of o){const s=rt.resolve(e);Object.assign(t,JSON.parse(T.readFileSync(s).toString()))}return t};class pt{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=N(s);if(D.includes(n)){await J(this.res,this.req,"./dist/client");return}const r=this.context.ssrManifest||this.context.manifest,a=this.context.manifest,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((h,c)=>i.headers[h]=c);try{const h=`${i.protocol}://${i.hostname}${i.url}`;let c,u=null;this.context.memcached&&(u=await this.context.memcached.getPage(h)),u?(c=u.data.toString(),i.responseHeaders=u.headers):({html:c}=await this.entry(s,{manifest:a,ssrManifest:r,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(h,i.headers,c,i.memcache)),this.res.cork(()=>{this.res.writeStatus(x(i.statusCode)),Object.keys(i.responseHeaders).map(g=>this.res.writeHeader(g,i.responseHeaders[g])),this.res.end(c)})}catch(h){let c=x(404),u=Object.assign({},i.responseHeaders||{}),g=h.message;h instanceof d&&(c=x(h.getStatusCode()),u=Object.assign(u,h.getHeaders()||{}),g=C(h.getData())&&Object.keys(h.getData()).length>0?JSON.stringify(h.getData()):g),this.res.cork(()=>{this.res.writeStatus(c),Object.keys(u).map(p=>this.res.writeHeader(p,u[p])),this.res.end(g)})}}}const bt=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,
@@ -17,7 +17,7 @@ import{ApiError as d}from"./ApiError.mjs";import{codeToStatus as x}from"./Server
17
17
  INNER JOIN app_subactions s ON s.app_controllers_id = c.id
18
18
  LEFT JOIN app_actions a ON a.id = s.app_actions_id
19
19
  WHERE c.name = :name AND s.name = :subaction
20
- `,namedPlaceholders:!0},{name:t,subaction:e}))?.[0],pt=async o=>(await o.poolQuery(`
20
+ `,namedPlaceholders:!0},{name:t,subaction:e}))?.[0],xt=async o=>(await o.poolQuery(`
21
21
  SELECT c.id AS controller_id,
22
22
  c.name AS controller_name,
23
23
  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((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),bt=async(o,t,e,s,n="",r=3600)=>{const a=`${n}::routes::controllers`,i=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(i)?c[i]:void 0}else{const c=await pt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),r),(c||{}).hasOwnProperty(i)?c[i]:void 0}},U=async(o,t,e,s,n,r="",a=3600)=>{let i;if(n&&n.isClient()&&n.isConnectedServers()?i=await bt(o,e,s,n,r,a):i=await gt(o,e,s),!i)throw new d({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(i?.action_method||"").split(",").map(c=>c.trim());if(i.controller_is_active!==1)throw new d({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!i.action_id)throw new d({statusCode:404,code:11,message:"Action not found in site schema"});if(i.action_is_active!==1)throw new d({statusCode:404,code:11,message:`Action ${i.action_name} not active in site schema`});if(!i.subaction_id)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(i.subaction_is_active!==1)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(i.subaction_is_check_method!==0&&i.action_method!=="any"&&!h.includes(t))throw new d({statusCode:404,code:11,message:`Controller ${e} action ${i.action_name} allow only ${i.action_method} method`});return{controller:{id:+i.controller_id,name:i.controller_name,isActive:!!i.controller_is_active,isSitemap:!!i.controller_is_sitemap},action:{id:+i.action_id,name:i.action_name,isActive:!!i.action_is_active,method:i.action_method},subaction:{id:+i.subaction_id,name:i.subaction_name,isPermission:!!i.subaction_is_permission,isCheckMethod:!!i.subaction_is_check_method,isLog:!!i.subaction_is_log,isActive:!!i.subaction_is_active,isSync:!1}}},xt=async o=>{const t={},e={};return(await o.poolQuery(`
38
+ `)).reduce((t,e)=>(t[`${e.controller_name}::${e.subaction_name}`]=e,t),{}),$t=async(o,t,e,s,n="",r=3600)=>{const a=`${n}::routes::controllers`,i=`${t}::${e}`,h=await s.getValue(a);if(h){const c=JSON.parse(h.toString());return(c||{}).hasOwnProperty(i)?c[i]:void 0}else{const c=await xt(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),r),(c||{}).hasOwnProperty(i)?c[i]:void 0}},F=async(o,t,e,s,n,r="",a=3600)=>{let i;if(n&&n.isClient()&&n.isConnectedServers()?i=await $t(o,e,s,n,r,a):i=await bt(o,e,s),!i)throw new d({statusCode:404,code:11,message:`Controller ${e} not found in site schema`});const h=(i?.action_method||"").split(",").map(c=>c.trim());if(i.controller_is_active!==1)throw new d({statusCode:404,code:11,message:`Controller ${e} not active in site schema`});if(!i.action_id)throw new d({statusCode:404,code:11,message:"Action not found in site schema"});if(i.action_is_active!==1)throw new d({statusCode:404,code:11,message:`Action ${i.action_name} not active in site schema`});if(!i.subaction_id)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(i.subaction_is_active!==1)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(i.subaction_is_check_method!==0&&i.action_method!=="any"&&!h.includes(t))throw new d({statusCode:404,code:11,message:`Controller ${e} action ${i.action_name} allow only ${i.action_method} method`});return{controller:{id:+i.controller_id,name:i.controller_name,isActive:!!i.controller_is_active,isSitemap:!!i.controller_is_sitemap},action:{id:+i.action_id,name:i.action_name,isActive:!!i.action_is_active,method:i.action_method},subaction:{id:+i.subaction_id,name:i.subaction_name,isPermission:!!i.subaction_is_permission,isCheckMethod:!!i.subaction_is_check_method,isLog:!!i.subaction_is_log,isActive:!!i.subaction_is_active,isSync:!1}}},_t=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 @@ 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=>{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)}},j=(o,t,e,s)=>{let n=o.controllers.find(h=>h.name===e);if(!n)throw new d({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 d({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let r=n.subactions.find(h=>h.name===s);if(!r)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(r=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},r),!r.isActive)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===r.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 i=(a?.method||"").split(",").map(h=>h.trim());if(r.isCheckMethod&&a.method!=="any"&&!i.includes(t))throw new d({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:r.id,name:r.name,isPermission:r.isPermission,isCheckMethod:r.isCheckMethod,isLog:r.isLog,isActive:r.isActive,isSync:!!r.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class $t{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 d({message:"The connection was close",code:1,statusCode:404})),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(n=>({name:n.name,method:n.method,component:n.component,binding:n.binding})))}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,ct.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),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,$di:{},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((c,u)=>this.contextWeb.headers[c]=u);const r=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:w(this.res,this.req,!1)});const c=this.importControllerSync(),u=new c;if(this.injectContext(u),n.subaction in u)e=await u[n.subaction]();else throw new d({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 S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const u=await c.getPage(this.memcachedKey);if(u){const{data:g,headers:b}=u;this.success({body:g.toString(),headers:b,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(r.indexOf("application/json")!==-1||r.indexOf("text/json")!==-1)Object.assign(n,await R(this.res));else if(r.indexOf("multipart/form-data")!==-1)Object.assign(n,await M(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:n.files});else if(r.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await W(this.res));else if(r.indexOf("application/xml")!==-1||r.indexOf("text/xml")!==-1){const c=(await O(this.res)).toString(),u=A.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,u||{})}else r.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)}):r.indexOf("binary")!==-1?await new Promise(c=>{const u=w(this.res,this.req),g=ht.tmpdir(),b="./body_"+tt.randomBytes(32).toString("hex"),$=rt.resolve(g,b),m=T.createWriteStream($);u.pipe(m),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:$}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await O(this.res)});if(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 U(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}),this.route.binding){const c=await this.importBinding(),u=new c;this.injectContext(u),this.contextWeb.$di=await this.initComponent(u)}const a=await this.importController(),i=new a;this.injectContext(i);const h=await this.initComponent(i);if(typeof h>"u")if(n.subaction in i)e=await i[n.subaction]();else throw new d({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 importBinding(){let t=this.route.binding.default||this.route.binding;if(L(t)||(t=(await this.route.binding()).default),typeof t!="function")throw new d({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return t}async importController(){let t=this.route.component.default||this.route.component;if(L(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){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 ${this.route.name} route`});return t}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 d({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 P,s=t.body instanceof Uint8Array,n=t.statusCode||200,r=x(n),a=!s&&!e&&C(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 S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(r),this.writeHeaders(t.headers),a.on("data",i=>{this.res.write(i)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(r),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d&&t.getData()instanceof P;let s=x(404),n=this.defaultResponse.headers,r=t.message;if(t instanceof d){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x(t.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?r=t.getData():r=C(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),r.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(r)})}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 F={compact:!0,ignoreComment:!0,spaces:4};class k{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return E(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",r=e.statusCode?e.statusCode:404,a=e.data?e.data:{},i=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"?i:{}},statusCode:r}}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:A.js2xml(Object.assign(s,{body:{...n.body}}),F),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:A.js2xml(Object.assign(s,{body:{...n.body}}),F),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,remote:this.$context.remote,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:(r,a)=>this.setResponseHeader(r,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const n=["init",...s.$inits||[]];for(const r of n)s[r]&&await s[r]();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 q().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}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 K{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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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)}}class Q{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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const _t=async(o,t,e={},s)=>{const n=async i=>{const h=[...new Set(["init",...i.$inits||[]])];for(const c of h)if(i[c]){const u=await i[c]();if(u)return u}},r=(i,h)=>{"$inject"in i&&i.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await U(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?j(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof k)return r(a,t),t.$initResponse=await n(a),a;if(a instanceof K||a instanceof Q){const i=new class extends k{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return r(i,t),t.$initResponse=await n(i),i.getModel()}else throw new d({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},f=Symbol("arguments"),V=Symbol("connections"),v=Symbol("response"),X=Symbol("init"),z=Symbol("logger"),G=Symbol("filters"),yt=o=>o.charAt(0).toUpperCase()+o.slice(1);function wt(o){const t=(s,n)=>{for(const a of Reflect.ownKeys(n))Object.defineProperty(s.prototype,a,{value:n[a]});const r=Object.getPrototypeOf(n);r&&t(s,r)};function e(s){return t(s,o),s}return e}const l=(o,t,e,s,n,r)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:n,params:r},Reflect.defineMetadata(o,a,t,e)};function St(){return function(o,t,e){l(f,o,t,e,"request")}}function Ct(){return function(o,t,e){l(f,o,t,e,"context")}}function At(){return function(o,t,e){l(f,o,t,e,"config")}}function Ot(){return function(o,t,e){l(f,o,t,e,"method")}}function jt(){return function(o,t,e){l(f,o,t,e,"remote")}}function kt(){return function(o,t,e){l(f,o,t,e,"cookies")}}function vt(){return function(o,t,e){l(f,o,t,e,"hostname")}}function Ht(){return function(o,t,e){l(f,o,t,e,"url")}}function Rt(){return function(o,t,e){l(f,o,t,e,"protocol")}}function qt(){return function(o,t,e){l(f,o,t,e,"db")}}function Pt(){return function(o,t,e){l(f,o,t,e,"headers")}}function Wt(){return function(o,t,e){l(f,o,t,e,"controller")}}function Mt(){return function(o,t,e){l(f,o,t,e,"action")}}function Bt(){return function(o,t,e){l(f,o,t,e,"subaction")}}function Et(){return function(o,t,e){l(f,o,t,e,"body")}}function Nt(){return function(o,t,e){l(f,o,t,e,"stream")}}function Dt(){return function(o,t,e){l(f,o,t,e,"home")}}function Jt(o="home"){return function(t,e,s){l(f,t,e,s,"pool",o)}}function Tt(o="home"){return function(t,e,s){l(V,t,e,s,"connection",o)}}function Lt(o={}){return function(t,e,s){l(v,t,e,0,"json",o)}}function It(o={}){return function(t,e,s){l(v,t,e,0,"xml",o)}}function Ut(o){return function(t,e,s){l(z,t,e,o,"logger",o)}}function Ft(o){return function(t,e,s){const n={format:"json"},r=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],i=[],h=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(V,t,e)||{},u=Reflect.getOwnMetadata(z,t,e)||{},g=Reflect.getOwnMetadata(v,t,e)?.[0]||{type:"json",params:{}},b=Reflect.getOwnMetadata(X,t,e)?.[0]||{type:"",params:{}},$=(Reflect.getOwnMetadata(G,t,e)?.[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 m in h){if(!h.hasOwnProperty(m))continue;const p=`get${yt(h[m].type)}`;a[+m]=this[p](h[m].params)}for(const m in c)c.hasOwnProperty(m)&&(c[m].type,a[+m]=await this.getDb()[c[m].params].getConnection(),i.push(a[+m]));try{let m=await r.apply(this,a),p;if(Array.isArray(m)&&([m,p]=m),b.type!=="init")return n.format==="xml"||g.type==="xml"?this.successXml(m,Object.assign(g.params,p||{})):n.format==="buffer"?this.successBuffer(m,Object.assign(g.params,p||{})):this.success(m,Object.assign(g.params,p||{}))}catch(m){await Promise.all([...i.map(_=>_.rollback())]);let p;n.format==="xml"||g.type==="xml"?p=this.errorXml(m):p=this.error(m);for(const _ in u){if(!u.hasOwnProperty(_))continue;const Y=u[_].params;await this[Y].error(m,{response:at(p?.body||{},["stack"])})}return p}finally{await Promise.all([...i.map(m=>m.release())])}}}}function Kt(){return function(o,t,e){l(X,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Qt(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){l(G,t,e,0,"allow",o)}}function Vt(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Xt={cookieParse:B,cookieString:E,jsonBody:R,rawBody:O,streamBody:w,urlencodedBody:W,multipartBody:M,readConfig:ot,readConfigSync:nt,staticBody:J,extensions:D,getExt:N,jwtDecode:dt,readJsonConfigsSync:lt};export{d as ApiError,ut as AsyncJwt,Q as Binding,k as Controller,Se as Jwt,S as Memcached,K as Model,ye as Server,ft as Ssr,$t as Web,Mt as action,Qt as allow,Et as body,x as codeToStatus,At as config,Tt as connection,Ct as context,Wt as controller,kt as cookies,qt as db,Pt as headers,Xt as helpers,Dt as home,vt as hostname,Ft as http,Kt as init,Vt as inject,Lt as json,Ut as logerror,Ot as method,wt as mixin,_t as mount,Jt as pool,Rt as protocol,jt as remote,St as request,xt as selectControllersSchema,Nt as stream,Bt as subaction,Ht as url,It as xml};
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)}},j=(o,t,e,s)=>{let n=o.controllers.find(h=>h.name===e);if(!n)throw new d({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 d({statusCode:404,code:11,message:`Controller ${e} not active is site schema`});let r=n.subactions.find(h=>h.name===s);if(!r)throw new d({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(r=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},r),!r.isActive)throw new d({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(h=>h.name===r.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 i=(a?.method||"").split(",").map(h=>h.trim());if(r.isCheckMethod&&a.method!=="any"&&!i.includes(t))throw new d({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:r.id,name:r.name,isPermission:r.isPermission,isCheckMethod:r.isCheckMethod,isLog:r.isLog,isActive:r.isActive,isSync:!!r.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class yt{constructor(t,e,s,n={}){this.opts={},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.opts=n,this.res.onAborted(()=>new d({message:"The connection was close",code:1,statusCode:404})),this.context=s,this.context.routes||(this.context.routes=this.context.schema?.controllers.map(r=>({name:r.name,method:r.method,component:r.component,binding:r.binding})))}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,ht.parse(this.req.getQuery()));this.contextWeb={url:this.req.getUrl()+(s?`?${s}`:""),method:this.req.getMethod(),remote:Buffer.from(this.res.getProxiedRemoteAddressAsText()).toString()||Buffer.from(this.res.getRemoteAddressAsText()).toString(),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,$di:{},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((c,u)=>this.contextWeb.headers[c]=u);const r=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:w(this.res,this.req,!1)});const c=this.importControllerSync(),u=new c;if(this.injectContext(u),n.subaction in u)e=await u[n.subaction]();else throw new d({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 S){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const u=await c.getPage(this.memcachedKey);if(u){const{data:g,headers:p}=u;this.success({body:g.toString(),headers:p,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(r.indexOf("application/json")!==-1||r.indexOf("text/json")!==-1)if(this.opts.raw){const c=await U(this.res);let u={};try{u=JSON.parse(c)}catch{}Object.assign(n,u),Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:c})}else Object.assign(n,await H(this.res));else if(r.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(r.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await B(this.res));else if(r.indexOf("application/xml")!==-1||r.indexOf("text/xml")!==-1){const c=(await O(this.res)).toString(),u=A.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,u||{})}else r.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)}):r.indexOf("binary")!==-1?await new Promise(c=>{const u=w(this.res,this.req),g=ut.tmpdir(),p="./body_"+et.randomBytes(32).toString("hex"),$=at.resolve(g,p),m=T.createWriteStream($);u.pipe(m),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:$}}}),u.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await O(this.res)});if(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 F(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}),this.route.binding){const c=Array.isArray(this.route.binding)?this.route.binding:[this.route.binding];for(const u of c){const g=await this.importBinding(u),p=new g;this.injectContext(p),Object.assign(this.contextWeb.$di,await this.initComponent(p))}}const a=await this.importController(),i=new a;this.injectContext(i);const h=await this.initComponent(i);if(typeof h>"u")if(n.subaction in i)e=await i[n.subaction]();else throw new d({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 importBinding(t){let e=t.default||t;if(L(e)||(e=(await t()).default),typeof e!="function")throw new d({statusCode:404,code:12,message:`Binding class not found for ${this.route.name} route`});return e}async importController(){let t=this.route.component.default||this.route.component;if(L(t)||(t=(await this.route.component()).default),typeof t!="function")throw new d({statusCode:404,code:12,message:`Class not found for ${this.route.name} route`});return t}importControllerSync(){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 ${this.route.name} route`});return t}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 d({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 P,s=t.body instanceof Uint8Array,n=t.statusCode||200,r=x(n),a=!s&&!e&&C(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 S&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,t.headers,a,t.memcache).then(),e?this.res.cork(()=>{this.res.writeStatus(r),this.writeHeaders(t.headers),a.on("data",i=>{this.res.write(i)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(r),this.writeHeaders(t.headers),this.res.end(a)})}error(t){const e=t instanceof d&&t.getData()instanceof P;let s=x(404),n=this.defaultResponse.headers,r=t.message;if(t instanceof d){const a={isError:!0,code:t.getCode(),error:t.getMessage()};s=x(t.getStatusCode()),n=Object.assign({},this.defaultResponse.headers,t.getHeaders()||{}),e?r=t.getData():r=C(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),r.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(r)})}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 K={compact:!0,ignoreComment:!0,spaces:4};class k{constructor(){this.responseHeaders={}}setCookieHeader(t,e,s={}){return E(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",r=e.statusCode?e.statusCode:404,a=e.data?e.data:{},i=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"?i:{}},statusCode:r}}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:A.js2xml(Object.assign(s,{body:{...n.body}}),K),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:A.js2xml(Object.assign(s,{body:{...n.body}}),K),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,remote:this.$context.remote,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:(r,a)=>this.setResponseHeader(r,a),setCookieHeader:this.setCookieHeader,$di:this.$context.$di});const n=["init",...s.$inits||[]];for(const r of n)s[r]&&await s[r]();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 q().end()}getConfig(){return this.$context.config}getSchema(){return this.$context.schema}getRoutes(){return this.$context.routes}getMethod(){return this.$context.method}getRemote(){return this.$context.remote}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 Q{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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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)}}class V{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,$di:this.$context.$di}),"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}getRemote(){return this.$context.remote}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}getPool(t="home"){return this.getDb()[t]}getStack(){return this.$context.stack}}const wt=async(o,t,e={},s)=>{const n=async i=>{const h=[...new Set(["init",...i.$inits||[]])];for(const c of h)if(i[c]){const u=await i[c]();if(u)return u}},r=(i,h)=>{"$inject"in i&&i.$inject(h)};t=Object.assign({config:{},getRequest:()=>e,method:"get",...e.controller&&e.subaction&&t.db?.home&&!t.schema?await F(t.db.home,t.method||"get",e.controller,e.subaction):{},...e.controller&&e.subaction&&t.schema?j(t.schema,t.method||"get",e.controller,e.subaction):{},cookies:{},hostname:"",protocol:"http",headers:{}},t);const a=new o(...s||[]);if(a instanceof k)return r(a,t),t.$initResponse=await n(a),a;if(a instanceof Q||a instanceof V){const i=new class extends k{async init(){this.model=await this.$create(o,...s||[])}getModel(){return this.model}};return r(i,t),t.$initResponse=await n(i),i.getModel()}else throw new d({message:"Class should be an instance of Controller or Model or Binding",statusCode:400})},f=Symbol("arguments"),X=Symbol("connections"),v=Symbol("response"),z=Symbol("init"),G=Symbol("logger"),Y=Symbol("filters"),St=o=>o.charAt(0).toUpperCase()+o.slice(1);function Ct(o){const t=(s,n)=>{for(const a of Reflect.ownKeys(n))Object.defineProperty(s.prototype,a,{value:n[a]});const r=Object.getPrototypeOf(n);r&&t(s,r)};function e(s){return t(s,o),s}return e}const l=(o,t,e,s,n,r)=>{const a=Reflect.getOwnMetadata(o,t,e)||{};a[s]={type:n,params:r},Reflect.defineMetadata(o,a,t,e)};function At(){return function(o,t,e){l(f,o,t,e,"request")}}function Ot(){return function(o,t,e){l(f,o,t,e,"context")}}function jt(){return function(o,t,e){l(f,o,t,e,"config")}}function kt(){return function(o,t,e){l(f,o,t,e,"method")}}function vt(){return function(o,t,e){l(f,o,t,e,"remote")}}function Rt(){return function(o,t,e){l(f,o,t,e,"cookies")}}function Ht(){return function(o,t,e){l(f,o,t,e,"hostname")}}function qt(){return function(o,t,e){l(f,o,t,e,"url")}}function Pt(){return function(o,t,e){l(f,o,t,e,"protocol")}}function Bt(){return function(o,t,e){l(f,o,t,e,"db")}}function Wt(){return function(o,t,e){l(f,o,t,e,"headers")}}function Mt(){return function(o,t,e){l(f,o,t,e,"controller")}}function Et(){return function(o,t,e){l(f,o,t,e,"action")}}function Nt(){return function(o,t,e){l(f,o,t,e,"subaction")}}function Dt(){return function(o,t,e){l(f,o,t,e,"body")}}function Jt(){return function(o,t,e){l(f,o,t,e,"stream")}}function Tt(){return function(o,t,e){l(f,o,t,e,"home")}}function Lt(o="home"){return function(t,e,s){l(f,t,e,s,"pool",o)}}function It(o="home"){return function(t,e,s){l(X,t,e,s,"connection",o)}}function Ut(o={}){return function(t,e,s){l(v,t,e,0,"json",o)}}function Ft(o={}){return function(t,e,s){l(v,t,e,0,"xml",o)}}function Kt(o){return function(t,e,s){l(G,t,e,o,"logger",o)}}function Qt(o){return function(t,e,s){const n={format:"json"},r=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],i=[],h=Reflect.getOwnMetadata(f,t,e)||{},c=Reflect.getOwnMetadata(X,t,e)||{},u=Reflect.getOwnMetadata(G,t,e)||{},g=Reflect.getOwnMetadata(v,t,e)?.[0]||{type:"json",params:{}},p=Reflect.getOwnMetadata(z,t,e)?.[0]||{type:"",params:{}},$=(Reflect.getOwnMetadata(Y,t,e)?.[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 m in h){if(!h.hasOwnProperty(m))continue;const b=`get${St(h[m].type)}`;a[+m]=this[b](h[m].params)}for(const m in c)c.hasOwnProperty(m)&&(c[m].type,a[+m]=await this.getDb()[c[m].params].getConnection(),i.push(a[+m]));try{let m=await r.apply(this,a),b;if(Array.isArray(m)&&([m,b]=m),p.type!=="init")return n.format==="xml"||g.type==="xml"?this.successXml(m,Object.assign(g.params,b||{})):n.format==="buffer"?this.successBuffer(m,Object.assign(g.params,b||{})):this.success(m,Object.assign(g.params,b||{}))}catch(m){await Promise.all([...i.map(_=>_.rollback())]);let b;n.format==="xml"||g.type==="xml"?b=this.errorXml(m):b=this.error(m);for(const _ in u){if(!u.hasOwnProperty(_))continue;const Z=u[_].params;await this[Z].error(m,{response:ct(b?.body||{},["stack"])})}return b}finally{await Promise.all([...i.map(m=>m.release())])}}}}function Vt(){return function(o,t,e){l(z,o,t,0,"init"),"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(t)}}function Xt(o){return o=(Array.isArray(o)?o:[o]).map(t=>t.toLowerCase()),function(t,e,s){l(Y,t,e,0,"allow",o)}}function zt(o){return function(t,e){delete t[e]&&Object.defineProperty(t,e,{get:function(){return this.$context.$di[o||e]},enumerable:!0,configurable:!1})}}const Gt={cookieParse:M,cookieString:E,jsonBody:H,jsonBodyRaw:U,rawBody:O,streamBody:w,urlencodedBody:B,multipartBody:W,readConfig:nt,readConfigSync:it,staticBody:J,extensions:D,getExt:N,jwtDecode:mt,readJsonConfigsSync:gt};export{d as ApiError,dt as AsyncJwt,V as Binding,k as Controller,Ae as Jwt,S as Memcached,Q as Model,Se as Server,pt as Ssr,yt as Web,Et as action,Xt as allow,Dt as body,x as codeToStatus,jt as config,It as connection,Ot as context,Mt as controller,Rt as cookies,Bt as db,Wt as headers,Gt as helpers,Tt as home,Ht as hostname,Qt as http,Vt as init,zt as inject,Ut as json,Kt as logerror,kt as method,Ct as mixin,wt as mount,Lt as pool,Pt as protocol,vt as remote,At as request,_t as selectControllersSchema,Jt as stream,Nt as subaction,qt as url,Ft as xml};
package/jsonBody.d.ts CHANGED
@@ -1,10 +1,5 @@
1
1
  import { HttpResponse } from 'uWebSockets.js';
2
2
 
3
- /**
4
- * @description
5
- * Parser of json requests body
6
- * @throws {ApiError}
7
- */
8
3
  declare const jsonBody: (res: HttpResponse) => Promise<any>;
9
4
 
10
5
  export { jsonBody };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jwn-js/common",
3
3
  "private": false,
4
- "version": "2.4.2",
4
+ "version": "2.4.4",
5
5
  "description": "@jwn-js/common package",
6
6
  "main": "./index.js",
7
7
  "types": "./index.d.ts",