@jwn-js/common 2.1.15 → 2.1.17

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 (97) hide show
  1. package/ApiError.d.ts +1 -29
  2. package/ApiError.js +1 -39
  3. package/ApiError.mjs +1 -0
  4. package/Jwt-7tQL-rwa.js +1 -0
  5. package/Jwt-CDdbxwvH.js +1 -0
  6. package/Jwt.js +1 -44
  7. package/Jwt.mjs +1 -0
  8. package/Memcached.js +9 -124
  9. package/Memcached.mjs +9 -0
  10. package/Server.d.ts +2 -2
  11. package/Server.js +1 -239
  12. package/Server.mjs +1 -0
  13. package/cookieParse.js +1 -27
  14. package/cookieParse.mjs +1 -0
  15. package/cookieString.js +1 -24
  16. package/cookieString.mjs +1 -0
  17. package/docs/assets/highlight.css +19 -5
  18. package/docs/assets/main.js +59 -52
  19. package/docs/assets/navigation.js +1 -0
  20. package/docs/assets/search.js +1 -1
  21. package/docs/assets/style.css +826 -826
  22. package/docs/classes/ApiError.html +22 -17
  23. package/docs/classes/AsyncJwt.html +16 -17
  24. package/docs/classes/Controller.html +42 -24
  25. package/docs/classes/Jwt.html +16 -17
  26. package/docs/classes/Memcached.html +31 -38
  27. package/docs/classes/Model.html +24 -7
  28. package/docs/classes/Server.html +25 -25
  29. package/docs/classes/Ssr.html +13 -11
  30. package/docs/classes/Web.html +10 -3
  31. package/docs/functions/action.html +2 -0
  32. package/docs/functions/body.html +2 -0
  33. package/docs/functions/codeToStatus.html +2 -0
  34. package/docs/functions/config.html +2 -0
  35. package/docs/functions/connection.html +2 -0
  36. package/docs/functions/context.html +2 -0
  37. package/docs/functions/controller-1.html +2 -0
  38. package/docs/functions/cookies.html +2 -0
  39. package/docs/functions/db.html +2 -0
  40. package/docs/functions/headers.html +2 -0
  41. package/docs/functions/home.html +2 -0
  42. package/docs/functions/hostname.html +2 -0
  43. package/docs/functions/http.html +4 -0
  44. package/docs/functions/init.html +2 -0
  45. package/docs/functions/json.html +3 -0
  46. package/docs/functions/logerror.html +3 -0
  47. package/docs/functions/method.html +2 -0
  48. package/docs/functions/mixin.html +5 -0
  49. package/docs/functions/mount.html +2 -0
  50. package/docs/functions/pool.html +2 -0
  51. package/docs/functions/protocol.html +2 -0
  52. package/docs/functions/request.html +2 -0
  53. package/docs/functions/selectControllersSchema.html +1 -0
  54. package/docs/functions/stream.html +2 -0
  55. package/docs/functions/subaction.html +2 -0
  56. package/docs/functions/url.html +2 -0
  57. package/docs/functions/xml.html +3 -0
  58. package/docs/index.html +8 -16
  59. package/docs/interfaces/ApiErrorMessage.html +6 -1
  60. package/docs/interfaces/ContextSsr.html +22 -19
  61. package/docs/interfaces/ContextWeb.html +7 -1
  62. package/docs/interfaces/OptionsSsr.html +3 -1
  63. package/docs/interfaces/OptionsWeb.html +6 -1
  64. package/docs/interfaces/ResponseOptions.html +4 -1
  65. package/docs/interfaces/Route.html +4 -1
  66. package/docs/interfaces/Schema.html +3 -1
  67. package/docs/interfaces/ServerHandler.html +4 -1
  68. package/docs/interfaces/ServerOptions.html +8 -1
  69. package/docs/interfaces/ServerWebsocket.html +4 -1
  70. package/docs/modules.html +50 -85
  71. package/docs/types/ServerRoutes.html +1 -0
  72. package/docs/variables/helpers.html +31 -0
  73. package/index.d.ts +30 -109
  74. package/index.js +4 -1965
  75. package/index.mjs +57 -0
  76. package/jsonBody.js +1 -27
  77. package/jsonBody.mjs +1 -0
  78. package/multipartBody.d.ts +1 -1
  79. package/multipartBody.js +1 -48
  80. package/multipartBody.mjs +1 -0
  81. package/package.json +12 -19
  82. package/readConfig.js +1 -17
  83. package/readConfig.mjs +1 -0
  84. package/readConfigSync.js +1 -18
  85. package/readConfigSync.mjs +1 -0
  86. package/staticBody.js +1 -207
  87. package/staticBody.mjs +1 -0
  88. package/urlencodedBody.js +1 -32
  89. package/urlencodedBody.mjs +1 -0
  90. package/ApiError-b517f53a.js +0 -37
  91. package/cookieParse-49f1da46.js +0 -25
  92. package/decoders-ee9f4396.js +0 -18
  93. package/docs/assets/icons.css +0 -1043
  94. package/docs/assets/icons.png +0 -0
  95. package/docs/assets/icons@2x.png +0 -0
  96. package/docs/assets/widgets.png +0 -0
  97. package/docs/assets/widgets@2x.png +0 -0
