@alwatr/nanotron-api-server 4.2.1 → 4.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,17 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [4.2.2](https://github.com/Alwatr/nanotron/compare/v4.2.1...v4.2.2) (2024-09-29)
7
+
8
+ ### Miscellaneous Chores
9
+
10
+ * **api-server:** change the license to AGPL-3.0 ([fa3347e](https://github.com/Alwatr/nanotron/commit/fa3347e005f926b4f17ccba0bbec19da3b5198ec)) by @ArmanAsadian
11
+
12
+ ### Dependencies update
13
+
14
+ * bump @types/node in the development-dependencies group ([9c8d7d5](https://github.com/Alwatr/nanotron/commit/9c8d7d518d9a5da2ea57ac2b210a8697267e6d3d)) by @dependabot[bot]
15
+ * update ([1c4ef63](https://github.com/Alwatr/nanotron/commit/1c4ef635fc969d4abd416aea2b954de674748da8)) by @AliMD
16
+
6
17
  ## [4.2.1](https://github.com/Alwatr/nanotron/compare/v4.2.0...v4.2.1) (2024-09-24)
7
18
 
8
19
  ### Dependencies update
package/README.md CHANGED
@@ -59,10 +59,10 @@ The following companies, organizations, and individuals support Nitrobase ongoin
59
59
 
60
60
  [![Exir Studio](https://avatars.githubusercontent.com/u/181194967?s=200&v=4)](https://exirstudio.com)
61
61
 
62
- ## License
62
+ ### Contributing
63
63
 
64
- This project is licensed under the AGPL-3.0 License.
64
+ Contributions are welcome! Please read our [contribution guidelines](https://github.com/Alwatr/.github/blob/next/CONTRIBUTING.md) before submitting a pull request.
65
65
 
66
- ## Contributing
66
+ ### License
67
67
 
68
- Contributions are welcome! Please feel free to submit issues and pull requests.
68
+ This project is licensed under the [AGPL-3.0 License](LICENSE).
package/dist/main.cjs CHANGED
@@ -1,5 +1,5 @@
1
- /* @alwatr/nanotron-api-server v4.2.1 */
2
- "use strict";var m=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var b=(a,e)=>{for(var t in e)m(a,t,{get:e[t],enumerable:!0})},M=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of T(e))!N.call(a,s)&&s!==t&&m(a,s,{get:()=>e[s],enumerable:!(r=w(e,s))||r.enumerable});return a};var H=a=>M(m({},"__esModule",{value:!0}),a);var P={};b(P,{HttpMethods:()=>L,HttpStatusCodes:()=>i,HttpStatusMessages:()=>d,NanotronApiServer:()=>R});module.exports=H(P);var L={GET:"GET",HEAD:"HEAD",POST:"POST",PUT:"PUT",DELETE:"DELETE",CONNECT:"CONNECT",OPTIONS:"OPTIONS",TRACE:"TRACE",PATCH:"PATCH"},i={Info_100_Continue:100,Info_101_Switching_Protocols:101,Info_102_Processing:102,Info_103_Early_Hints:103,Success_200_OK:200,Success_201_Created:201,Success_202_Accepted:202,Success_203_Non_Authoritative_Information:203,Success_204_No_Content:204,Success_205_Reset_Content:205,Success_206_Partial_Content:206,Success_207_Multi_Status:207,Success_208_Already_Reported:208,Success_226_IM_Used:226,Redirect_300_Multiple_Choices:300,Redirect_301_Moved_Permanently:301,Redirect_302_Found:302,Redirect_303_See_Other:303,Redirect_304_Not_Modified:304,Redirect_305_Use_Proxy:305,Redirect_306_Switch_Proxy:306,Redirect_307_Temporary_Redirect:307,Redirect_308_Permanent_Redirect:308,Error_Client_400_Bad_Request:400,Error_Client_401_Unauthorized:401,Error_Client_402_Payment_Required:402,Error_Client_403_Forbidden:403,Error_Client_404_Not_Found:404,Error_Client_405_Method_Not_Allowed:405,Error_Client_406_Not_Acceptable:406,Error_Client_407_Proxy_Authentication_Required:407,Error_Client_408_Request_Timeout:408,Error_Client_409_Conflict:409,Error_Client_410_Gone:410,Error_Client_411_Length_Required:411,Error_Client_412_Precondition_Failed:412,Error_Client_413_Payload_Too_Large:413,Error_Client_414_URI_Too_Long:414,Error_Client_415_Unsupported_Media_Type:415,Error_Client_416_Range_Not_Satisfiable:416,Error_Client_417_Expectation_Failed:417,Error_Client_421_Misdirected_Request:421,Error_Client_422_Unprocessable_Entity:422,Error_Client_423_Locked:423,Error_Client_424_Failed_Dependency:424,Error_Client_425_Too_Early:425,Error_Client_426_Upgrade_Required:426,Error_Client_428_Precondition_Required:428,Error_Client_429_Too_Many_Requests:429,Error_Client_431_Request_Header_Fields_Too_Large:431,Error_Client_451_Unavailable_For_Legal_Reasons:451,Error_Server_500_Internal_Server_Error:500,Error_Server_501_Not_Implemented:501,Error_Server_502_Bad_Gateway:502,Error_Server_503_Service_Unavailable:503,Error_Server_504_Gateway_Timeout:504,Error_Server_505_HTTP_Version_Not_Supported:505,Error_Server_506_Variant_Also_Negotiates:506,Error_Server_507_Insufficient_Storage:507,Error_Server_508_Loop_Detected:508,Error_Server_510_Not_Extended:510,Error_Server_511_Network_Authentication_Required:511},d={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var C=require("@alwatr/logger"),h=class{constructor(e,t){this.hasBeenSent_=!1;this.clientRequest=e,this.raw_=t,this.logger_=(0,C.createLogger)(`nt-server-response(${this.clientRequest.remoteAddress})`),this.logger_.logMethodArgs?.("new",this.clientRequest.url.debugId),this.headers={server:"Alwatr Nanotron","content-type":"text/plain"}}get hasBeenSent(){return this.hasBeenSent_}get statusCode(){return this.raw_.statusCode}set statusCode(e){this.raw_.statusCode=e}applyHeaders_(){this.logger_.logMethodArgs?.("applyHeaders_",this.headers);for(let e in this.headers)this.raw_.setHeader(e,this.headers[e])}replyErrorResponse(e){this.logger_.logMethod?.("replyErrorResponse"),this.clientRequest.terminatedHandlers=!0,this.headers["content-type"]="application/json";let t="";if(e.meta!==void 0){let s=typeof e.meta;s==="string"||s==="number"||s==="boolean"||e.meta===null?t=`,"meta":"${e.meta}"`:s==="object"&&(t=`,"meta":${JSON.stringify(e.meta)}`)}let r=`{"ok":false,"errorCode":"${e.errorCode}","errorMessage":"${e.errorMessage}"${t}}`;this.reply(r)}replyError(e){this.logger_.logMethodArgs?.("replyError",{error:e}),this.clientRequest.terminatedHandlers=!0;let t=this.statusCode;t<i.Error_Client_400_Bad_Request&&(this.statusCode=t=500),e instanceof Error?this.replyErrorResponse({ok:!1,errorCode:e.name==="Error"?"error_"+t:(e.name+"").toLowerCase(),errorMessage:e.message}):typeof e=="string"?this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:e}):typeof e=="object"&&e!==null?this.replyJson(e):this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:d[t]})}replyJson(e){this.logger_.logMethodArgs?.("replyJson",{responseJson:e});let t;try{t=JSON.stringify(e)}catch(r){this.logger_.error("replyJson","reply_json_stringify_failed",r,this.clientRequest.url.debugId),this.statusCode=i.Error_Server_500_Internal_Server_Error,this.replyErrorResponse({ok:!1,errorCode:"reply_json_stringify_failed",errorMessage:"Failed to stringify response JSON."});return}this.headers["content-type"]="application/json",this.reply(t)}reply(e){if(this.logger_.logMethodArgs?.("reply",this.clientRequest.url.debugId),this.raw_.writableFinished&&this.hasBeenSent_===!1&&(this.logger_.accident("reply","server_response_writable_finished_directly"),this.hasBeenSent_=!0),this.hasBeenSent_){this.logger_.accident("reply","reply_already_sent",{url:this.clientRequest.url.debugId,replySent:this.hasBeenSent_,writableFinished:this.raw_.writableFinished});return}this.hasBeenSent_=!0;try{typeof e=="string"&&(e=Buffer.from(e)),this.headers["content-length"]=e.byteLength,this.applyHeaders_(),this.raw_.end(e,"binary")}catch(t){this.logger_.error("reply","server_response_error",t,this.clientRequest.url.debugId),this.hasBeenSent_=!1}}};var v=require("@alwatr/logger"),p=class{constructor(e,t,r,s){this.sharedMeta={};this.raw_=t,this.url=e,this.routeOption=s,this.remoteAddress=this.getRemoteAddress__(),this.logger_=(0,v.createLogger)(`nt-client-request(${this.remoteAddress})`),this.logger_.logMethodArgs?.("new",e.debugId),this.serverResponse=new h(this,r)}get headers(){return this.raw_.headers}get queryParams(){if(this.queryParams__===void 0){this.queryParams__={};for(let[e,t]of this.url.searchParams.entries())this.queryParams__[e]=t}return this.queryParams__}getBodyRaw(){return new Promise((e,t)=>{let r=this.url.method;if(!(r==="POST"||r==="PUT"||r==="PATCH"))return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_405_Method_Not_Allowed,t(new Error("body_not_allowed"));let s=+this.raw_.headers["content-length"];if(Number.isNaN(s)||s===0)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_411_Length_Required,t(new Error("body_length_required"));if(s>this.routeOption.bodyLimit)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let o=[],n=0,f=l=>{if(n+=l.length,o.push(l),n>this.routeOption.bodyLimit)return this.raw_.removeListener("data",f),this.raw_.removeListener("end",_),this.raw_.removeListener("error",_),o.length=0,this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"))},_=l=>{if(this.raw_.removeListener("data",f),this.raw_.removeListener("end",_),this.raw_.removeListener("error",_),l!==void 0)return o.length=0,this.serverResponse.statusCode=i.Error_Client_400_Bad_Request,t(l);if(n!==s)return o.length=0,this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let q=Buffer.concat(o);e(q)};this.raw_.on("data",f),this.raw_.on("end",_),this.raw_.on("error",_),this.raw_.resume()})}getRemoteAddress__(){return this.raw_.headers["x-forwarded-for"]?.split(",").pop()?.trim()||this.raw_.socket.remoteAddress||null}};var E=require("node:url"),c=class c extends E.URL{constructor(e,t){let r=e.url??"";t!=="/"&&r.indexOf(t)===0&&(r=r.slice(t.length-1)),r=r.replace(c.versionPattern_,"/"),super(r,"http://hostname/"),this.method=(e.method??"GET").toUpperCase(),this.debugId=`[${this.method}]${this.pathname}`}};c.versionPattern_=new RegExp("^/v[0-9]+/");var u=c;var S=require("node:http"),y=require("@alwatr/logger");(0,y.definePackage)("@alwatr/nanotron-api-server","4.2.1");var g=class g{constructor(e){this.config_={...g.defaultConfig_,...e},this.logger_=(0,y.createLogger)("nt-api-server"+(this.config_.port!==80?":"+this.config_.port:"")),this.logger_.logMethodArgs?.("new",{config:this.config_}),this.handleClientRequest_=this.handleClientRequest_.bind(this),this.handleServerError_=this.handleServerError_.bind(this),this.handleClientError_=this.handleClientError_.bind(this),this.routeHandlerList__={exact:{},startsWith:{}},this.httpServer=(0,S.createServer)({keepAlive:!0,keepAliveInitialDelay:0,noDelay:!0},this.handleClientRequest_),this.httpServer.requestTimeout=this.config_.requestTimeout,this.httpServer.keepAliveTimeout=this.config_.keepAliveTimeout,this.httpServer.headersTimeout=this.config_.headersTimeout,this.httpServer.listen(this.config_.port,this.config_.host,()=>{this.logger_.logOther?.(`listening on ${this.config_.host}:${this.config_.port}`)}),this.httpServer.on("error",this.handleServerError_),this.httpServer.on("clientError",this.handleClientError_)}close(){this.logger_.logMethod?.("close"),this.httpServer.close()}getRouteOption_(e){if(this.logger_.logMethod?.("getRouteOption_"),Object.hasOwn(this.routeHandlerList__.exact,e.method)&&Object.hasOwn(this.routeHandlerList__.exact[e.method],e.pathname))return this.routeHandlerList__.exact[e.method][e.pathname];if(Object.hasOwn(this.routeHandlerList__.startsWith,e.method)){let t=this.routeHandlerList__.startsWith[e.method];for(let r in t)if(r.indexOf(e.pathname)===0)return t[r]}return this.logger_.incident?.("getRouteOption_","route_not_found",{method:e.method,url:e.pathname}),null}setRouteOption_(e){var r;this.logger_.logMethodArgs?.("setRouteOption_",e);let t=this.routeHandlerList__[e.matchType];if(t[r=e.method]??(t[r]={}),Object.hasOwn(t[e.method],e.url))throw this.logger_.error("defineRoute","route_already_exists",e),new Error("route_already_exists");t[e.method][e.url]=e}defineRoute(e){let t={matchType:"exact",preHandlers:[],postHandlers:[],bodyLimit:this.config_.bodyLimit,...e};this.logger_.logMethodArgs?.("defineRoute",t),this.setRouteOption_(t)}handleServerError_(e){e.code==="EADDRINUSE"?this.logger_.error("handleServerError_","address_in_use",e):this.logger_.error("handleServerError_","http_server_error",e)}handleClientError_(e,t){this.logger_.accident("handleClientError_","http_server_client_error",{errCode:e.code,errMessage:e.message});let r=e.code?.toLowerCase()??`error_${i.Error_Client_400_Bad_Request}`,s=e.message??d[i.Error_Client_400_Bad_Request],o=`{"ok":false,"errorCode":"${r}","errorMessage":"${s}"}`,n=[`HTTP/1.1 ${i.Error_Client_400_Bad_Request} ${d[i.Error_Client_400_Bad_Request]}`,"content-type: application/json",`content-length: ${Buffer.byteLength(o)}`,`\r
1
+ /* @alwatr/nanotron-api-server v4.2.2 */
2
+ "use strict";var m=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var b=(a,e)=>{for(var t in e)m(a,t,{get:e[t],enumerable:!0})},M=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of T(e))!N.call(a,s)&&s!==t&&m(a,s,{get:()=>e[s],enumerable:!(r=w(e,s))||r.enumerable});return a};var H=a=>M(m({},"__esModule",{value:!0}),a);var P={};b(P,{HttpMethods:()=>L,HttpStatusCodes:()=>i,HttpStatusMessages:()=>d,NanotronApiServer:()=>R});module.exports=H(P);var L={GET:"GET",HEAD:"HEAD",POST:"POST",PUT:"PUT",DELETE:"DELETE",CONNECT:"CONNECT",OPTIONS:"OPTIONS",TRACE:"TRACE",PATCH:"PATCH"},i={Info_100_Continue:100,Info_101_Switching_Protocols:101,Info_102_Processing:102,Info_103_Early_Hints:103,Success_200_OK:200,Success_201_Created:201,Success_202_Accepted:202,Success_203_Non_Authoritative_Information:203,Success_204_No_Content:204,Success_205_Reset_Content:205,Success_206_Partial_Content:206,Success_207_Multi_Status:207,Success_208_Already_Reported:208,Success_226_IM_Used:226,Redirect_300_Multiple_Choices:300,Redirect_301_Moved_Permanently:301,Redirect_302_Found:302,Redirect_303_See_Other:303,Redirect_304_Not_Modified:304,Redirect_305_Use_Proxy:305,Redirect_306_Switch_Proxy:306,Redirect_307_Temporary_Redirect:307,Redirect_308_Permanent_Redirect:308,Error_Client_400_Bad_Request:400,Error_Client_401_Unauthorized:401,Error_Client_402_Payment_Required:402,Error_Client_403_Forbidden:403,Error_Client_404_Not_Found:404,Error_Client_405_Method_Not_Allowed:405,Error_Client_406_Not_Acceptable:406,Error_Client_407_Proxy_Authentication_Required:407,Error_Client_408_Request_Timeout:408,Error_Client_409_Conflict:409,Error_Client_410_Gone:410,Error_Client_411_Length_Required:411,Error_Client_412_Precondition_Failed:412,Error_Client_413_Payload_Too_Large:413,Error_Client_414_URI_Too_Long:414,Error_Client_415_Unsupported_Media_Type:415,Error_Client_416_Range_Not_Satisfiable:416,Error_Client_417_Expectation_Failed:417,Error_Client_421_Misdirected_Request:421,Error_Client_422_Unprocessable_Entity:422,Error_Client_423_Locked:423,Error_Client_424_Failed_Dependency:424,Error_Client_425_Too_Early:425,Error_Client_426_Upgrade_Required:426,Error_Client_428_Precondition_Required:428,Error_Client_429_Too_Many_Requests:429,Error_Client_431_Request_Header_Fields_Too_Large:431,Error_Client_451_Unavailable_For_Legal_Reasons:451,Error_Server_500_Internal_Server_Error:500,Error_Server_501_Not_Implemented:501,Error_Server_502_Bad_Gateway:502,Error_Server_503_Service_Unavailable:503,Error_Server_504_Gateway_Timeout:504,Error_Server_505_HTTP_Version_Not_Supported:505,Error_Server_506_Variant_Also_Negotiates:506,Error_Server_507_Insufficient_Storage:507,Error_Server_508_Loop_Detected:508,Error_Server_510_Not_Extended:510,Error_Server_511_Network_Authentication_Required:511},d={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var C=require("@alwatr/logger"),h=class{constructor(e,t){this.hasBeenSent_=!1;this.clientRequest=e,this.raw_=t,this.logger_=(0,C.createLogger)(`nt-server-response(${this.clientRequest.remoteAddress})`),this.logger_.logMethodArgs?.("new",this.clientRequest.url.debugId),this.headers={server:"Alwatr Nanotron","content-type":"text/plain"}}get hasBeenSent(){return this.hasBeenSent_}get statusCode(){return this.raw_.statusCode}set statusCode(e){this.raw_.statusCode=e}applyHeaders_(){this.logger_.logMethodArgs?.("applyHeaders_",this.headers);for(let e in this.headers)this.raw_.setHeader(e,this.headers[e])}replyErrorResponse(e){this.logger_.logMethod?.("replyErrorResponse"),this.clientRequest.terminatedHandlers=!0,this.headers["content-type"]="application/json";let t="";if(e.meta!==void 0){let s=typeof e.meta;s==="string"||s==="number"||s==="boolean"||e.meta===null?t=`,"meta":"${e.meta}"`:s==="object"&&(t=`,"meta":${JSON.stringify(e.meta)}`)}let r=`{"ok":false,"errorCode":"${e.errorCode}","errorMessage":"${e.errorMessage}"${t}}`;this.reply(r)}replyError(e){this.logger_.logMethodArgs?.("replyError",{error:e}),this.clientRequest.terminatedHandlers=!0;let t=this.statusCode;t<i.Error_Client_400_Bad_Request&&(this.statusCode=t=500),e instanceof Error?this.replyErrorResponse({ok:!1,errorCode:e.name==="Error"?"error_"+t:(e.name+"").toLowerCase(),errorMessage:e.message}):typeof e=="string"?this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:e}):typeof e=="object"&&e!==null?this.replyJson(e):this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:d[t]})}replyJson(e){this.logger_.logMethodArgs?.("replyJson",{responseJson:e});let t;try{t=JSON.stringify(e)}catch(r){this.logger_.error("replyJson","reply_json_stringify_failed",r,this.clientRequest.url.debugId),this.statusCode=i.Error_Server_500_Internal_Server_Error,this.replyErrorResponse({ok:!1,errorCode:"reply_json_stringify_failed",errorMessage:"Failed to stringify response JSON."});return}this.headers["content-type"]="application/json",this.reply(t)}reply(e){if(this.logger_.logMethodArgs?.("reply",this.clientRequest.url.debugId),this.raw_.writableFinished&&this.hasBeenSent_===!1&&(this.logger_.accident("reply","server_response_writable_finished_directly"),this.hasBeenSent_=!0),this.hasBeenSent_){this.logger_.accident("reply","reply_already_sent",{url:this.clientRequest.url.debugId,replySent:this.hasBeenSent_,writableFinished:this.raw_.writableFinished});return}this.hasBeenSent_=!0;try{typeof e=="string"&&(e=Buffer.from(e)),this.headers["content-length"]=e.byteLength,this.applyHeaders_(),this.raw_.end(e,"binary")}catch(t){this.logger_.error("reply","server_response_error",t,this.clientRequest.url.debugId),this.hasBeenSent_=!1}}};var v=require("@alwatr/logger"),p=class{constructor(e,t,r,s){this.sharedMeta={};this.raw_=t,this.url=e,this.routeOption=s,this.remoteAddress=this.getRemoteAddress__(),this.logger_=(0,v.createLogger)(`nt-client-request(${this.remoteAddress})`),this.logger_.logMethodArgs?.("new",e.debugId),this.serverResponse=new h(this,r)}get headers(){return this.raw_.headers}get queryParams(){if(this.queryParams__===void 0){this.queryParams__={};for(let[e,t]of this.url.searchParams.entries())this.queryParams__[e]=t}return this.queryParams__}getBodyRaw(){return new Promise((e,t)=>{let r=this.url.method;if(!(r==="POST"||r==="PUT"||r==="PATCH"))return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_405_Method_Not_Allowed,t(new Error("body_not_allowed"));let s=+this.raw_.headers["content-length"];if(Number.isNaN(s)||s===0)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_411_Length_Required,t(new Error("body_length_required"));if(s>this.routeOption.bodyLimit)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let o=[],n=0,f=l=>{if(n+=l.length,o.push(l),n>this.routeOption.bodyLimit)return this.raw_.removeListener("data",f),this.raw_.removeListener("end",_),this.raw_.removeListener("error",_),o.length=0,this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"))},_=l=>{if(this.raw_.removeListener("data",f),this.raw_.removeListener("end",_),this.raw_.removeListener("error",_),l!==void 0)return o.length=0,this.serverResponse.statusCode=i.Error_Client_400_Bad_Request,t(l);if(n!==s)return o.length=0,this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let q=Buffer.concat(o);e(q)};this.raw_.on("data",f),this.raw_.on("end",_),this.raw_.on("error",_),this.raw_.resume()})}getRemoteAddress__(){return this.raw_.headers["x-forwarded-for"]?.split(",").pop()?.trim()||this.raw_.socket.remoteAddress||null}};var E=require("node:url"),c=class c extends E.URL{constructor(e,t){let r=e.url??"";t!=="/"&&r.indexOf(t)===0&&(r=r.slice(t.length-1)),r=r.replace(c.versionPattern_,"/"),super(r,"http://hostname/"),this.method=(e.method??"GET").toUpperCase(),this.debugId=`[${this.method}]${this.pathname}`}};c.versionPattern_=new RegExp("^/v[0-9]+/");var u=c;var S=require("node:http"),y=require("@alwatr/logger");(0,y.definePackage)("@alwatr/nanotron-api-server","4.2.2");var g=class g{constructor(e){this.config_={...g.defaultConfig_,...e},this.logger_=(0,y.createLogger)("nt-api-server"+(this.config_.port!==80?":"+this.config_.port:"")),this.logger_.logMethodArgs?.("new",{config:this.config_}),this.handleClientRequest_=this.handleClientRequest_.bind(this),this.handleServerError_=this.handleServerError_.bind(this),this.handleClientError_=this.handleClientError_.bind(this),this.routeHandlerList__={exact:{},startsWith:{}},this.httpServer=(0,S.createServer)({keepAlive:!0,keepAliveInitialDelay:0,noDelay:!0},this.handleClientRequest_),this.httpServer.requestTimeout=this.config_.requestTimeout,this.httpServer.keepAliveTimeout=this.config_.keepAliveTimeout,this.httpServer.headersTimeout=this.config_.headersTimeout,this.httpServer.listen(this.config_.port,this.config_.host,()=>{this.logger_.logOther?.(`listening on ${this.config_.host}:${this.config_.port}`)}),this.httpServer.on("error",this.handleServerError_),this.httpServer.on("clientError",this.handleClientError_)}close(){this.logger_.logMethod?.("close"),this.httpServer.close()}getRouteOption_(e){if(this.logger_.logMethod?.("getRouteOption_"),Object.hasOwn(this.routeHandlerList__.exact,e.method)&&Object.hasOwn(this.routeHandlerList__.exact[e.method],e.pathname))return this.routeHandlerList__.exact[e.method][e.pathname];if(Object.hasOwn(this.routeHandlerList__.startsWith,e.method)){let t=this.routeHandlerList__.startsWith[e.method];for(let r in t)if(r.indexOf(e.pathname)===0)return t[r]}return this.logger_.incident?.("getRouteOption_","route_not_found",{method:e.method,url:e.pathname}),null}setRouteOption_(e){var r;this.logger_.logMethodArgs?.("setRouteOption_",e);let t=this.routeHandlerList__[e.matchType];if(t[r=e.method]??(t[r]={}),Object.hasOwn(t[e.method],e.url))throw this.logger_.error("defineRoute","route_already_exists",e),new Error("route_already_exists");t[e.method][e.url]=e}defineRoute(e){let t={matchType:"exact",preHandlers:[],postHandlers:[],bodyLimit:this.config_.bodyLimit,...e};this.logger_.logMethodArgs?.("defineRoute",t),this.setRouteOption_(t)}handleServerError_(e){e.code==="EADDRINUSE"?this.logger_.error("handleServerError_","address_in_use",e):this.logger_.error("handleServerError_","http_server_error",e)}handleClientError_(e,t){this.logger_.accident("handleClientError_","http_server_client_error",{errCode:e.code,errMessage:e.message});let r=e.code?.toLowerCase()??`error_${i.Error_Client_400_Bad_Request}`,s=e.message??d[i.Error_Client_400_Bad_Request],o=`{"ok":false,"errorCode":"${r}","errorMessage":"${s}"}`,n=[`HTTP/1.1 ${i.Error_Client_400_Bad_Request} ${d[i.Error_Client_400_Bad_Request]}`,"content-type: application/json",`content-length: ${Buffer.byteLength(o)}`,`\r
3
3
  `].join(`\r
4
4
  `);t.end(n+o)}async handleClientRequest_(e,t){if(this.logger_.logMethod?.("handleClientRequest_"),e.url===void 0){this.logger_.accident("handleClientRequest_","http_server_url_undefined");return}let r=new u(e,this.config_.prefix),s=this.getRouteOption_(r),o=new p(r,e,t,s);if(s===null){o.serverResponse.statusCode=i.Error_Client_404_Not_Found,o.serverResponse.replyError();return}try{for(let n of s.preHandlers){if(o.terminatedHandlers===!0)return;await n.call(o,o,o.serverResponse,o.sharedMeta)}await s.handler.call(o,o,o.serverResponse,o.sharedMeta);for(let n of s.postHandlers){if(o.terminatedHandlers===!0)return;await n.call(o,o,o.serverResponse,o.sharedMeta)}}catch(n){this.logger_.error("handleClientRequest_","route_handler_error",n,r.debugId),o.serverResponse.statusCode<i.Error_Client_400_Bad_Request&&(o.serverResponse.statusCode=i.Error_Server_500_Internal_Server_Error),o.serverResponse.replyError(n)}}};g.defaultConfig_={host:"0.0.0.0",port:80,requestTimeout:1e4,headersTimeout:13e4,keepAliveTimeout:12e4,healthRoute:!0,allowAllOrigin:!1,prefix:"/api/",bodyLimit:1048576};var R=g;0&&(module.exports={HttpMethods,HttpStatusCodes,HttpStatusMessages,NanotronApiServer});
5
5
  //# sourceMappingURL=main.cjs.map
package/dist/main.mjs CHANGED
@@ -1,5 +1,5 @@
1
- /* @alwatr/nanotron-api-server v4.2.1 */
2
- var w={GET:"GET",HEAD:"HEAD",POST:"POST",PUT:"PUT",DELETE:"DELETE",CONNECT:"CONNECT",OPTIONS:"OPTIONS",TRACE:"TRACE",PATCH:"PATCH"},i={Info_100_Continue:100,Info_101_Switching_Protocols:101,Info_102_Processing:102,Info_103_Early_Hints:103,Success_200_OK:200,Success_201_Created:201,Success_202_Accepted:202,Success_203_Non_Authoritative_Information:203,Success_204_No_Content:204,Success_205_Reset_Content:205,Success_206_Partial_Content:206,Success_207_Multi_Status:207,Success_208_Already_Reported:208,Success_226_IM_Used:226,Redirect_300_Multiple_Choices:300,Redirect_301_Moved_Permanently:301,Redirect_302_Found:302,Redirect_303_See_Other:303,Redirect_304_Not_Modified:304,Redirect_305_Use_Proxy:305,Redirect_306_Switch_Proxy:306,Redirect_307_Temporary_Redirect:307,Redirect_308_Permanent_Redirect:308,Error_Client_400_Bad_Request:400,Error_Client_401_Unauthorized:401,Error_Client_402_Payment_Required:402,Error_Client_403_Forbidden:403,Error_Client_404_Not_Found:404,Error_Client_405_Method_Not_Allowed:405,Error_Client_406_Not_Acceptable:406,Error_Client_407_Proxy_Authentication_Required:407,Error_Client_408_Request_Timeout:408,Error_Client_409_Conflict:409,Error_Client_410_Gone:410,Error_Client_411_Length_Required:411,Error_Client_412_Precondition_Failed:412,Error_Client_413_Payload_Too_Large:413,Error_Client_414_URI_Too_Long:414,Error_Client_415_Unsupported_Media_Type:415,Error_Client_416_Range_Not_Satisfiable:416,Error_Client_417_Expectation_Failed:417,Error_Client_421_Misdirected_Request:421,Error_Client_422_Unprocessable_Entity:422,Error_Client_423_Locked:423,Error_Client_424_Failed_Dependency:424,Error_Client_425_Too_Early:425,Error_Client_426_Upgrade_Required:426,Error_Client_428_Precondition_Required:428,Error_Client_429_Too_Many_Requests:429,Error_Client_431_Request_Header_Fields_Too_Large:431,Error_Client_451_Unavailable_For_Legal_Reasons:451,Error_Server_500_Internal_Server_Error:500,Error_Server_501_Not_Implemented:501,Error_Server_502_Bad_Gateway:502,Error_Server_503_Service_Unavailable:503,Error_Server_504_Gateway_Timeout:504,Error_Server_505_HTTP_Version_Not_Supported:505,Error_Server_506_Variant_Also_Negotiates:506,Error_Server_507_Insufficient_Storage:507,Error_Server_508_Loop_Detected:508,Error_Server_510_Not_Extended:510,Error_Server_511_Network_Authentication_Required:511},d={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};import{createLogger as R}from"@alwatr/logger";var l=class{constructor(e,t){this.hasBeenSent_=!1;this.clientRequest=e,this.raw_=t,this.logger_=R(`nt-server-response(${this.clientRequest.remoteAddress})`),this.logger_.logMethodArgs?.("new",this.clientRequest.url.debugId),this.headers={server:"Alwatr Nanotron","content-type":"text/plain"}}get hasBeenSent(){return this.hasBeenSent_}get statusCode(){return this.raw_.statusCode}set statusCode(e){this.raw_.statusCode=e}applyHeaders_(){this.logger_.logMethodArgs?.("applyHeaders_",this.headers);for(let e in this.headers)this.raw_.setHeader(e,this.headers[e])}replyErrorResponse(e){this.logger_.logMethod?.("replyErrorResponse"),this.clientRequest.terminatedHandlers=!0,this.headers["content-type"]="application/json";let t="";if(e.meta!==void 0){let s=typeof e.meta;s==="string"||s==="number"||s==="boolean"||e.meta===null?t=`,"meta":"${e.meta}"`:s==="object"&&(t=`,"meta":${JSON.stringify(e.meta)}`)}let r=`{"ok":false,"errorCode":"${e.errorCode}","errorMessage":"${e.errorMessage}"${t}}`;this.reply(r)}replyError(e){this.logger_.logMethodArgs?.("replyError",{error:e}),this.clientRequest.terminatedHandlers=!0;let t=this.statusCode;t<i.Error_Client_400_Bad_Request&&(this.statusCode=t=500),e instanceof Error?this.replyErrorResponse({ok:!1,errorCode:e.name==="Error"?"error_"+t:(e.name+"").toLowerCase(),errorMessage:e.message}):typeof e=="string"?this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:e}):typeof e=="object"&&e!==null?this.replyJson(e):this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:d[t]})}replyJson(e){this.logger_.logMethodArgs?.("replyJson",{responseJson:e});let t;try{t=JSON.stringify(e)}catch(r){this.logger_.error("replyJson","reply_json_stringify_failed",r,this.clientRequest.url.debugId),this.statusCode=i.Error_Server_500_Internal_Server_Error,this.replyErrorResponse({ok:!1,errorCode:"reply_json_stringify_failed",errorMessage:"Failed to stringify response JSON."});return}this.headers["content-type"]="application/json",this.reply(t)}reply(e){if(this.logger_.logMethodArgs?.("reply",this.clientRequest.url.debugId),this.raw_.writableFinished&&this.hasBeenSent_===!1&&(this.logger_.accident("reply","server_response_writable_finished_directly"),this.hasBeenSent_=!0),this.hasBeenSent_){this.logger_.accident("reply","reply_already_sent",{url:this.clientRequest.url.debugId,replySent:this.hasBeenSent_,writableFinished:this.raw_.writableFinished});return}this.hasBeenSent_=!0;try{typeof e=="string"&&(e=Buffer.from(e)),this.headers["content-length"]=e.byteLength,this.applyHeaders_(),this.raw_.end(e,"binary")}catch(t){this.logger_.error("reply","server_response_error",t,this.clientRequest.url.debugId),this.hasBeenSent_=!1}}};import{createLogger as C}from"@alwatr/logger";var h=class{constructor(e,t,r,s){this.sharedMeta={};this.raw_=t,this.url=e,this.routeOption=s,this.remoteAddress=this.getRemoteAddress__(),this.logger_=C(`nt-client-request(${this.remoteAddress})`),this.logger_.logMethodArgs?.("new",e.debugId),this.serverResponse=new l(this,r)}get headers(){return this.raw_.headers}get queryParams(){if(this.queryParams__===void 0){this.queryParams__={};for(let[e,t]of this.url.searchParams.entries())this.queryParams__[e]=t}return this.queryParams__}getBodyRaw(){return new Promise((e,t)=>{let r=this.url.method;if(!(r==="POST"||r==="PUT"||r==="PATCH"))return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_405_Method_Not_Allowed,t(new Error("body_not_allowed"));let s=+this.raw_.headers["content-length"];if(Number.isNaN(s)||s===0)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_411_Length_Required,t(new Error("body_length_required"));if(s>this.routeOption.bodyLimit)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let o=[],n=0,g=_=>{if(n+=_.length,o.push(_),n>this.routeOption.bodyLimit)return this.raw_.removeListener("data",g),this.raw_.removeListener("end",a),this.raw_.removeListener("error",a),o.length=0,this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"))},a=_=>{if(this.raw_.removeListener("data",g),this.raw_.removeListener("end",a),this.raw_.removeListener("error",a),_!==void 0)return o.length=0,this.serverResponse.statusCode=i.Error_Client_400_Bad_Request,t(_);if(n!==s)return o.length=0,this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let m=Buffer.concat(o);e(m)};this.raw_.on("data",g),this.raw_.on("end",a),this.raw_.on("error",a),this.raw_.resume()})}getRemoteAddress__(){return this.raw_.headers["x-forwarded-for"]?.split(",").pop()?.trim()||this.raw_.socket.remoteAddress||null}};import{URL as v}from"node:url";var u=class u extends v{constructor(e,t){let r=e.url??"";t!=="/"&&r.indexOf(t)===0&&(r=r.slice(t.length-1)),r=r.replace(u.versionPattern_,"/"),super(r,"http://hostname/"),this.method=(e.method??"GET").toUpperCase(),this.debugId=`[${this.method}]${this.pathname}`}};u.versionPattern_=new RegExp("^/v[0-9]+/");var p=u;import{createServer as E}from"node:http";import{createLogger as S,definePackage as q}from"@alwatr/logger";q("@alwatr/nanotron-api-server","4.2.1");var c=class c{constructor(e){this.config_={...c.defaultConfig_,...e},this.logger_=S("nt-api-server"+(this.config_.port!==80?":"+this.config_.port:"")),this.logger_.logMethodArgs?.("new",{config:this.config_}),this.handleClientRequest_=this.handleClientRequest_.bind(this),this.handleServerError_=this.handleServerError_.bind(this),this.handleClientError_=this.handleClientError_.bind(this),this.routeHandlerList__={exact:{},startsWith:{}},this.httpServer=E({keepAlive:!0,keepAliveInitialDelay:0,noDelay:!0},this.handleClientRequest_),this.httpServer.requestTimeout=this.config_.requestTimeout,this.httpServer.keepAliveTimeout=this.config_.keepAliveTimeout,this.httpServer.headersTimeout=this.config_.headersTimeout,this.httpServer.listen(this.config_.port,this.config_.host,()=>{this.logger_.logOther?.(`listening on ${this.config_.host}:${this.config_.port}`)}),this.httpServer.on("error",this.handleServerError_),this.httpServer.on("clientError",this.handleClientError_)}close(){this.logger_.logMethod?.("close"),this.httpServer.close()}getRouteOption_(e){if(this.logger_.logMethod?.("getRouteOption_"),Object.hasOwn(this.routeHandlerList__.exact,e.method)&&Object.hasOwn(this.routeHandlerList__.exact[e.method],e.pathname))return this.routeHandlerList__.exact[e.method][e.pathname];if(Object.hasOwn(this.routeHandlerList__.startsWith,e.method)){let t=this.routeHandlerList__.startsWith[e.method];for(let r in t)if(r.indexOf(e.pathname)===0)return t[r]}return this.logger_.incident?.("getRouteOption_","route_not_found",{method:e.method,url:e.pathname}),null}setRouteOption_(e){var r;this.logger_.logMethodArgs?.("setRouteOption_",e);let t=this.routeHandlerList__[e.matchType];if(t[r=e.method]??(t[r]={}),Object.hasOwn(t[e.method],e.url))throw this.logger_.error("defineRoute","route_already_exists",e),new Error("route_already_exists");t[e.method][e.url]=e}defineRoute(e){let t={matchType:"exact",preHandlers:[],postHandlers:[],bodyLimit:this.config_.bodyLimit,...e};this.logger_.logMethodArgs?.("defineRoute",t),this.setRouteOption_(t)}handleServerError_(e){e.code==="EADDRINUSE"?this.logger_.error("handleServerError_","address_in_use",e):this.logger_.error("handleServerError_","http_server_error",e)}handleClientError_(e,t){this.logger_.accident("handleClientError_","http_server_client_error",{errCode:e.code,errMessage:e.message});let r=e.code?.toLowerCase()??`error_${i.Error_Client_400_Bad_Request}`,s=e.message??d[i.Error_Client_400_Bad_Request],o=`{"ok":false,"errorCode":"${r}","errorMessage":"${s}"}`,n=[`HTTP/1.1 ${i.Error_Client_400_Bad_Request} ${d[i.Error_Client_400_Bad_Request]}`,"content-type: application/json",`content-length: ${Buffer.byteLength(o)}`,`\r
1
+ /* @alwatr/nanotron-api-server v4.2.2 */
2
+ var w={GET:"GET",HEAD:"HEAD",POST:"POST",PUT:"PUT",DELETE:"DELETE",CONNECT:"CONNECT",OPTIONS:"OPTIONS",TRACE:"TRACE",PATCH:"PATCH"},i={Info_100_Continue:100,Info_101_Switching_Protocols:101,Info_102_Processing:102,Info_103_Early_Hints:103,Success_200_OK:200,Success_201_Created:201,Success_202_Accepted:202,Success_203_Non_Authoritative_Information:203,Success_204_No_Content:204,Success_205_Reset_Content:205,Success_206_Partial_Content:206,Success_207_Multi_Status:207,Success_208_Already_Reported:208,Success_226_IM_Used:226,Redirect_300_Multiple_Choices:300,Redirect_301_Moved_Permanently:301,Redirect_302_Found:302,Redirect_303_See_Other:303,Redirect_304_Not_Modified:304,Redirect_305_Use_Proxy:305,Redirect_306_Switch_Proxy:306,Redirect_307_Temporary_Redirect:307,Redirect_308_Permanent_Redirect:308,Error_Client_400_Bad_Request:400,Error_Client_401_Unauthorized:401,Error_Client_402_Payment_Required:402,Error_Client_403_Forbidden:403,Error_Client_404_Not_Found:404,Error_Client_405_Method_Not_Allowed:405,Error_Client_406_Not_Acceptable:406,Error_Client_407_Proxy_Authentication_Required:407,Error_Client_408_Request_Timeout:408,Error_Client_409_Conflict:409,Error_Client_410_Gone:410,Error_Client_411_Length_Required:411,Error_Client_412_Precondition_Failed:412,Error_Client_413_Payload_Too_Large:413,Error_Client_414_URI_Too_Long:414,Error_Client_415_Unsupported_Media_Type:415,Error_Client_416_Range_Not_Satisfiable:416,Error_Client_417_Expectation_Failed:417,Error_Client_421_Misdirected_Request:421,Error_Client_422_Unprocessable_Entity:422,Error_Client_423_Locked:423,Error_Client_424_Failed_Dependency:424,Error_Client_425_Too_Early:425,Error_Client_426_Upgrade_Required:426,Error_Client_428_Precondition_Required:428,Error_Client_429_Too_Many_Requests:429,Error_Client_431_Request_Header_Fields_Too_Large:431,Error_Client_451_Unavailable_For_Legal_Reasons:451,Error_Server_500_Internal_Server_Error:500,Error_Server_501_Not_Implemented:501,Error_Server_502_Bad_Gateway:502,Error_Server_503_Service_Unavailable:503,Error_Server_504_Gateway_Timeout:504,Error_Server_505_HTTP_Version_Not_Supported:505,Error_Server_506_Variant_Also_Negotiates:506,Error_Server_507_Insufficient_Storage:507,Error_Server_508_Loop_Detected:508,Error_Server_510_Not_Extended:510,Error_Server_511_Network_Authentication_Required:511},d={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};import{createLogger as R}from"@alwatr/logger";var l=class{constructor(e,t){this.hasBeenSent_=!1;this.clientRequest=e,this.raw_=t,this.logger_=R(`nt-server-response(${this.clientRequest.remoteAddress})`),this.logger_.logMethodArgs?.("new",this.clientRequest.url.debugId),this.headers={server:"Alwatr Nanotron","content-type":"text/plain"}}get hasBeenSent(){return this.hasBeenSent_}get statusCode(){return this.raw_.statusCode}set statusCode(e){this.raw_.statusCode=e}applyHeaders_(){this.logger_.logMethodArgs?.("applyHeaders_",this.headers);for(let e in this.headers)this.raw_.setHeader(e,this.headers[e])}replyErrorResponse(e){this.logger_.logMethod?.("replyErrorResponse"),this.clientRequest.terminatedHandlers=!0,this.headers["content-type"]="application/json";let t="";if(e.meta!==void 0){let s=typeof e.meta;s==="string"||s==="number"||s==="boolean"||e.meta===null?t=`,"meta":"${e.meta}"`:s==="object"&&(t=`,"meta":${JSON.stringify(e.meta)}`)}let r=`{"ok":false,"errorCode":"${e.errorCode}","errorMessage":"${e.errorMessage}"${t}}`;this.reply(r)}replyError(e){this.logger_.logMethodArgs?.("replyError",{error:e}),this.clientRequest.terminatedHandlers=!0;let t=this.statusCode;t<i.Error_Client_400_Bad_Request&&(this.statusCode=t=500),e instanceof Error?this.replyErrorResponse({ok:!1,errorCode:e.name==="Error"?"error_"+t:(e.name+"").toLowerCase(),errorMessage:e.message}):typeof e=="string"?this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:e}):typeof e=="object"&&e!==null?this.replyJson(e):this.replyErrorResponse({ok:!1,errorCode:"error_"+t,errorMessage:d[t]})}replyJson(e){this.logger_.logMethodArgs?.("replyJson",{responseJson:e});let t;try{t=JSON.stringify(e)}catch(r){this.logger_.error("replyJson","reply_json_stringify_failed",r,this.clientRequest.url.debugId),this.statusCode=i.Error_Server_500_Internal_Server_Error,this.replyErrorResponse({ok:!1,errorCode:"reply_json_stringify_failed",errorMessage:"Failed to stringify response JSON."});return}this.headers["content-type"]="application/json",this.reply(t)}reply(e){if(this.logger_.logMethodArgs?.("reply",this.clientRequest.url.debugId),this.raw_.writableFinished&&this.hasBeenSent_===!1&&(this.logger_.accident("reply","server_response_writable_finished_directly"),this.hasBeenSent_=!0),this.hasBeenSent_){this.logger_.accident("reply","reply_already_sent",{url:this.clientRequest.url.debugId,replySent:this.hasBeenSent_,writableFinished:this.raw_.writableFinished});return}this.hasBeenSent_=!0;try{typeof e=="string"&&(e=Buffer.from(e)),this.headers["content-length"]=e.byteLength,this.applyHeaders_(),this.raw_.end(e,"binary")}catch(t){this.logger_.error("reply","server_response_error",t,this.clientRequest.url.debugId),this.hasBeenSent_=!1}}};import{createLogger as C}from"@alwatr/logger";var h=class{constructor(e,t,r,s){this.sharedMeta={};this.raw_=t,this.url=e,this.routeOption=s,this.remoteAddress=this.getRemoteAddress__(),this.logger_=C(`nt-client-request(${this.remoteAddress})`),this.logger_.logMethodArgs?.("new",e.debugId),this.serverResponse=new l(this,r)}get headers(){return this.raw_.headers}get queryParams(){if(this.queryParams__===void 0){this.queryParams__={};for(let[e,t]of this.url.searchParams.entries())this.queryParams__[e]=t}return this.queryParams__}getBodyRaw(){return new Promise((e,t)=>{let r=this.url.method;if(!(r==="POST"||r==="PUT"||r==="PATCH"))return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_405_Method_Not_Allowed,t(new Error("body_not_allowed"));let s=+this.raw_.headers["content-length"];if(Number.isNaN(s)||s===0)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_411_Length_Required,t(new Error("body_length_required"));if(s>this.routeOption.bodyLimit)return this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let o=[],n=0,g=_=>{if(n+=_.length,o.push(_),n>this.routeOption.bodyLimit)return this.raw_.removeListener("data",g),this.raw_.removeListener("end",a),this.raw_.removeListener("error",a),o.length=0,this.serverResponse.headers.connection="close",this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"))},a=_=>{if(this.raw_.removeListener("data",g),this.raw_.removeListener("end",a),this.raw_.removeListener("error",a),_!==void 0)return o.length=0,this.serverResponse.statusCode=i.Error_Client_400_Bad_Request,t(_);if(n!==s)return o.length=0,this.serverResponse.statusCode=i.Error_Client_413_Payload_Too_Large,t(new Error("body_too_large"));let m=Buffer.concat(o);e(m)};this.raw_.on("data",g),this.raw_.on("end",a),this.raw_.on("error",a),this.raw_.resume()})}getRemoteAddress__(){return this.raw_.headers["x-forwarded-for"]?.split(",").pop()?.trim()||this.raw_.socket.remoteAddress||null}};import{URL as v}from"node:url";var u=class u extends v{constructor(e,t){let r=e.url??"";t!=="/"&&r.indexOf(t)===0&&(r=r.slice(t.length-1)),r=r.replace(u.versionPattern_,"/"),super(r,"http://hostname/"),this.method=(e.method??"GET").toUpperCase(),this.debugId=`[${this.method}]${this.pathname}`}};u.versionPattern_=new RegExp("^/v[0-9]+/");var p=u;import{createServer as E}from"node:http";import{createLogger as S,definePackage as q}from"@alwatr/logger";q("@alwatr/nanotron-api-server","4.2.2");var c=class c{constructor(e){this.config_={...c.defaultConfig_,...e},this.logger_=S("nt-api-server"+(this.config_.port!==80?":"+this.config_.port:"")),this.logger_.logMethodArgs?.("new",{config:this.config_}),this.handleClientRequest_=this.handleClientRequest_.bind(this),this.handleServerError_=this.handleServerError_.bind(this),this.handleClientError_=this.handleClientError_.bind(this),this.routeHandlerList__={exact:{},startsWith:{}},this.httpServer=E({keepAlive:!0,keepAliveInitialDelay:0,noDelay:!0},this.handleClientRequest_),this.httpServer.requestTimeout=this.config_.requestTimeout,this.httpServer.keepAliveTimeout=this.config_.keepAliveTimeout,this.httpServer.headersTimeout=this.config_.headersTimeout,this.httpServer.listen(this.config_.port,this.config_.host,()=>{this.logger_.logOther?.(`listening on ${this.config_.host}:${this.config_.port}`)}),this.httpServer.on("error",this.handleServerError_),this.httpServer.on("clientError",this.handleClientError_)}close(){this.logger_.logMethod?.("close"),this.httpServer.close()}getRouteOption_(e){if(this.logger_.logMethod?.("getRouteOption_"),Object.hasOwn(this.routeHandlerList__.exact,e.method)&&Object.hasOwn(this.routeHandlerList__.exact[e.method],e.pathname))return this.routeHandlerList__.exact[e.method][e.pathname];if(Object.hasOwn(this.routeHandlerList__.startsWith,e.method)){let t=this.routeHandlerList__.startsWith[e.method];for(let r in t)if(r.indexOf(e.pathname)===0)return t[r]}return this.logger_.incident?.("getRouteOption_","route_not_found",{method:e.method,url:e.pathname}),null}setRouteOption_(e){var r;this.logger_.logMethodArgs?.("setRouteOption_",e);let t=this.routeHandlerList__[e.matchType];if(t[r=e.method]??(t[r]={}),Object.hasOwn(t[e.method],e.url))throw this.logger_.error("defineRoute","route_already_exists",e),new Error("route_already_exists");t[e.method][e.url]=e}defineRoute(e){let t={matchType:"exact",preHandlers:[],postHandlers:[],bodyLimit:this.config_.bodyLimit,...e};this.logger_.logMethodArgs?.("defineRoute",t),this.setRouteOption_(t)}handleServerError_(e){e.code==="EADDRINUSE"?this.logger_.error("handleServerError_","address_in_use",e):this.logger_.error("handleServerError_","http_server_error",e)}handleClientError_(e,t){this.logger_.accident("handleClientError_","http_server_client_error",{errCode:e.code,errMessage:e.message});let r=e.code?.toLowerCase()??`error_${i.Error_Client_400_Bad_Request}`,s=e.message??d[i.Error_Client_400_Bad_Request],o=`{"ok":false,"errorCode":"${r}","errorMessage":"${s}"}`,n=[`HTTP/1.1 ${i.Error_Client_400_Bad_Request} ${d[i.Error_Client_400_Bad_Request]}`,"content-type: application/json",`content-length: ${Buffer.byteLength(o)}`,`\r
3
3
  `].join(`\r
4
4
  `);t.end(n+o)}async handleClientRequest_(e,t){if(this.logger_.logMethod?.("handleClientRequest_"),e.url===void 0){this.logger_.accident("handleClientRequest_","http_server_url_undefined");return}let r=new p(e,this.config_.prefix),s=this.getRouteOption_(r),o=new h(r,e,t,s);if(s===null){o.serverResponse.statusCode=i.Error_Client_404_Not_Found,o.serverResponse.replyError();return}try{for(let n of s.preHandlers){if(o.terminatedHandlers===!0)return;await n.call(o,o,o.serverResponse,o.sharedMeta)}await s.handler.call(o,o,o.serverResponse,o.sharedMeta);for(let n of s.postHandlers){if(o.terminatedHandlers===!0)return;await n.call(o,o,o.serverResponse,o.sharedMeta)}}catch(n){this.logger_.error("handleClientRequest_","route_handler_error",n,r.debugId),o.serverResponse.statusCode<i.Error_Client_400_Bad_Request&&(o.serverResponse.statusCode=i.Error_Server_500_Internal_Server_Error),o.serverResponse.replyError(n)}}};c.defaultConfig_={host:"0.0.0.0",port:80,requestTimeout:1e4,headersTimeout:13e4,keepAliveTimeout:12e4,healthRoute:!0,allowAllOrigin:!1,prefix:"/api/",bodyLimit:1048576};var y=c;export{w as HttpMethods,i as HttpStatusCodes,d as HttpStatusMessages,y as NanotronApiServer};
5
5
  //# sourceMappingURL=main.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alwatr/nanotron-api-server",
3
- "version": "4.2.1",
3
+ "version": "4.2.2",
4
4
  "description": "Nanotron: Your Lightweight, High-Performance Micro/Nano Service Framework. Nanotron is designed for building blazingly fast and efficient microservices and APIs. Its minimalist approach and focus on performance make it ideal for resource-constrained environments and scenarios where every millisecond counts.",
5
5
  "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
6
6
  "keywords": [
@@ -22,7 +22,7 @@
22
22
  "require": "./dist/main.cjs"
23
23
  }
24
24
  },
25
- "license": "MIT",
25
+ "license": "AGPL-3.0-only",
26
26
  "files": [
27
27
  "**/*.{js,mjs,cjs,map,d.ts,html,md}",
28
28
  "!demo/**/*"
@@ -65,9 +65,9 @@
65
65
  "@alwatr/prettier-config": "^1.0.4",
66
66
  "@alwatr/tsconfig-base": "^1.2.0",
67
67
  "@alwatr/type-helper": "^1.2.6",
68
- "@types/node": "^22.6.1",
68
+ "@types/node": "^22.7.4",
69
69
  "jest": "^29.7.0",
70
70
  "typescript": "^5.6.2"
71
71
  },
72
- "gitHead": "b4a2982e438591723fc4a19ce004cf2938b01971"
72
+ "gitHead": "887f58ef716850a245871fe0f3672354201cdb9a"
73
73
  }