package/index.mjs ADDED
@@ -0,0 +1,57 @@
1
+ import{ApiError as h}from"./ApiError.mjs";import{codeToStatus as _}from"./Server.mjs";import{Server as pe}from"./Server.mjs";import{t as v,f as x,u as U}from"./Jwt-7tQL-rwa.js";import{J as ge}from"./Jwt-7tQL-rwa.js";import V,{webcrypto as X}from"crypto";import{TextEncoder as z}from"util";import{Memcached as $}from"./Memcached.mjs";import{jsonBody as O}from"./jsonBody.mjs";import{PassThrough as j,Stream as k}from"stream";import{urlencodedBody as H}from"./urlencodedBody.mjs";import{multipartBody as R}from"./multipartBody.mjs";import{readConfig as G}from"./readConfig.mjs";import{readConfigSync as Y}from"./readConfigSync.mjs";import{cookieParse as q}from"./cookieParse.mjs";import{cookieString as P}from"./cookieString.mjs";import{getExt as W,extensions as E,staticBody as N}from"./staticBody.mjs";import*as M from"fs";import*as Z from"path";import tt from"path";import{isClass as et,isObject as B,omit as st}from"easy-ash";import ot from"querystring";import S from"xml-js";import*as nt from"os";import"reflect-metadata";import"dns";import"uWebSockets.js";import"formidable";const{subtle:D}=X;class it{constructor(e,t){this.algorithm="SHA-256",this.secret=e,this.algorithm=t?.algorithm||this.algorithm,this.algorithm=this.algorithm.replace("-","").replace("SHA","SHA-")}async verify(e){if(!e)return!1;const t=e.split(".");return await this.signString(`${t[0]}.${t[1]}`)===t[2]}async sign(e){const t=v({alg:this.algorithm.replace("-","").replace("SHA","HS"),typ:"JWT"}),s=v(e),n=await this.signString(`${t}.${s}`);return`${t}.${s}.${n}`}decode(e){const t=(e||"").split("."),s=x(t[0]),n=x(t[1]);return{head:s,body:n}}async signString(e){const t=new z,s=await D.importKey("raw",t.encode(this.secret),{name:"HMAC",hash:{name:this.algorithm}},!1,["sign","verify"]);return U(Buffer.from(await D.sign("HMAC",s,t.encode(e))).toString("base64"))}}const rt=o=>{const e=(o||"").split("."),t=x(e[0]),s=x(e[1]);return{head:t,body:s}},C=o=>new Promise((e,t)=>{at(o,s=>e(s),()=>{t(new h({message:"Can`t parse request",code:1,statusCode:404}))})});function at(o,e,t){let s=Buffer.from([]);o.onData((n,i)=>{s=Buffer.concat([s,Buffer.from(n)]),i&&e(s)}),o.onAborted(t)}const w=(o,e,t=!0)=>{o.onAborted(()=>new h({message:"Connection aborted",code:1,statusCode:404}));const s=new j;return s.headers={},e.forEach((n,i)=>s.headers[n]=i),o.onData((n,i)=>{s.write(Buffer.from(Buffer.from(n))),t&&s.resume(),i&&s.end()}),s},ct=(o,e={})=>{for(const t of o){const s=Z.resolve(t);Object.assign(e,JSON.parse(M.readFileSync(s).toString()))}return e};class ht{constructor(e,t,s,n){this.res=e,this.req=t,this.context=s,this.entry=n}async request(e={}){this.res.onAborted(()=>{console.log("Abort is SSR handler")});const t=this.req.getQuery(),s=this.req.getUrl()+(t?`?${t}`:""),n=W(s);if(E.includes(n)){await N(this.res,this.req,"./dist/client");return}const i={hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl(),cookies:q(this.req.getHeader("cookie")),ip:this.req.getHeader("x-forwarded-for")?.split(/,\s+/)?.[0],memcache:null,statusCode:200,headers:{},responseHeaders:{"content-type":"text/html; charset=utf-8"}};this.req.forEach((c,l)=>i.headers[c]=l);const a=`${i.protocol}://${i.hostname}${i.url}`;let r,d=null;this.context.memcached&&(d=await this.context.memcached.getPage(a)),d?(r=d.data.toString(),i.headers=d.headers):({html:r}=await this.entry(s,{manifest:this.context.manifest,res:this.res,req:this.req,context:i}),i.statusCode===200&&this.context.memcached&&await this.context.memcached.setPage(a,i.headers,r,i.memcache)),this.res.writeStatus(_(i.statusCode)),Object.keys(i.headers).map(c=>this.res.writeHeader(c,i.headers[c])),this.res.end(r)}}const dt=async(o,e,t)=>(await o.poolQuery({sql:`
2
+ SELECT c.id AS controller_id,
3
+ c.name AS controller_name,
4
+ c.is_active AS controller_is_active,
5
+ c.is_sitemap AS controller_is_sitemap,
6
+ a.id AS action_id,
7
+ a.name AS action_name,
8
+ a.is_active AS action_is_active,
9
+ a.method AS action_method,
10
+ s.id AS subaction_id,
11
+ s.name AS subaction_name,
12
+ s.is_permission AS subaction_is_permission,
13
+ s.is_check_method AS subaction_is_check_method,
14
+ s.is_log AS subaction_is_log,
15
+ s.is_active AS subaction_is_active
16
+ FROM app_controllers c
17
+ INNER JOIN app_subactions s ON s.app_controllers_id = c.id
18
+ LEFT JOIN app_actions a ON a.id = s.app_actions_id
19
+ WHERE c.name = :name AND s.name = :subaction
20
+ `,namedPlaceholders:!0},{name:e,subaction:t}))?.[0],ut=async o=>(await o.poolQuery(`
21
+ SELECT c.id AS controller_id,
22
+ c.name AS controller_name,
23
+ c.is_active AS controller_is_active,
24
+ c.is_sitemap AS controller_is_sitemap,
25
+ a.id AS action_id,
26
+ a.name AS action_name,
27
+ a.is_active AS action_is_active,
28
+ a.method AS action_method,
29
+ s.id AS subaction_id,
30
+ s.name AS subaction_name,
31
+ s.is_permission AS subaction_is_permission,
32
+ s.is_check_method AS subaction_is_check_method,
33
+ s.is_log AS subaction_is_log,
34
+ s.is_active AS subaction_is_active
35
+ FROM app_controllers c
36
+ INNER JOIN app_subactions s ON s.app_controllers_id = c.id
37
+ LEFT JOIN app_actions a ON a.id = s.app_actions_id;
38
+ `)).reduce((e,t)=>(e[`${t.controller_name}::${t.subaction_name}`]=t,e),{}),mt=async(o,e,t,s,n="",i=3600)=>{const a=`${n}::routes::controllers`,r=`${e}::${t}`,d=await s.getValue(a);if(d){const c=JSON.parse(d.toString());return(c||{}).hasOwnProperty(r)?c[r]:void 0}else{const c=await ut(o);return await s.setValue(a,Buffer.from(JSON.stringify(c)),i),(c||{}).hasOwnProperty(r)?c[r]:void 0}},J=async(o,e,t,s,n,i="",a=3600)=>{let r;if(n&&n.isClient()&&n.isConnectedServers()?r=await mt(o,t,s,n,i,a):r=await dt(o,t,s),!r)throw new h({statusCode:404,code:11,message:`Controller ${t} not found in site schema`});const d=(r?.action_method||"").split(",").map(c=>c.trim());if(r.controller_is_active!==1)throw new h({statusCode:404,code:11,message:`Controller ${t} not active in site schema`});if(!r.action_id)throw new h({statusCode:404,code:11,message:"Action not found in site schema"});if(r.action_is_active!==1)throw new h({statusCode:404,code:11,message:`Action ${r.action_name} not active in site schema`});if(!r.subaction_id)throw new h({statusCode:404,code:11,message:`Subaction ${s} not found in site schema`});if(r.subaction_is_active!==1)throw new h({statusCode:404,code:11,message:`Subaction ${s} not active in site schema`});if(r.subaction_is_check_method!==0&&r.action_method!=="any"&&!d.includes(e))throw new h({statusCode:404,code:11,message:`Controller ${t} action ${r.action_name} allow only ${r.action_method} method`});return{controller:{id:+r.controller_id,name:r.controller_name,isActive:!!r.controller_is_active,isSitemap:!!r.controller_is_sitemap},action:{id:+r.action_id,name:r.action_name,isActive:!!r.action_is_active,method:r.action_method},subaction:{id:+r.subaction_id,name:r.subaction_name,isPermission:!!r.subaction_is_permission,isCheckMethod:!!r.subaction_is_check_method,isLog:!!r.subaction_is_log,isActive:!!r.subaction_is_active,isSync:!1}}},lt=async o=>{const e={},t={};return(await o.poolQuery(`
39
+ SELECT c.id AS controller_id,
40
+ c.name AS controller_name,
41
+ c.is_active AS controller_is_active,
42
+ c.is_sitemap AS controller_is_sitemap,
43
+ a.id AS action_id,
44
+ a.name AS action_name,
45
+ a.is_active AS action_is_active,
46
+ a.method AS action_method,
47
+ s.id AS subaction_id,
48
+ s.name AS subaction_name,
49
+ s.is_permission AS subaction_is_permission,
50
+ s.is_check_method AS subaction_is_check_method,
51
+ s.is_log AS subaction_is_log,
52
+ s.is_active AS subaction_is_active,
53
+ s.is_sync AS subaction_is_sync
54
+ FROM app_controllers c
55
+ INNER JOIN app_subactions s ON s.app_controllers_id = c.id
56
+ LEFT JOIN app_actions a ON a.id = s.app_actions_id;
57
+ `)).forEach(s=>{e[s.action_name]={id:s.action_id,name:s.action_name,isActive:!!s.action_is_active,method:s.action_method},t[s.controller_name]=t[s.controller_name]||{id:s.controller_id,name:s.controller_name,isActive:!!s.controller_is_active,isSitemap:!!s.controller_is_sitemap,subactions:[]},t[s.controller_name].subactions.push({id:s.subaction_id,action:s.action_name,name:s.subaction_name,isPermission:!!s.subaction_is_permission,isCheckMethod:!!s.subaction_is_check_method,isLog:!!s.subaction_is_log,isActive:!!s.subaction_is_active,isSync:!!s.subaction_is_sync})}),{controllers:Object.values(t),actions:Object.values(e)}},I=(o,e,t,s)=>{let n=o.controllers.find(d=>d.name===t);if(!n)throw new h({statusCode:404,code:11,message:`Controller ${t} not found is site schema`});if(n=Object.assign({isActive:!0,isSitemap:!1},n),!n.isActive)throw new h({statusCode:404,code:11,message:`Controller ${t} not active is site schema`});let i=n.subactions.find(d=>d.name===s);if(!i)throw new h({statusCode:404,code:11,message:`Subaction ${s} not found is site schema`});if(i=Object.assign({isPermission:!1,isCheckMethod:!1,isLog:!1,isActive:!0},i),!i.isActive)throw new h({statusCode:404,code:11,message:`Subaction ${s} not active is site schema`});let a=o.actions.find(d=>d.name===i.action);if(!a)throw new h({statusCode:404,code:11,message:"Action not found is site schema"});if(a=Object.assign({isActive:!0,method:"any"},a),!a.isActive)throw new h({statusCode:404,code:11,message:`Action ${a.name} not active is site schema`});const r=(a?.method||"").split(",").map(d=>d.trim());if(i.isCheckMethod&&a.method!=="any"&&!r.includes(e))throw new h({statusCode:404,code:11,message:`Controller ${t} action ${a.name} allow only ${a.method} method`});return{controller:{id:n.id,name:n.name,isActive:n.isActive,isSitemap:n.isSitemap},subaction:{id:i.id,name:i.name,isPermission:i.isPermission,isCheckMethod:i.isCheckMethod,isLog:i.isLog,isActive:i.isActive,isSync:!!i.isSync},action:{id:a.id,name:a.name,isActive:a.isActive,method:a.method}}};class ft{constructor(e,t,s){this.defaultRequest={lang:"ru"},this.defaultResponse={statusCode:200,headers:{"content-type":"application/json"},body:{}},this.defaultControllerSubaction={controller:"Index",subaction:"index"},this.res=e,this.req=t,this.res.onAborted(()=>new h({message:"The connection was close",code:1,statusCode:404})),this.context=s}setDefaultRequest(e){return Object.assign(this.defaultRequest,e),this}async request(e={}){let t={};try{const s=this.req.getQuery(),n=Object.assign({},this.defaultRequest,e,ot.parse(this.req.getQuery()));this.contextWeb={config:this.context.config,db:this.context.db,method:this.req.getMethod(),cookies:this.req.cookies,hostname:this.req.getHeader("host"),protocol:this.req.getHeader("x-forwarded-proto")||"http",url:this.req.getUrl()+(s?`?${s}`:""),headers:{},stack:this.context.stack||{},getRequest:()=>n},this.memcachedKey=`${this.contextWeb.protocol}://${this.contextWeb.hostname}${this.contextWeb.url}`,this.req.forEach((c,l)=>this.contextWeb.headers[c]=l);const i=this.contextWeb.headers["content-type"]||"application/json";if(n.controller&&n.subaction&&this.context.schema&&(this.route=this.findRoute(n.controller),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route}),Object.assign(this.contextWeb,I(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(n.controller),l=new c;if(this.injectContext(l),n.subaction in l)t=await l[n.subaction]();else throw new h({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});t=Object.assign({},this.defaultResponse,t),this.success(t);return}if(["get","head"].includes(this.contextWeb.method)&&this.contextWeb?.stack?.memcached instanceof $){const c=this.contextWeb.stack.memcached;if(c.isConnectedServers()){const l=await c.getPage(this.memcachedKey);if(l){const{data:b,headers:g}=l;this.success({body:b.toString(),headers:g,statusCode:200})}}}if(n.controller=n.controller||this.defaultControllerSubaction.controller,n.subaction=n.subaction||this.defaultControllerSubaction.subaction,!["get","head"].includes(this.contextWeb.method))if(i.indexOf("application/json")!==-1||i.indexOf("text/json")!==-1)Object.assign(n,await O(this.res));else if(i.indexOf("multipart/form-data")!==-1)Object.assign(n,await R(this.res,this.req)),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:n.files});else if(i.indexOf("application/x-www-form-urlencoded")!==-1)Object.assign(n,await H(this.res));else if(i.indexOf("application/xml")!==-1||i.indexOf("text/xml")!==-1){const c=(await C(this.res)).toString(),l=S.xml2js(c,{compact:!0,cdataKey:"_value",textKey:"_value"});Object.assign(n,l||{})}else i.indexOf("stream")!==-1?Object.defineProperty(this.contextWeb,"$stream",{enumerable:!1,configurable:!1,writable:!1,value:w(this.res,this.req,!1)}):i.indexOf("binary")!==-1?await new Promise(c=>{const l=w(this.res,this.req),b=nt.tmpdir(),g="./body_"+V.randomBytes(32).toString("hex"),u=tt.resolve(b,g),p=M.createWriteStream(u);l.pipe(p),Object.defineProperty(this.contextWeb,"$files",{enumerable:!1,configurable:!1,writable:!1,value:{body:{path:u}}}),l.on("end",()=>c(!0))}):Object.defineProperty(this.contextWeb,"$body",{enumerable:!1,configurable:!1,writable:!1,value:await C(this.res)});this.route=this.findRoute(n.controller),Object.assign(this.contextWeb,this.context.schema?I(this.context.schema,this.contextWeb.method,this.route.name,n.subaction):await J(this.contextWeb.db.home,this.contextWeb.method,this.route.name,n.subaction,this.context.stack?.memcached,this.context.stack?.memcachedPrefix,this.context.stack?.memcachedExpiry)),Object.defineProperty(this.contextWeb,"$route",{enumerable:!1,configurable:!1,writable:!1,value:this.route});const a=await this.importController(n.controller),r=new a;this.injectContext(r);const d=await this.initComponent(r);if(typeof d>"u")if(n.subaction in r)t=await r[n.subaction]();else throw new h({statusCode:404,code:13,message:`Method ${n.subaction} not found in ${n.controller} route`});else t=d;t=Object.assign({},this.defaultResponse,t),this.success(t)}catch(s){this.error(s)}}async importController(e){let t=this.route.component.default||this.route.component;if(et(t)||(t=(await this.route.component()).default),typeof t!="function")throw new h({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}importControllerSync(e){const t=this.route.component.default||this.route.component;if(typeof t!="function")throw new h({statusCode:404,code:12,message:`Class not found for ${e} route`});return t}findRoute(e){const t=this.context.routes.filter(s=>s.name===e&&(s.method===this.contextWeb.method||s.method==="any"||Array.isArray(s.method)&&s.method.includes(this.contextWeb.method)||typeof s.method>"u"))?.[0];if(!t)throw new h({statusCode:404,code:11,message:`Route ${e} not found`});return t}injectContext(e){"$inject"in e&&e.$inject(this.contextWeb)}async initComponent(e){const t=[...new Set(["init",...e.$inits||[]])];for(const s of t)if(e[s]){const n=await e[s]();if(n)return n}}success(e){const t=e.body instanceof k,s=e.statusCode||200,n=_(s),i=!t&&B(e.body)?JSON.stringify(e.body):e.body;!t&&["get","head"].includes(this.contextWeb.method)&&s===200&&e.memcache&&this.contextWeb?.stack?.memcached instanceof $&&this.contextWeb.stack.memcached.setPage(this.memcachedKey,e.headers,i,e.memcache).then(),t?this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(e.headers),i.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(n),this.writeHeaders(e.headers),this.res.end(i)})}error(e){const t=e instanceof h&&e.getData()instanceof k;let s=_(404),n=this.defaultResponse.headers,i=e.message;if(e instanceof h){const a={isError:!0,code:e.getCode(),error:e.getMessage()};s=_(e.getStatusCode()),n=e.getHeaders()||this.defaultResponse.headers,t?i=e.getData():i=B(e.getData())&&Object.keys(e.getData()).length>0?JSON.stringify(e.getData()):JSON.stringify(a)}t?this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),i.on("data",a=>{this.res.write(a)}).on("end",()=>{this.res.end()})}):this.res.cork(()=>{this.res.writeStatus(s),this.writeHeaders(n),this.res.end(i)})}writeHeaders(e){Object.entries(e).forEach(([t,s])=>{Array.isArray(s)?s.forEach(n=>this.res.writeHeader(t,n)):this.res.writeHeader(t,s)})}}const pt=async(o,e,t={})=>{const s=async a=>{let r;return"init"in a&&(r=await a.init()),r},n=(a,r)=>{"$inject"in a&&a.$inject(r)};e=Object.assign({config:{},getRequest:()=>t,method:"get",...t.controller&&t.subaction&&e.db?.home?await J(e.db.home,e.method||"get",t.controller,t.subaction):{},cookies:{},hostname:e.config?.server?.development?.host,protocol:"http",headers:{}},e);const i=new o;if(n(i,e),await s(i))throw new h({statusCode:404,code:13,message:"init method response value"});return i},L={compact:!0,ignoreComment:!0,spaces:4};class bt{constructor(){this.responseHeaders={}}setCookieHeader(e,t,s={}){return P(e,t,s)}success(e={},t){return{headers:Object.assign({"content-type":"application/json"},this.responseHeaders,t?.headers||{}),body:{isError:!1,data:e},memcache:t?.memcache||null,statusCode:t?.statusCode||200}}error(e){const t=e,s=t.code?t.code:0,n=t.message?t.message:"Api request error",i=t.statusCode?t.statusCode:404,a=t.data?t.data:{},r=t.response?{status:t.response.status,headers:t.response.headers,config:{url:t.response.url,method:t.response.method,params:t.response.params,headers:t.response.headers},data:t.response.data}:{};return{headers:Object.assign({"content-type":"application/json"},t.headers),body:{isError:!0,error:n,code:s,data:a,stack:process.env.NODE_ENV!=="production"?t.stack:"",response:process.env.NODE_ENV!=="production"?r:{}},statusCode:i}}successXml(e={},t){const s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.success(e,t);return{headers:Object.assign({"content-type":"application/xml"},this.responseHeaders,t?.headers||{}),body:S.js2xml(Object.assign(s,{body:{...n.body}}),L),memcache:n.memcache}}errorXml(e){const t=e,s={_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},n=this.error(t);return{headers:Object.assign({"content-type":"application/json"},t.headers),body:S.js2xml(Object.assign(s,{body:{...n.body}}),L),statusCode:n.statusCode}}async $create(e,...t){const s=new e(...t);"$inject"in s&&s.$inject({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,setResponseHeader:(i,a)=>this.setResponseHeader(i,a),setCookieHeader:this.setCookieHeader});const n=["init",...s.$inits||[]];for(const i of n)s[i]&&await s[i]();return s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getBody(){return this.$context.$body||Buffer.from("")}getFiles(){return this.$context.$files||{}}getStream(){return this.$context.$stream||new j().end()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}getCookies(){return this.$context.cookies}getHostname(){return this.$context.hostname}getUrl(){return this.$context.url}getProtocol(){return this.$context.protocol}getDb(){return this.$context.db}getHeaders(){return this.$context.headers}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getHome(){return this.getDb().home}getPool(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){this.responseHeaders.hasOwnProperty(e)?(this.responseHeaders[e]=Array.isArray(this.responseHeaders[e])?this.responseHeaders[e]:[this.responseHeaders[e]],this.responseHeaders[e].push(t)):this.responseHeaders[e]=t}}class gt{async $create(e,...t){const s=new e(...t);return"$inject"in s&&s.$inject({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,setResponseHeader:this.$context.setResponseHeader,setCookieHeader:this.$context.setCookieHeader}),"init"in s&&await s.init(),s}async $createAll(e){return Promise.all(e.map(t=>this.$create(...t)))}$inject(e){this.$context=e}getContext(){return this.$context}getRequest(){return this.$context.getRequest()}getConfig(){return this.$context.config}getMethod(){return this.$context.method}getHeaders(){return this.$context.headers}getCookies(){return this.$context.cookies}getController(){return this.$context.controller}getAction(){return this.$context.action}getSubaction(){return this.$context.subaction}getDb(){return this.$context.db}getHome(){return this.$context.db.home}getPool(e="home"){return this.getDb()[e]}getStack(){return this.$context.stack}setResponseHeader(e,t){return this.$context.setResponseHeader(e,t)}setCookieHeader(e,t,s={}){return this.$context.setCookieHeader(e,t,s)}}const f=Symbol("arguments"),T=Symbol("connections"),A=Symbol("response"),F=Symbol("init"),K=Symbol("logger"),_t=o=>o.charAt(0).toUpperCase()+o.slice(1);function yt(o,e={}){const t=Reflect.ownKeys(o),s=Reflect.ownKeys(e),n=Symbol("isa");function i(a){for(const r of t)Object.defineProperty(a.prototype,r,{value:o[r]});return Object.defineProperty(a.prototype,n,{value:!0}),a}for(const a of s)Object.defineProperty(i,a,{value:e[a],enumerable:e.propertyIsEnumerable(a)});return Object.defineProperty(i,Symbol.hasInstance,{value:a=>!!a[n]}),i}const m=(o,e,t,s,n,i)=>{const a=Reflect.getOwnMetadata(o,e,t)||{};a[s]={type:n,params:i},Reflect.defineMetadata(o,a,e,t)};function xt(){return function(o,e,t){m(f,o,e,t,"request")}}function wt(){return function(o,e,t){m(f,o,e,t,"context")}}function $t(){return function(o,e,t){m(f,o,e,t,"config")}}function St(){return function(o,e,t){m(f,o,e,t,"method")}}function Ct(){return function(o,e,t){m(f,o,e,t,"cookies")}}function At(){return function(o,e,t){m(f,o,e,t,"hostname")}}function vt(){return function(o,e,t){m(f,o,e,t,"url")}}function Ot(){return function(o,e,t){m(f,o,e,t,"protocol")}}function jt(){return function(o,e,t){m(f,o,e,t,"db")}}function kt(){return function(o,e,t){m(f,o,e,t,"headers")}}function Ht(){return function(o,e,t){m(f,o,e,t,"controller")}}function Rt(){return function(o,e,t){m(f,o,e,t,"action")}}function qt(){return function(o,e,t){m(f,o,e,t,"subaction")}}function Pt(){return function(o,e,t){m(f,o,e,t,"body")}}function Wt(){return function(o,e,t){m(f,o,e,t,"stream")}}function Et(){return function(o,e,t){m(f,o,e,t,"home")}}function Nt(o="home"){return function(e,t,s){m(f,e,t,s,"pool",o)}}function Mt(o="home"){return function(e,t,s){m(T,e,t,s,"connection",o)}}function Bt(o={}){return function(e,t,s){m(A,e,t,0,"json",o)}}function Dt(o={}){return function(e,t,s){m(A,e,t,0,"xml",o)}}function Jt(o){return function(e,t,s){m(K,e,t,o,"logger",o)}}function It(o){return function(e,t,s){const n={format:"json"},i=s.value;s.value=async function(){o&&Object.assign(n,await o.apply(this)||{});const a=[],r=[],d=Reflect.getOwnMetadata(f,e,t)||{},c=Reflect.getOwnMetadata(T,e,t)||{},l=Reflect.getOwnMetadata(K,e,t)||{},b=Reflect.getOwnMetadata(A,e,t)?.[0]||{type:"json",params:{}},g=Reflect.getOwnMetadata(F,e,t)?.[0]||{type:"",params:{}};for(const u in d){if(!d.hasOwnProperty(u))continue;const p=`get${_t(d[u].type)}`;a[+u]=this[p](d[u].params)}for(const u in c)c.hasOwnProperty(u)&&(c[u].type,a[+u]=await this.getDb()[c[u].params].getConnection(),r.push(a[+u]));try{let u=await i.apply(this,a),p;if(Array.isArray(u)&&([u,p]=u),g.type!=="init")return n.format==="xml"||b.type==="xml"?this.successXml(u,Object.assign(b.params,p||{})):this.success(u,Object.assign(b.params,p||{}))}catch(u){await Promise.all([...r.map(y=>y.rollback())]);let p;n.format==="xml"||b.type==="xml"?p=this.errorXml(u):p=this.error(u);for(const y in l){if(!l.hasOwnProperty(y))continue;const Q=l[y].params;await this[Q].error(u,{response:st(p?.body||{},["stack"])})}return p}finally{await Promise.all([...r.map(u=>u.release())])}}}}function Lt(){return function(o,e,t){m(F,o,e,0,"init"),t.value,"$inits"in o||Object.defineProperty(o,"$inits",{value:[]}),o.$inits.push(e)}}const Tt={cookieParse:q,cookieString:P,jsonBody:O,rawBody:C,streamBody:w,urlencodedBody:H,multipartBody:R,readConfig:G,readConfigSync:Y,staticBody:N,extensions:E,getExt:W,jwtDecode:rt,readJsonConfigsSync:ct};export{h as ApiError,it as AsyncJwt,bt as Controller,ge as Jwt,$ as Memcached,gt as Model,pe as Server,ht as Ssr,ft as Web,Rt as action,Pt as body,_ as codeToStatus,$t as config,Mt as connection,wt as context,Ht as controller,Ct as cookies,jt as db,kt as headers,Tt as helpers,Et as home,At as hostname,It as http,Lt as init,Bt as json,Jt as logerror,St as method,yt as mixin,pt as mount,Nt as pool,Ot as protocol,xt as request,lt as selectControllersSchema,Wt as stream,qt as subaction,vt as url,Dt as xml};
package/jsonBody.js CHANGED
@@ -1,27 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var ApiError = require('./ApiError-b517f53a.js');
6
-
7
- const jsonBody = (res) => new Promise((resolve, reject) => {
8
- readJson(res, (obj) => resolve(obj), () => {
9
- reject(new ApiError.ApiError({ message: "Can`t parse request", code: 1, statusCode: 404 }));
10
- });
11
- });
12
- function readJson(res, cb, err) {
13
- let buffer = Buffer.from([]);
14
- res.onData((ab, isLast) => {
15
- buffer = Buffer.concat([buffer, Buffer.from(ab)]);
16
- if (isLast) {
17
- try {
18
- cb(JSON.parse(buffer.toString()));
19
- } catch (e) {
20
- cb({});
21
- }
22
- }
23
- });
24
- res.onAborted(err);
25
- }
26
-
27
- exports.jsonBody = jsonBody;
1
+ "use strict";var f=require("./ApiError.js");const a=e=>new Promise((o,t)=>{c(e,r=>o(r),()=>{t(new f.ApiError({message:"Can`t parse request",code:1,statusCode:404}))})});function c(e,o,t){let r=Buffer.from([]);e.onData((s,n)=>{if(r=Buffer.concat([r,Buffer.from(s)]),n)try{o(JSON.parse(r.toString()))}catch{o({})}}),e.onAborted(t)}exports.jsonBody=a;
package/jsonBody.mjs ADDED
@@ -0,0 +1 @@
1
+ import{ApiError as s}from"./ApiError.mjs";const a=r=>new Promise((o,t)=>{c(r,e=>o(e),()=>{t(new s({message:"Can`t parse request",code:1,statusCode:404}))})});function c(r,o,t){let e=Buffer.from([]);r.onData((f,n)=>{if(e=Buffer.concat([e,Buffer.from(f)]),n)try{o(JSON.parse(e.toString()))}catch{o({})}}),r.onAborted(t)}export{a as jsonBody};
@@ -38,4 +38,4 @@ interface Files {
38
38
  */
39
39
  declare const multipartBody: (res: HttpResponse, req: HttpRequest, options?: Options) => Promise<any>;
40
40
 
41
- export { Files, multipartBody };
41
+ export { type Files, multipartBody };
package/multipartBody.js CHANGED
@@ -1,48 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var stream = require('stream');
6
- var ApiError = require('./ApiError-b517f53a.js');
7
- var formidable = require('formidable');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- var formidable__default = /*#__PURE__*/_interopDefaultLegacy(formidable);
12
-
13
- const multipartBody = (res, req, options = { multiples: true }) => new Promise(async (resolve, reject) => {
14
- const err = new ApiError.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 });
15
- res.onAborted(() => err);
16
- try {
17
- const stream$1 = new stream.PassThrough();
18
- stream$1.headers = {};
19
- req.forEach((key, val) => stream$1.headers[key] = val);
20
- res.onData((chunk, isLast) => {
21
- stream$1.write(Buffer.from(Buffer.from(chunk)));
22
- stream$1.resume();
23
- isLast && stream$1.end();
24
- });
25
- const form = formidable__default["default"](options);
26
- const adapter = (row) => ({
27
- size: row.size,
28
- path: row.filepath,
29
- name: row.originalFilename,
30
- type: row.mimetype,
31
- mtime: row.mtime,
32
- newFilename: row.newFilename
33
- });
34
- form.parse(stream$1, (err2, fields, files) => {
35
- err2 && reject(err2);
36
- const output = {};
37
- Object.keys(files).map((key) => {
38
- output[key] = Array.isArray(files[key]) ? files[key].map((row) => adapter(row)) : adapter(files[key]);
39
- });
40
- fields.files = output;
41
- resolve(fields);
42
- });
43
- } catch (e) {
44
- reject(err);
45
- }
46
- });
47
-
48
- exports.multipartBody = multipartBody;
1
+ "use strict";var f=require("stream"),h=require("./ApiError.js"),w=require("formidable");const A=(m,u,c={multiples:!0})=>new Promise(async(y,o)=>{const i=new h.ApiError({message:"Can`t parse body",code:1,statusCode:404});m.onAborted(()=>i);try{const r=new f.PassThrough;r.headers={},u.forEach((e,a)=>r.headers[e]=a),m.onData((e,a)=>{r.write(Buffer.from(Buffer.from(e))),r.resume(),a&&r.end()});const l=w(c),n=e=>({size:e.size,path:e.filepath,name:e.originalFilename,type:e.mimetype,mtime:e.mtime,newFilename:e.newFilename});l.parse(r,(e,a,t)=>{e&&o(e);const p={};Object.keys(t).map(s=>{p[s]=Array.isArray(t[s])?t[s].map(d=>n(d)):n(t[s])}),a.files=p,y(a)})}catch{o(i)}});exports.multipartBody=A;
@@ -0,0 +1 @@
1
+ import{PassThrough as h}from"stream";import{ApiError as u}from"./ApiError.mjs";import w from"formidable";const A=(a,f,c={multiples:!0})=>new Promise(async(y,s)=>{const n=new u({message:"Can`t parse body",code:1,statusCode:404});a.onAborted(()=>n);try{const r=new h;r.headers={},f.forEach((e,t)=>r.headers[e]=t),a.onData((e,t)=>{r.write(Buffer.from(Buffer.from(e))),r.resume(),t&&r.end()});const l=w(c),i=e=>({size:e.size,path:e.filepath,name:e.originalFilename,type:e.mimetype,mtime:e.mtime,newFilename:e.newFilename});l.parse(r,(e,t,o)=>{e&&s(e);const p={};Object.keys(o).map(m=>{p[m]=Array.isArray(o[m])?o[m].map(d=>i(d)):i(o[m])}),t.files=p,y(t)})}catch{s(n)}});export{A as multipartBody};
package/package.json CHANGED
@@ -1,14 +1,13 @@
1
1
  {
2
2
  "name": "@jwn-js/common",
3
3
  "private": false,
4
- "version": "2.1.15",
4
+ "version": "2.1.17",
5
5
  "description": "@jwn-js/common package",
6
6
  "main": "./index.js",
7
7
  "types": "./index.d.ts",
8
8
  "scripts": {
9
9
  "build": "yarn docs && node scripts/build.js",
10
- "test": "jest test -c jest.config.ts --silent true",
11
- "lint": "eslint src/** --ignore-path ./.eslintignore",
10
+ "test": "vitest run",
12
11
  "docs": "typedoc --includeVersion --excludePrivate --out docs src/index.ts"
13
12
  },
14
13
  "repository": {
@@ -18,31 +17,25 @@
18
17
  "author": "webigorkiev",
19
18
  "license": "MIT",
20
19
  "devDependencies": {
21
- "@rollup/plugin-alias": "^3.1.4",
20
+ "@rollup/plugin-alias": "^5.1.0",
22
21
  "@types/formidable": "^2.0.1",
23
- "@types/jest": "^27.0.3",
24
22
  "@types/memjs": "^1.2.3",
25
23
  "@types/node": "^17.0.5",
26
24
  "@types/supertest": "^2.0.11",
27
- "@typescript-eslint/eslint-plugin": "^4.23.0",
28
- "@typescript-eslint/parser": "^4.26.1",
29
25
  "buildmsql": "^1.6.9",
30
26
  "chalk": "^4.1.1",
31
- "esbuild": "^0.14.39",
32
- "eslint": "^7.26.0",
27
+ "esbuild": "^0.20.0",
33
28
  "fs-extra": "^10.0.0",
34
- "jest": "^27.4.5",
29
+ "jsdom": "^24.0.0",
35
30
  "mariadb": "^3.2.3",
36
- "rollup": "^2.62.0",
37
- "rollup-plugin-dts": "3",
38
- "rollup-plugin-esbuild": "^4.8.1",
31
+ "rollup": "^4.10.0",
32
+ "rollup-plugin-dts": "^6.1.0",
33
+ "rollup-plugin-esbuild": "^6.1.1",
39
34
  "supertest": "^6.1.6",
40
35
  "superwstest": "^1.8.0",
41
- "ts-jest": "^27.1.2",
42
- "ts-node": "^10.4.0",
43
- "typedoc": "^0.22.10",
44
- "typescript": "^4.5.4",
45
- "zlib": "^1.0.5"
36
+ "typedoc": "^0.25.8",
37
+ "typescript": "^5.3.3",
38
+ "vitest": "^1.2.2"
46
39
  },
47
40
  "dependencies": {
48
41
  "easy-ash": "^1.1.14",
@@ -50,7 +43,7 @@
50
43
  "memjs": "^1.3.0",
51
44
  "reflect-metadata": "^0.1.13",
52
45
  "uWebSockets.js": "uNetworking/uWebSockets.js#v20.10.0",
53
- "vite-ssr-vue": "^1.0.5",
46
+ "vite-ssr-vue": "^1.0.6",
54
47
  "xml-js": "^1.6.11"
55
48
  }
56
49
  }
package/readConfig.js CHANGED
@@ -1,17 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var path = require('path');
6
- var fs = require('fs');
7
-
8
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
-
10
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
11
-
12
- const readConfig = async (jsonfile) => {
13
- const file = path__default["default"].resolve(jsonfile);
14
- return JSON.parse(await fs.promises.readFile(file, "utf-8"));
15
- };
16
-
17
- exports.readConfig = readConfig;
1
+ "use strict";var a=require("path"),s=require("fs");const i=async e=>{const r=a.resolve(e);return JSON.parse(await s.promises.readFile(r,"utf-8"))};exports.readConfig=i;
package/readConfig.mjs ADDED
@@ -0,0 +1 @@
1
+ import o from"path";import{promises as t}from"fs";const a=async r=>{const e=o.resolve(r);return JSON.parse(await t.readFile(e,"utf-8"))};export{a as readConfig};
package/readConfigSync.js CHANGED
@@ -1,18 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var path = require('path');
6
- var fs = require('fs');
7
-
8
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
-
10
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
11
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
12
-
13
- const readConfigSync = (jsonfile) => {
14
- const file = path__default["default"].resolve(jsonfile);
15
- return JSON.parse(fs__default["default"].readFileSync(file, "utf-8"));
16
- };
17
-
18
- exports.readConfigSync = readConfigSync;
1
+ "use strict";var n=require("path"),t=require("fs");const a=e=>{const r=n.resolve(e);return JSON.parse(t.readFileSync(r,"utf-8"))};exports.readConfigSync=a;
@@ -0,0 +1 @@
1
+ import o from"path";import t from"fs";const f=e=>{const r=o.resolve(e);return JSON.parse(t.readFileSync(r,"utf-8"))};export{f as readConfigSync};
package/staticBody.js CHANGED
@@ -1,207 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var path = require('path');
6
- var fs = require('fs');
7
- var ApiError = require('./ApiError-b517f53a.js');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
12
-
13
- const exts = {
14
- "3gp": "video/3gpp",
15
- "a": "application/octet-stream",
16
- "ai": "application/postscript",
17
- "aif": "audio/x-aiff",
18
- "aiff": "audio/x-aiff",
19
- "asc": "application/pgp-signature",
20
- "asf": "video/x-ms-asf",
21
- "asm": "text/x-asm",
22
- "asx": "video/x-ms-asf",
23
- "atom": "application/atom+xml",
24
- "au": "audio/basic",
25
- "avi": "video/x-msvideo",
26
- "bat": "application/x-msdownload",
27
- "bin": "application/octet-stream",
28
- "bmp": "image/bmp",
29
- "bz2": "application/x-bzip2",
30
- "c": "text/x-c",
31
- "cab": "application/vnd.ms-cab-compressed",
32
- "cc": "text/x-c",
33
- "chm": "application/vnd.ms-htmlhelp",
34
- "class": "application/octet-stream",
35
- "com": "application/x-msdownload",
36
- "conf": "text/plain",
37
- "cpp": "text/x-c",
38
- "crt": "application/x-x509-ca-cert",
39
- "css": "text/css",
40
- "csv": "text/csv",
41
- "cxx": "text/x-c",
42
- "deb": "application/x-debian-package",
43
- "der": "application/x-x509-ca-cert",
44
- "diff": "text/x-diff",
45
- "djv": "image/vnd.djvu",
46
- "djvu": "image/vnd.djvu",
47
- "dll": "application/x-msdownload",
48
- "dmg": "application/octet-stream",
49
- "doc": "application/msword",
50
- "dot": "application/msword",
51
- "dtd": "application/xml-dtd",
52
- "dvi": "application/x-dvi",
53
- "ear": "application/java-archive",
54
- "eml": "message/rfc822",
55
- "eps": "application/postscript",
56
- "exe": "application/x-msdownload",
57
- "f": "text/x-fortran",
58
- "f77": "text/x-fortran",
59
- "f90": "text/x-fortran",
60
- "flv": "video/x-flv",
61
- "for": "text/x-fortran",
62
- "gem": "application/octet-stream",
63
- "gemspec": "text/x-script.ruby",
64
- "gif": "image/gif",
65
- "gz": "application/x-gzip",
66
- "h": "text/x-c",
67
- "hh": "text/x-c",
68
- "htm": "text/html",
69
- "html": "text/html",
70
- "ico": "image/vnd.microsoft.icon",
71
- "ics": "text/calendar",
72
- "ifb": "text/calendar",
73
- "iso": "application/octet-stream",
74
- "jar": "application/java-archive",
75
- "java": "text/x-java-source",
76
- "jnlp": "application/x-java-jnlp-file",
77
- "jpeg": "image/jpeg",
78
- "jpg": "image/jpeg",
79
- "js": "application/javascript",
80
- "json": "application/json",
81
- "log": "text/plain",
82
- "m3u": "audio/x-mpegurl",
83
- "m4v": "video/mp4",
84
- "man": "text/troff",
85
- "mathml": "application/mathml+xml",
86
- "mbox": "application/mbox",
87
- "mdoc": "text/troff",
88
- "me": "text/troff",
89
- "mid": "audio/midi",
90
- "midi": "audio/midi",
91
- "mime": "message/rfc822",
92
- "mml": "application/mathml+xml",
93
- "mng": "video/x-mng",
94
- "mov": "video/quicktime",
95
- "mp3": "audio/mpeg",
96
- "mp4": "video/mp4",
97
- "mp4v": "video/mp4",
98
- "mpeg": "video/mpeg",
99
- "mpg": "video/mpeg",
100
- "ms": "text/troff",
101
- "msi": "application/x-msdownload",
102
- "odp": "application/vnd.oasis.opendocument.presentation",
103
- "ods": "application/vnd.oasis.opendocument.spreadsheet",
104
- "odt": "application/vnd.oasis.opendocument.text",
105
- "ogg": "application/ogg",
106
- "p": "text/x-pascal",
107
- "pas": "text/x-pascal",
108
- "pbm": "image/x-portable-bitmap",
109
- "pdf": "application/pdf",
110
- "pem": "application/x-x509-ca-cert",
111
- "pgm": "image/x-portable-graymap",
112
- "pgp": "application/pgp-encrypted",
113
- "pkg": "application/octet-stream",
114
- "pl": "text/x-script.perl",
115
- "pm": "text/x-script.perl-module",
116
- "png": "image/png",
117
- "pnm": "image/x-portable-anymap",
118
- "ppm": "image/x-portable-pixmap",
119
- "pps": "application/vnd.ms-powerpoint",
120
- "ppt": "application/vnd.ms-powerpoint",
121
- "ps": "application/postscript",
122
- "psd": "image/vnd.adobe.photoshop",
123
- "py": "text/x-script.python",
124
- "qt": "video/quicktime",
125
- "ra": "audio/x-pn-realaudio",
126
- "rake": "text/x-script.ruby",
127
- "ram": "audio/x-pn-realaudio",
128
- "rar": "application/x-rar-compressed",
129
- "rb": "text/x-script.ruby",
130
- "rdf": "application/rdf+xml",
131
- "roff": "text/troff",
132
- "rpm": "application/x-redhat-package-manager",
133
- "rss": "application/rss+xml",
134
- "rtf": "application/rtf",
135
- "ru": "text/x-script.ruby",
136
- "s": "text/x-asm",
137
- "sgm": "text/sgml",
138
- "sgml": "text/sgml",
139
- "sh": "application/x-sh",
140
- "sig": "application/pgp-signature",
141
- "snd": "audio/basic",
142
- "so": "application/octet-stream",
143
- "svg": "image/svg+xml",
144
- "svgz": "image/svg+xml",
145
- "swf": "application/x-shockwave-flash",
146
- "t": "text/troff",
147
- "tar": "application/x-tar",
148
- "tbz": "application/x-bzip-compressed-tar",
149
- "tcl": "application/x-tcl",
150
- "tex": "application/x-tex",
151
- "texi": "application/x-texinfo",
152
- "texinfo": "application/x-texinfo",
153
- "text": "text/plain",
154
- "tif": "image/tiff",
155
- "tiff": "image/tiff",
156
- "torrent": "application/x-bittorrent",
157
- "tr": "text/troff",
158
- "txt": "text/plain",
159
- "vcf": "text/x-vcard",
160
- "vcs": "text/x-vcalendar",
161
- "vrml": "model/vrml",
162
- "war": "application/java-archive",
163
- "wav": "audio/x-wav",
164
- "webp": "image/webp",
165
- "wma": "audio/x-ms-wma",
166
- "wmv": "video/x-ms-wmv",
167
- "wmx": "video/x-ms-wmx",
168
- "wrl": "model/vrml",
169
- "wsdl": "application/wsdl+xml",
170
- "xbm": "image/x-xbitmap",
171
- "xhtml": "application/xhtml+xml",
172
- "xls": "application/vnd.ms-excel",
173
- "xml": "application/xml",
174
- "xpm": "image/x-xpixmap",
175
- "xsl": "application/xml",
176
- "xslt": "application/xslt+xml",
177
- "yaml": "text/yaml",
178
- "yml": "text/yaml",
179
- "zip": "application/zip",
180
- "ttf": "application/x-font-ttf",
181
- "woff": "application/x-font-woff",
182
- "woff2": "application/x-font-woff2"
183
- };
184
- const extensions = Object.keys(exts);
185
- const getExt = (path2) => path2.split(".").pop();
186
- const getContentType = (ext) => exts[ext.toLowerCase()] || "application/octet-stream";
187
- async function staticBody(res, req, base) {
188
- try {
189
- res.onAborted(() => new ApiError.ApiError({
190
- message: "Requers is aborted",
191
- code: 1,
192
- statusCode: 404
193
- }));
194
- let url = req.getUrl().replace(/\.\.\//ig, "").replace(/^\.\/?/, "");
195
- url = `./${url}`;
196
- const file = path__default["default"].resolve(base, url);
197
- const content = await fs.promises.readFile(file);
198
- res.writeStatus("200 OK").writeHeader("content-type", getContentType(getExt(url))).end(content);
199
- } catch (e) {
200
- res.writeStatus("404 Not Found").end(e.message);
201
- }
202
- }
203
-
204
- exports.extensions = extensions;
205
- exports.exts = exts;
206
- exports.getExt = getExt;
207
- exports.staticBody = staticBody;
1
+ "use strict";var m=require("path"),l=require("fs"),n=require("./ApiError.js");const i={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2"},s=Object.keys(i),p=t=>t.split(".").pop(),r=t=>i[t.toLowerCase()]||"application/octet-stream";async function d(t,e,o){try{t.onAborted(()=>new n.ApiError({message:"Requers is aborted",code:1,statusCode:404}));let a=e.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const c=m.resolve(o,a),x=await l.promises.readFile(c);t.writeStatus("200 OK").writeHeader("content-type",r(p(a))).end(x)}catch(a){t.writeStatus("404 Not Found").end(a.message)}}exports.extensions=s,exports.exts=i,exports.getExt=p,exports.staticBody=d;
package/staticBody.mjs ADDED
@@ -0,0 +1 @@
1
+ import x from"path";import{promises as l}from"fs";import{ApiError as n}from"./ApiError.mjs";const i={"3gp":"video/3gpp",a:"application/octet-stream",ai:"application/postscript",aif:"audio/x-aiff",aiff:"audio/x-aiff",asc:"application/pgp-signature",asf:"video/x-ms-asf",asm:"text/x-asm",asx:"video/x-ms-asf",atom:"application/atom+xml",au:"audio/basic",avi:"video/x-msvideo",bat:"application/x-msdownload",bin:"application/octet-stream",bmp:"image/bmp",bz2:"application/x-bzip2",c:"text/x-c",cab:"application/vnd.ms-cab-compressed",cc:"text/x-c",chm:"application/vnd.ms-htmlhelp",class:"application/octet-stream",com:"application/x-msdownload",conf:"text/plain",cpp:"text/x-c",crt:"application/x-x509-ca-cert",css:"text/css",csv:"text/csv",cxx:"text/x-c",deb:"application/x-debian-package",der:"application/x-x509-ca-cert",diff:"text/x-diff",djv:"image/vnd.djvu",djvu:"image/vnd.djvu",dll:"application/x-msdownload",dmg:"application/octet-stream",doc:"application/msword",dot:"application/msword",dtd:"application/xml-dtd",dvi:"application/x-dvi",ear:"application/java-archive",eml:"message/rfc822",eps:"application/postscript",exe:"application/x-msdownload",f:"text/x-fortran",f77:"text/x-fortran",f90:"text/x-fortran",flv:"video/x-flv",for:"text/x-fortran",gem:"application/octet-stream",gemspec:"text/x-script.ruby",gif:"image/gif",gz:"application/x-gzip",h:"text/x-c",hh:"text/x-c",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",ifb:"text/calendar",iso:"application/octet-stream",jar:"application/java-archive",java:"text/x-java-source",jnlp:"application/x-java-jnlp-file",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",log:"text/plain",m3u:"audio/x-mpegurl",m4v:"video/mp4",man:"text/troff",mathml:"application/mathml+xml",mbox:"application/mbox",mdoc:"text/troff",me:"text/troff",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mml:"application/mathml+xml",mng:"video/x-mng",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",mp4v:"video/mp4",mpeg:"video/mpeg",mpg:"video/mpeg",ms:"text/troff",msi:"application/x-msdownload",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",p:"text/x-pascal",pas:"text/x-pascal",pbm:"image/x-portable-bitmap",pdf:"application/pdf",pem:"application/x-x509-ca-cert",pgm:"image/x-portable-graymap",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pl:"text/x-script.perl",pm:"text/x-script.perl-module",png:"image/png",pnm:"image/x-portable-anymap",ppm:"image/x-portable-pixmap",pps:"application/vnd.ms-powerpoint",ppt:"application/vnd.ms-powerpoint",ps:"application/postscript",psd:"image/vnd.adobe.photoshop",py:"text/x-script.python",qt:"video/quicktime",ra:"audio/x-pn-realaudio",rake:"text/x-script.ruby",ram:"audio/x-pn-realaudio",rar:"application/x-rar-compressed",rb:"text/x-script.ruby",rdf:"application/rdf+xml",roff:"text/troff",rpm:"application/x-redhat-package-manager",rss:"application/rss+xml",rtf:"application/rtf",ru:"text/x-script.ruby",s:"text/x-asm",sgm:"text/sgml",sgml:"text/sgml",sh:"application/x-sh",sig:"application/pgp-signature",snd:"audio/basic",so:"application/octet-stream",svg:"image/svg+xml",svgz:"image/svg+xml",swf:"application/x-shockwave-flash",t:"text/troff",tar:"application/x-tar",tbz:"application/x-bzip-compressed-tar",tcl:"application/x-tcl",tex:"application/x-tex",texi:"application/x-texinfo",texinfo:"application/x-texinfo",text:"text/plain",tif:"image/tiff",tiff:"image/tiff",torrent:"application/x-bittorrent",tr:"text/troff",txt:"text/plain",vcf:"text/x-vcard",vcs:"text/x-vcalendar",vrml:"model/vrml",war:"application/java-archive",wav:"audio/x-wav",webp:"image/webp",wma:"audio/x-ms-wma",wmv:"video/x-ms-wmv",wmx:"video/x-ms-wmx",wrl:"model/vrml",wsdl:"application/wsdl+xml",xbm:"image/x-xbitmap",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xml:"application/xml",xpm:"image/x-xpixmap",xsl:"application/xml",xslt:"application/xslt+xml",yaml:"text/yaml",yml:"text/yaml",zip:"application/zip",ttf:"application/x-font-ttf",woff:"application/x-font-woff",woff2:"application/x-font-woff2"},s=Object.keys(i),p=t=>t.split(".").pop(),r=t=>i[t.toLowerCase()]||"application/octet-stream";async function d(t,e,o){try{t.onAborted(()=>new n({message:"Requers is aborted",code:1,statusCode:404}));let a=e.getUrl().replace(/\.\.\//ig,"").replace(/^\.\/?/,"");a=`./${a}`;const m=x.resolve(o,a),c=await l.readFile(m);t.writeStatus("200 OK").writeHeader("content-type",r(p(a))).end(c)}catch(a){t.writeStatus("404 Not Found").end(a.message)}}export{s as extensions,i as exts,p as getExt,d as staticBody};
package/urlencodedBody.js CHANGED
@@ -1,32 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var ApiError = require('./ApiError-b517f53a.js');
6
- var querystring = require('querystring');
7
-
8
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
-
10
- var querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
11
-
12
- const urlencodedBody = (res) => new Promise((resolve, reject) => {
13
- readBody(res, (obj) => resolve(obj), () => {
14
- reject(new ApiError.ApiError({ message: "Can`t parse body", code: 1, statusCode: 404 }));
15
- });
16
- });
17
- function readBody(res, cb, err) {
18
- let buffer = Buffer.from([]);
19
- res.onData((ab, isLast) => {
20
- buffer = Buffer.concat([buffer, Buffer.from(ab)]);
21
- if (isLast) {
22
- try {
23
- cb(querystring__default["default"].parse(buffer.toString()));
24
- } catch (e) {
25
- cb({});
26
- }
27
- }
28
- });
29
- res.onAborted(err);
30
- }
31
-
32
- exports.urlencodedBody = urlencodedBody;
1
+ "use strict";var c=require("./ApiError.js"),d=require("querystring");const f=e=>new Promise((o,t)=>{s(e,r=>o(r),()=>{t(new c.ApiError({message:"Can`t parse body",code:1,statusCode:404}))})});function s(e,o,t){let r=Buffer.from([]);e.onData((a,n)=>{if(r=Buffer.concat([r,Buffer.from(a)]),n)try{o(d.parse(r.toString()))}catch{o({})}}),e.onAborted(t)}exports.urlencodedBody=f;
@@ -0,0 +1 @@
1
+ import{ApiError as a}from"./ApiError.mjs";import c from"querystring";const m=r=>new Promise((e,t)=>{s(r,o=>e(o),()=>{t(new a({message:"Can`t parse body",code:1,statusCode:404}))})});function s(r,e,t){let o=Buffer.from([]);r.onData((f,n)=>{if(o=Buffer.concat([o,Buffer.from(f)]),n)try{e(c.parse(o.toString()))}catch{e({})}}),r.onAborted(t)}export{m as urlencodedBody};
@@ -1,37 +0,0 @@
1
- 'use strict';
2
-
3
- class ApiError extends Error {
4
- constructor(params = "", code = 0, statusCode = 404) {
5
- super();
6
- let paramsObj = {};
7
- if (typeof params === "string") {
8
- paramsObj.message = params;
9
- paramsObj.code = code;
10
- paramsObj.statusCode = statusCode;
11
- } else {
12
- paramsObj = params;
13
- }
14
- this.statusCode = paramsObj.statusCode ?? 404;
15
- this.code = paramsObj.code ?? 0;
16
- this.message = paramsObj.message ?? "";
17
- this.data = paramsObj.data ?? {};
18
- this.headers = paramsObj.headers ?? {};
19
- }
20
- getMessage() {
21
- return this.message;
22
- }
23
- getStatusCode() {
24
- return this.statusCode;
25
- }
26
- getCode() {
27
- return this.code;
28
- }
29
- getData() {
30
- return this.data;
31
- }
32
- getHeaders() {
33
- return this.headers;
34
- }
35
- }
36
-
37
- exports.ApiError = ApiError;