@andrewcaires/express 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v2.1.0
2
+ * @andrewcaires/express v2.2.0
3
3
  * Decorators for express
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- "use strict";var e=require("@andrewcaires/decorator"),t=require("@andrewcaires/node"),s=require("@andrewcaires/utils.js"),r=require("compression"),o=require("cookie-parser"),i=require("cors"),n=require("express"),a=require("express-session"),u=require("fs"),l=require("http"),d=require("https"),p=require("net"),h=require("path"),E=require("request-ip"),c=require("multer");function _(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var T=_(l),O=_(d);function v(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{u(r.next(e))}catch(e){i(e)}}function a(e){try{u(r.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}u((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class R{}R.CONTINUE=100,R.SWITCHING_PROTOCOLS=101,R.PROCESSING=102,R.OK=200,R.CREATED=201,R.ACCEPTED=202,R.NON_AUTHORITATIVE_INFORMATION=203,R.NO_CONTENT=204,R.RESET_CONTENT=205,R.PARTIAL_CONTENT=206,R.MULTI_STATUS=207,R.ALREADY_REPORTED=208,R.IM_USED=226,R.MULTIPLE_CHOICES=300,R.MOVED_PERMANENTLY=301,R.FOUND=302,R.SEE_OTHER=303,R.NOT_MODIFIED=304,R.USE_PROXY=305,R.TEMPORARY_REDIRECT=307,R.PERMANENT_REDIRECT=308,R.BAD_REQUEST=400,R.UNAUTHORIZED=401,R.PAYMENT_REQUIRED=402,R.FORBIDDEN=403,R.NOT_FOUND=404,R.METHOD_NOT_ALLOWED=405,R.NOT_ACCEPTABLE=406,R.PROXY_AUTHENTICATION_REQUIRED=407,R.REQUEST_TIMEOUT=408,R.CONFLICT=409,R.GONE=410,R.LENGTH_REQUIRED=411,R.PRECONDITION_FAILED=412,R.PAYLOAD_TOO_LARGE=413,R.REQUEST_URI_TOO_LONG=414,R.UNSUPPORTED_MEDIA_TYPE=415,R.REQUESTED_RANGE_NOT_SATISFIABLE=416,R.EXPECTATION_FAILED=417,R.IM_A_TEAPOT=418,R.MISDIRECTED_REQUEST=421,R.UNPROCESSABLE_ENTITY=422,R.LOCKED=423,R.FAILED_DEPENDENCY=424,R.UPGRADE_REQUIRED=426,R.PRECONDITION_REQUIRED=428,R.TOO_MANY_REQUESTS=429,R.REQUEST_HEADER_FIELDS_TOO_LARGE=431,R.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,R.UNAVAILABLE_FOR_LEGAL_REASONS=451,R.CLIENT_CLOSED_REQUEST=499,R.INTERNAL_SERVER_ERROR=500,R.NOT_IMPLEMENTED=501,R.BAD_GATEWAY=502,R.SERVICE_UNAVAILABLE=503,R.GATEWAY_TIMEOUT=504,R.HTTP_VERSION_NOT_SUPPORTED=505,R.VARIANT_ALSO_NEGOCIATES=506,R.INSUFFICIENT_STORAGE=507,R.LOOP_DETECTED=508,R.NOT_EXTENDED=510,R.NETWORK_AUTHENTICATION_REQUIRED=511,R.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class m extends Error{constructor(e,t=R.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class N extends m{constructor(e){super(e,R.UNPROCESSABLE_ENTITY)}}class x{constructor(e,t,s,r,o){this.storage={},this.req=e,this.res=t,this.next=s,this.app=r,this.controller=o}cache(e){const t=Object.assign({},e),r=[];t.private?r.push("private"):t.public&&r.push("public"),t.noStore&&(t.noCache=!0,r.push("no-store")),t.noCache&&(t.maxAge=0,delete t.sMaxAge,r.push("no-cache")),t.noTransform&&r.push("no-transform"),t.proxyRevalidate&&r.push("proxy-revalidate"),t.mustRevalidate?r.push("must-revalidate"):t.noCache||(s.isNumber(t.staleIfError)&&r.push(`stale-if-error=${t.staleIfError}`),s.isNumber(t.staleWhileRevalidate)&&r.push(`stale-while-revalidate=${t.staleWhileRevalidate}`)),s.isNumber(t.maxAge)&&r.push(`max-age=${t.maxAge}`),s.isNumber(t.sMaxAge)&&r.push(`s-maxage=${t.sMaxAge}`),r.length&&(this.res.setHeader("Cache-Control",r.join(",")),t.noCache&&s.forEachKey({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}clearCookie(e,t){this.res.clearCookie(e,t)}close(e){this.isResponded()||this.res.json(null!=e?e:this.storage)}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){var t;let s=null!==(t=e.toString())&&void 0!==t?t:"",r=R.INTERNAL_SERVER_ERROR;e instanceof Error&&(s=e.message,e instanceof m&&(r=e.status)),this.send(r,{error:s})}file(e){this.isResponded()||(this.status(R.OK),this.res.sendFile(h.resolve(e)))}getBody(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.body)&&void 0!==t?t:{}}getBodyValue(e){var t;return null===(t=this.req.body)||void 0===t?void 0:t[e]}getCookie(e){var t;return this.normalize(null===(t=this.req.cookies)||void 0===t?void 0:t[e])}getCookies(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.cookies)&&void 0!==t?t:{},e=>this.normalize(e))}getFiles(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.files)&&void 0!==t?t:{}}getHeader(e){var t;return this.normalize(null===(t=this.req.headers)||void 0===t?void 0:t[e])}getHeaders(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.headers)&&void 0!==t?t:{},e=>this.normalize(e))}getIp(){return E.getClientIp(this.req)||"0.0.0.0"}getQuery(e){var t;return this.normalize(null===(t=this.req.query)||void 0===t?void 0:t[e])}getQueries(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.query)&&void 0!==t?t:{},e=>this.normalize(e))}getParam(e){var t;const r=null===(t=this.req.params)||void 0===t?void 0:t[e];return s.isUndefined(r)?void 0:String(r)}getParams(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.params)&&void 0!==t?t:{},e=>{if(!s.isUndefined(e)&&!s.isNull(e))return String(e)})}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}isResponded(){return this.res.headersSent||this.res.writableEnded}json(e){this.send(R.OK,e)}normalize(e){if(!s.isUndefined(e)&&!s.isNull(e))return s.isObject(e)?JSON.stringify(e):String(e)}prepare(e,t){this.isResponded()||(this.status(e),this.storage=t)}send(e,t){this.isResponded()||(this.status(e),204===e||304===e||s.isUndefined(t)?this.res.end():this.res.json(t))}setCookie(e,t,s){this.res.cookie(e,t,null!=s?s:{})}status(e){return s.isUndefined(e)||this.res.status(e),this.res.statusCode}success(e){this.send(R.OK,{message:e})}}class A{static extends(t){return e.metadata(A.EXTENDS,t,[])}static middleware(t){return e.metadata(A.MIDDLEWARE,t,[])}static parameters(t){return e.metadata(A.PARAMETERS,t,[])}static path(t,s){return e.metadata(A.PATH,t,s)}static routers(t){return e.metadata(A.ROUTERS,t,[])}}A.EXTENDS=Symbol("EXTENDS"),A.MIDDLEWARE=Symbol("MIDDLEWARE"),A.PARAMETERS=Symbol("PARAMETERS"),A.PATH=Symbol("PATH"),A.ROUTERS=Symbol("ROUTERS");class g extends s.EventEmitter{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(t,l){var d,p;super(),this._app=n(),this._options={},this._base=n.Router(),this._router=n.Router(),this._controllers=[],this._controllers.push(...t.map(t=>s.isConstructor(t)?new t(...e.getInjectionArgs(t)):t)),this._options=s.merge({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=l?l:{}),this._app.use(n.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(n.urlencoded({extended:!0})),this._options.cross&&this._app.use(i(s.isObject(this._options.cross)?this._options.cross:{})),this._app.use(r(this._options.compression)),this._app.use(o(null===(d=this._options.cookie)||void 0===d?void 0:d.secret,this._options.cookie)),this._app.use(a(this._options.session)),this.init(),this._app.use(this._router);const E=(null===(p=this._options.path)||void 0===p?void 0:p.length)?this._options.path:"/";if(this._app.use(E,this._base),this._app.all(E+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(R.NOT_FOUND),t.json({message:"INVALID API"}))}),this._options.public){const e=h.resolve(this._options.public);u.existsSync(e)&&this._app.use(n.static(e)),this._app.get("*path",(t,s)=>{u.existsSync(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(R.NOT_FOUND),s.json({message:'FILE "index.html" NOT FOUND'}))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(R.NOT_FOUND),t.json({message:"INVALID API"}))});this._controllers.forEach(e=>{const t=n.Router(),r=this._middlewares(e),o=A.parameters(e);this._extends(e).forEach(e=>{r.push(...this._middlewares(e)),o.push(...A.parameters(e))}),A.routers(e).forEach(i=>{const n=i.propertyKey.toString();if(s.isFunction(e[n])){if(!s.isFunction(t[i.method]))return this._notFound(i.method);const a=this._handles(e,n,r,o);return t[i.method](i.path,...a,(t,r,i)=>v(this,void 0,void 0,function*(){const a=new x(t,r,i,this,e),u=this._args(a,this._indexes(n,o)),l=yield e[n](...u);a.close(s.isArray(l)||s.isObject(l)?l:void 0)}))}this._notFound(`${e.name}.${n}`)}),this._extends(e).forEach(i=>{A.routers(i).forEach(i=>{const n=i.propertyKey.toString();if(s.isFunction(e[n])){if(!s.isFunction(t[i.method]))return this._notFound(i.method);const a=this._handles(e,n,r,o);return t[i.method](i.path,...a,(t,r,i)=>v(this,void 0,void 0,function*(){const a=new x(t,r,i,this,e),u=this._args(a,this._indexes(n,o)),l=yield e[n](...u);a.close(s.isArray(l)||s.isObject(l)?l:void 0)}))}this._notFound(`${e.constructor.name}.${n}`)})}),this._base.use(A.path(e,"/"),t)})}init(){}error(e,s){t.Log.error(e)}log(e,s){t.Log.info(e)}_args(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_handles(e,t,r,o){return r.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=s.noop){const r=this._indexes(t.method,o);return(o,i,n)=>v(this,void 0,void 0,function*(){const a=new x(o,i,n,this,e),u=s.isFunction(t.argument)?t.argument(a):t.argument,l=yield t.callback.call(e,...this._args(a,r,u));(s.isArray(l)||s.isObject(l))&&a.close(l)})}this._notFound(t.method)}).filter(s.isFunction)}_extends(e){return A.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...A.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return v(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=T.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=T.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(R.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()}),t=O.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new p.Server(s=>{s.once("data",r=>{s.pause(),s.unshift(r),(22===r[0]?t:e).emit("connection",s),process.nextTick(()=>s.resume())})}).listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t}this._server||(443==this._options.port&&e.listen(80,()=>this.log(this._port(80),"express")),t.listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t)}})}}const I=e=>t=>(s,r,o)=>{A.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},S=I(({app:e})=>e),D=I(({argument:e})=>e),f=I(({ctx:e,key:t})=>t?e.getBodyValue(t):e.getBody()),y=I(({ctx:e,key:t})=>t?e.getCookie(t):e.getCookies()),C=I(({ctx:e})=>e),U=I(({ctx:e})=>e.getFiles()),L=I(({ctx:e,key:t})=>t?e.getHeader(t):e.getHeaders()),P=I(({ctx:e,key:t})=>t?e.getParam(t):e.getParams()),b=I(({ctx:e,key:t})=>t?e.getQuery(t):e.getQueries()),F=I(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),q=(e,t)=>(r,o)=>{const i=s.uuidv7();C()(r,i,0),A.middleware(r).push({method:i,argument:t,propertyKey:o,callback:e})},k={ALL:"all",GET:"get",POST:"post",PUT:"put",HEAD:"head",DELETE:"delete",OPTIONS:"options",PATCH:"patch"},M=e=>t=>(s,r)=>{A.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},w=M(k.ALL),j=M(k.DELETE),H=M(k.GET),Q=M(k.HEAD),V=M(k.OPTIONS),$=M(k.PATCH),B=M(k.POST),G=M(k.PUT),K=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},Y=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},z=(e,t)=>{const r=s.uuidv7()+"."+t;return u.existsSync(h.join(e,r))?z(e,t):r};exports.All=w,exports.App=S,exports.Application=g,exports.Argument=D,exports.BadRequestError=class extends m{constructor(e="Bad Request"){super(e,R.BAD_REQUEST)}},exports.Body=f,exports.Cache=e=>(t,s,r)=>{q(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},exports.Context=x,exports.Controller=e=>t=>{A.path(t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=y,exports.Ctx=C,exports.Delete=j,exports.Extends=e=>t=>{A.extends(t).push(e)},exports.Files=U,exports.ForbiddenError=class extends m{constructor(e="Forbidden"){super(e,R.FORBIDDEN)}},exports.Get=H,exports.Head=Q,exports.Headers=L,exports.InternalServerError=class extends m{constructor(e="Internal server error"){super(e,R.INTERNAL_SERVER_ERROR)}},exports.Metadata=A,exports.Methods=k,exports.Middleware=(e,t)=>(r,o)=>{let i=s.noop;if(s.isString(o)){const t=r;s.isFunction(t[e])&&(i=t[e])}A.middleware(r).push({method:e,argument:t,propertyKey:o,callback:i})},exports.NotFoundError=class extends m{constructor(e="Record not found"){super(e,R.NOT_FOUND)}},exports.Options=V,exports.Params=P,exports.Patch=$,exports.Post=B,exports.Put=G,exports.Query=b,exports.ResponseError=m,exports.Session=F,exports.Status=R,exports.UnauthorizedError=class extends m{constructor(e="Unauthorized"){super(e,R.UNAUTHORIZED)}},exports.Upload=e=>{const t=s.merge({},e),r=c.diskStorage({destination(e,s,r){var o;const i=Y(t,s.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,s,r){var o;const i=Y(t,s.fieldname);r(null,z(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",K(s.originalname)))}}),o=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),i=c({storage:r,fileFilter(e,s,r){var o;const i=Y(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(K(e.originalname))||t.includes(e.mimetype.toLowerCase()))(s,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${s.fieldname}"`)):r(new Error(`UPLOAD FIELD "${s.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*o*1024}}).fields(Object.keys(t).map(e=>{var s,r;return{name:e,maxCount:null!==(r=null===(s=t[e])||void 0===s?void 0:s.count)&&void 0!==r?r:1}}));return(e,t,s)=>{q(e=>{i(e.req,e.res,t=>{if(t)return"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t);e.next()})})(e,t,s)}},exports.Use=q,exports.Validate=e=>{const t=s.Validation.object(s.isFunction(e)?e(s.Validation):e).parse();return(e,s,r)=>{q(e=>v(void 0,void 0,void 0,function*(){var s,r;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{});if(o)return e.error(new N(null!=i?i:o));e.req.body=n,e.next()}))(e,s,r)}},exports.ValidationError=N,exports.methodFactory=M,exports.parameterFactory=I;
7
+ "use strict";var e=require("@andrewcaires/decorator"),t=require("@andrewcaires/node"),s=require("@andrewcaires/utils.js"),r=require("compression"),o=require("cookie-parser"),i=require("cors"),n=require("express"),a=require("express-session"),l=require("fs"),u=require("http"),d=require("https"),h=require("net"),c=require("path"),p=require("request-ip"),E=require("multer");function _(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var v=_(u),R=_(d),m=_(h);function T(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}l((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class g{}g.CONTINUE=100,g.SWITCHING_PROTOCOLS=101,g.PROCESSING=102,g.OK=200,g.CREATED=201,g.ACCEPTED=202,g.NON_AUTHORITATIVE_INFORMATION=203,g.NO_CONTENT=204,g.RESET_CONTENT=205,g.PARTIAL_CONTENT=206,g.MULTI_STATUS=207,g.ALREADY_REPORTED=208,g.IM_USED=226,g.MULTIPLE_CHOICES=300,g.MOVED_PERMANENTLY=301,g.FOUND=302,g.SEE_OTHER=303,g.NOT_MODIFIED=304,g.USE_PROXY=305,g.TEMPORARY_REDIRECT=307,g.PERMANENT_REDIRECT=308,g.BAD_REQUEST=400,g.UNAUTHORIZED=401,g.PAYMENT_REQUIRED=402,g.FORBIDDEN=403,g.NOT_FOUND=404,g.METHOD_NOT_ALLOWED=405,g.NOT_ACCEPTABLE=406,g.PROXY_AUTHENTICATION_REQUIRED=407,g.REQUEST_TIMEOUT=408,g.CONFLICT=409,g.GONE=410,g.LENGTH_REQUIRED=411,g.PRECONDITION_FAILED=412,g.PAYLOAD_TOO_LARGE=413,g.REQUEST_URI_TOO_LONG=414,g.UNSUPPORTED_MEDIA_TYPE=415,g.REQUESTED_RANGE_NOT_SATISFIABLE=416,g.EXPECTATION_FAILED=417,g.IM_A_TEAPOT=418,g.MISDIRECTED_REQUEST=421,g.UNPROCESSABLE_ENTITY=422,g.LOCKED=423,g.FAILED_DEPENDENCY=424,g.UPGRADE_REQUIRED=426,g.PRECONDITION_REQUIRED=428,g.TOO_MANY_REQUESTS=429,g.REQUEST_HEADER_FIELDS_TOO_LARGE=431,g.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,g.UNAVAILABLE_FOR_LEGAL_REASONS=451,g.CLIENT_CLOSED_REQUEST=499,g.INTERNAL_SERVER_ERROR=500,g.NOT_IMPLEMENTED=501,g.BAD_GATEWAY=502,g.SERVICE_UNAVAILABLE=503,g.GATEWAY_TIMEOUT=504,g.HTTP_VERSION_NOT_SUPPORTED=505,g.VARIANT_ALSO_NEGOCIATES=506,g.INSUFFICIENT_STORAGE=507,g.LOOP_DETECTED=508,g.NOT_EXTENDED=510,g.NETWORK_AUTHENTICATION_REQUIRED=511,g.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class O{}O[100]="Continue",O[101]="Switching Protocols",O[102]="Processing",O[200]="OK",O[201]="Created",O[202]="Accepted",O[203]="Non-Authoritative Information",O[204]="No Content",O[205]="Reset Content",O[206]="Partial Content",O[207]="Multi-Status",O[226]="IM Used",O[300]="Multiple Choices",O[301]="Moved Permanently",O[302]="Found",O[303]="See Other",O[304]="Not Modified",O[305]="Use Proxy",O[307]="Temporary Redirect",O[308]="Permanent Redirect",O[400]="Bad Request",O[401]="Unauthorized",O[402]="Payment Required",O[403]="Forbidden",O[404]="Not Found",O[405]="Method Not Allowed",O[406]="Not Acceptable",O[407]="Proxy Authentication Required",O[408]="Request Timeout",O[409]="Conflict",O[410]="Gone",O[411]="Length Required",O[412]="Precondition Failed",O[413]="Payload Too Large",O[414]="URI Too Long",O[415]="Unsupported Media Type",O[416]="Range Not Satisfiable",O[417]="Expectation Failed",O[418]="I'm a teapot",O[422]="Unprocessable Entity",O[423]="Locked",O[424]="Failed Dependency",O[426]="Upgrade Required",O[428]="Precondition Required",O[429]="Too Many Requests",O[431]="Request Header Fields Too Large",O[451]="Unavailable For Legal Reasons",O[500]="Internal Server Error",O[501]="Not Implemented",O[502]="Bad Gateway",O[503]="Service Unavailable",O[504]="Gateway Time-out",O[505]="HTTP Version Not Supported",O[506]="Variant Also Negotiates",O[507]="Insufficient Storage",O[511]="Network Authentication Required";class N extends Error{constructor(e,t=g.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class S extends N{constructor(e="Not Found"){super(e,g.NOT_FOUND)}}class f extends N{constructor(e){super(e,g.UNPROCESSABLE_ENTITY)}}class A{static created(e,t,s){var r,o;const i=g.CREATED,n={success:!0,status:i,data:t?{id:t}:{},meta:null!==(r=null==s?void 0:s.meta)&&void 0!==r?r:{},message:null!==(o=null==s?void 0:s.message)&&void 0!==o?o:null};return e.status(i).json(n),n}static noContent(e){e.status(g.NO_CONTENT).end()}static ok(e,t,s){var r,o;const i=g.OK,n={success:!0,status:i,data:t,meta:null!==(r=null==s?void 0:s.meta)&&void 0!==r?r:{},message:null!==(o=null==s?void 0:s.message)&&void 0!==o?o:null};return e.status(i).json(n),n}static error(e,t,s){var r,o;const{status:i,message:n}=this.normalizeError(s),a=Object.assign({success:!1,status:i,error:null!==(r=null==O?void 0:O[i])&&void 0!==r?r:"Internal Server Error",message:n,path:null!==(o=e.originalUrl)&&void 0!==o?o:e.url,timestamp:(new Date).toISOString()},this.isDev()&&s instanceof Error&&s.stack?{stack:s.stack}:{});return t.status(i).json(a),a}static isDev(){return"production"!==process.env.NODE_ENV}static normalizeError(e){let t=g.INTERNAL_SERVER_ERROR,r=O[500];if(e instanceof N)return t=this.safeStatus(e.status),r=this.safeMessage(e.message)||r,{status:t,message:r};if(e instanceof Error){const o=e;return s.isNumber(o.statusCode)?t=this.safeStatus(o.statusCode):s.isNumber(o.status)&&(t=this.safeStatus(o.status)),r=this.safeMessage(e.message)||r,{status:t,message:r}}if(s.isString(e))return r=this.safeMessage(e)||r,{status:t,message:r};if(e&&s.isObject(e)){const o=e;return s.isNumber(o.statusCode)?t=this.safeStatus(o.statusCode):s.isNumber(o.status)&&(t=this.safeStatus(o.status)),s.isString(o.message)&&(r=this.safeMessage(o.message)||r),{status:t,message:r}}return{status:t,message:r}}static safeStatus(e){if(!Number.isFinite(e))return g.INTERNAL_SERVER_ERROR;const t=Math.trunc(e);return t<400||t>599?g.INTERNAL_SERVER_ERROR:t}static safeMessage(e){if(!s.isString(e))return"";const t=e.trim();return t.length>2e3?t.slice(0,2e3)+"...":t}}class y{constructor(e,t,r,o,i){this.storage={},this.req=e,this.res=t,this.next=r,this.id=s.uuidv7(),this.app=o,this.controller=i}cache(e){const t=Object.assign({},e),r=[];t.private?r.push("private"):t.public&&r.push("public"),t.noStore&&(t.noCache=!0,r.push("no-store")),t.noCache&&(t.maxAge=0,delete t.sMaxAge,r.push("no-cache")),t.noTransform&&r.push("no-transform"),t.proxyRevalidate&&r.push("proxy-revalidate"),t.mustRevalidate?r.push("must-revalidate"):t.noCache||(s.isNumber(t.staleIfError)&&r.push(`stale-if-error=${t.staleIfError}`),s.isNumber(t.staleWhileRevalidate)&&r.push(`stale-while-revalidate=${t.staleWhileRevalidate}`)),s.isNumber(t.maxAge)&&r.push(`max-age=${t.maxAge}`),s.isNumber(t.sMaxAge)&&r.push(`s-maxage=${t.sMaxAge}`),r.length&&(this.res.setHeader("Cache-Control",r.join(",")),t.noCache&&s.forEachKey({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}clearCookie(e,t){this.res.clearCookie(e,t)}close(e){this.isResponded()||this.res.json(null!=e?e:this.storage)}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){this.isResponded()||A.error(this.req,this.res,e)}file(e){this.isResponded()||(this.status(g.OK),this.res.sendFile(c.resolve(e)))}getBody(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.body)&&void 0!==t?t:{}}getBodyValue(e){var t;return null===(t=this.req.body)||void 0===t?void 0:t[e]}getCookie(e){var t;return this.normalize(null===(t=this.req.cookies)||void 0===t?void 0:t[e])}getCookies(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.cookies)&&void 0!==t?t:{},e=>this.normalize(e))}getFiles(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.files)&&void 0!==t?t:{}}getHeader(e){var t;return this.normalize(null===(t=this.req.headers)||void 0===t?void 0:t[e])}getHeaders(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.headers)&&void 0!==t?t:{},e=>this.normalize(e))}getIp(){return p.getClientIp(this.req)||"0.0.0.0"}getQuery(e){var t;return this.normalize(null===(t=this.req.query)||void 0===t?void 0:t[e])}getQueries(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.query)&&void 0!==t?t:{},e=>this.normalize(e))}getParam(e){var t;const r=null===(t=this.req.params)||void 0===t?void 0:t[e];return s.isUndefined(r)?void 0:String(r)}getParams(){var e,t;return s.map(null!==(t=null===(e=this.req)||void 0===e?void 0:e.params)&&void 0!==t?t:{},e=>{if(!s.isUndefined(e)&&!s.isNull(e))return String(e)})}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}isResponded(){return this.res.headersSent||this.res.writableEnded}json(e){this.send(g.OK,e)}normalize(e){if(!s.isUndefined(e)&&!s.isNull(e))return s.isObject(e)?JSON.stringify(e):String(e)}ok(e,t){this.isResponded()||A.ok(this.res,e,t)}prepare(e,t){this.isResponded()||(this.status(e),this.storage=t)}send(e,t){this.isResponded()||(this.status(e),204===e||304===e||s.isUndefined(t)?this.res.end():this.res.json(t))}setCookie(e,t,s){this.res.cookie(e,t,null!=s?s:{})}status(e){return s.isUndefined(e)||this.res.status(e),this.res.statusCode}success(e){this.send(g.OK,{message:e})}}class x{static extends(t){return e.metadata(x.EXTENDS,t,[])}static middleware(t){return e.metadata(x.MIDDLEWARE,t,[])}static parameters(t){return e.metadata(x.PARAMETERS,t,[])}static path(t,s){return e.metadata(x.PATH,t,s)}static routers(t){return e.metadata(x.ROUTERS,t,[])}}x.EXTENDS=Symbol("EXTENDS"),x.MIDDLEWARE=Symbol("MIDDLEWARE"),x.PARAMETERS=Symbol("PARAMETERS"),x.PATH=Symbol("PATH"),x.ROUTERS=Symbol("ROUTERS");class I extends s.EventEmitter{get controllers(){return[...this._controllers]}get instance(){return this._app}get router(){return this._globalRouter}get server(){return this._server}constructor(t,u){var d,h;super(),this._app=n(),this._boundServers=[],this._options={},this._baseRouter=n.Router(),this._globalRouter=n.Router(),this._controllers=[],this._controllers.push(...t.map(t=>s.isConstructor(t)?new t(...e.getInjectionArgs(t)):t)),this._options=s.merge({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=u?u:{}),this._app.use(n.json(this._options.json)),this._app.disable("x-powered-by"),this._app.use(n.urlencoded({extended:!0})),this._options.cross&&this._app.use(i(s.isObject(this._options.cross)?this._options.cross:{})),this._app.use(r(this._options.compression)),this._app.use(o(null===(d=this._options.cookie)||void 0===d?void 0:d.secret,this._options.cookie)),this._app.use(a(this._options.session)),this.init(),this._app.use(this._globalRouter);const p=(null===(h=this._options.path)||void 0===h?void 0:h.length)?this._options.path:"/";if(this._app.use(p,this._baseRouter),this._app.all(p+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):A.error(e,t,new S("Endpoint Not Found"))}),this._options.public){const e=c.resolve(this._options.public);l.existsSync(e)&&this._app.use(n.static(e)),this._app.get("*path",(t,s)=>{l.existsSync(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):A.error(t,s,new S('FILE "index.html" Not Found'))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):A.error(e,t,new S("Endpoint not found"))});this._controllers.forEach(e=>{const t=n.Router(),r=this._collectMiddlewares(e),o=x.parameters(e);this._collectExtends(e).forEach(e=>{r.push(...this._collectMiddlewares(e)),o.push(...x.parameters(e))}),x.routers(e).forEach(i=>{const n=i.propertyKey.toString();if(s.isFunction(e[n])){if(!s.isFunction(t[i.method]))return this._logRouteNotFound(i.method);const a=this._buildMiddlewareChain(e,n,r,o);return t[i.method](i.path,...a,(t,r,i)=>T(this,void 0,void 0,function*(){const a=new y(t,r,i,this,e),l=this._resolveArgs(a,this._filterParamsByKey(n,o)),u=yield e[n](...l);a.close(s.isArray(u)||s.isObject(u)?u:void 0)}))}this._logRouteNotFound(`${e.name}.${n}`)}),this._collectExtends(e).forEach(i=>{x.routers(i).forEach(i=>{const n=i.propertyKey.toString();if(s.isFunction(e[n])){if(!s.isFunction(t[i.method]))return this._logRouteNotFound(i.method);const a=this._buildMiddlewareChain(e,n,r,o);return t[i.method](i.path,...a,(t,r,i)=>T(this,void 0,void 0,function*(){const a=new y(t,r,i,this,e),l=this._resolveArgs(a,this._filterParamsByKey(n,o)),u=yield e[n](...l);a.close(s.isArray(u)||s.isObject(u)?u:void 0)}))}this._logRouteNotFound(`${e.constructor.name}.${n}`)})}),this._baseRouter.use(x.path(e,"/"),t)})}init(){}error(e,s){t.Log.error(e)}log(e,s){t.Log.info(e)}_resolveArgs(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_buildMiddlewareChain(e,t,r,o){return r.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=s.noop){const r=this._filterParamsByKey(t.method,o);return(o,i,n)=>T(this,void 0,void 0,function*(){const a=new y(o,i,n,this,e),l=s.isFunction(t.argument)?t.argument(a):t.argument,u=yield t.callback.call(e,...this._resolveArgs(a,r,l));(s.isArray(u)||s.isObject(u))&&a.close(u)})}this._logRouteNotFound(t.method)}).filter(s.isFunction)}_collectExtends(e){return x.extends(e).reduce((e,t)=>(e.push(t,...this._collectExtends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_filterParamsByKey(e,t){return t.filter(t=>t.propertyKey==e)}_collectMiddlewares(e){return[...x.middleware(e)].reverse()}_logRouteNotFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_formatListeningMessage(e){return`Server listening on port ${e}`}listen(){return T(this,void 0,void 0,function*(){var e;const t=this._resolveMode(),s={http:this._startHttp,https:this._startHttps,hybrid:this._startHybrid,redirect:this._startHttpsWithRedirect};yield(null!==(e=s[t])&&void 0!==e?e:this._startHttp).call(this)})}close(){return T(this,void 0,void 0,function*(){yield Promise.all(this._boundServers.map(e=>new Promise((t,s)=>{e.close(e=>e?s(e):t())}))),this._boundServers.length=0,this._server=void 0})}_resolveMode(){return this._resolveTls()?this._options.mode?this._options.mode:this._options.hybrid?"hybrid":"https":"http"}_resolveTls(){if(this._options.tls&&this._options.tls.key&&this._options.tls.cert)return this._options.tls}_bindServer(e,t,s){return new Promise((r,o)=>{const i=t=>{e.off("listening",n),o(t)},n=()=>{e.off("error",i),this.log(this._formatListeningMessage(t),"express"),r()};e.once("error",i),e.once("listening",n),e.listen(t,s)})}_startHttp(){return T(this,void 0,void 0,function*(){var e;const t=v.createServer(this._app);this._server=t,this._boundServers.push(t),yield this._bindServer(t,null!==(e=this._options.port)&&void 0!==e?e:3e3,this._options.host)})}_startHttps(){return T(this,void 0,void 0,function*(){var e;const t=R.createServer(this._resolveTls(),this._app);this._server=t,this._boundServers.push(t),yield this._bindServer(t,null!==(e=this._options.port)&&void 0!==e?e:443,this._options.host)})}_startHttpsWithRedirect(){return T(this,void 0,void 0,function*(){var e,t;const s=R.createServer(this._resolveTls(),this._app),r=v.createServer((e,t)=>{var s,r;const o=(null!==(s=e.headers.host)&&void 0!==s?s:"").split(":")[0];t.writeHead(g.MOVED_PERMANENTLY,{Location:`https://${o}${null!==(r=e.url)&&void 0!==r?r:""}`}),t.end()});this._server=s,this._boundServers.push(s,r),yield Promise.all([this._bindServer(s,null!==(e=this._options.port)&&void 0!==e?e:443,this._options.host),this._bindServer(r,null!==(t=this._options.redirectPort)&&void 0!==t?t:80,this._options.host)])})}_startHybrid(){return T(this,void 0,void 0,function*(){var e;const t=v.createServer(this._app),s=R.createServer(this._resolveTls(),this._app),r=m.createServer(e=>{const r=setTimeout(()=>e.destroy(),5e3);e.once("data",o=>{clearTimeout(r),e.pause(),e.unshift(o),(22===o[0]?s:t).emit("connection",e),process.nextTick(()=>e.resume())}),e.once("error",()=>clearTimeout(r))});return this._server=s,this._boundServers.push(r,s,t),yield this._bindServer(r,null!==(e=this._options.port)&&void 0!==e?e:443,this._options.host),s})}}const b=e=>t=>(s,r,o)=>{x.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},C=b(({app:e})=>e),D=b(({argument:e})=>e),P=b(({ctx:e,key:t})=>t?e.getBodyValue(t):e.getBody()),U=b(({ctx:e,key:t})=>t?e.getCookie(t):e.getCookies()),L=b(({ctx:e})=>e),M=b(({ctx:e})=>e.getFiles()),F=b(({ctx:e,key:t})=>t?e.getHeader(t):e.getHeaders()),q=b(({ctx:e,key:t})=>t?e.getParam(t):e.getParams()),k=b(({ctx:e,key:t})=>t?e.getQuery(t):e.getQueries()),w=b(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),H=(e,t)=>(r,o)=>{const i=s.uuidv7();L()(r,i,0),x.middleware(r).push({method:i,argument:t,propertyKey:o,callback:e})},j={ALL:"all",GET:"get",POST:"post",PUT:"put",HEAD:"head",DELETE:"delete",OPTIONS:"options",PATCH:"patch"},B=e=>t=>(s,r)=>{x.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},V=B(j.ALL),K=B(j.DELETE),G=B(j.GET),Q=B(j.HEAD),$=B(j.OPTIONS),z=B(j.PATCH),Y=B(j.POST),W=B(j.PUT),X=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},Z=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},J=(e,t)=>{const r=s.uuidv7()+"."+t;return l.existsSync(c.join(e,r))?J(e,t):r};exports.All=V,exports.App=C,exports.Application=I,exports.Argument=D,exports.BadRequestError=class extends N{constructor(e="Bad Request"){super(e,g.BAD_REQUEST)}},exports.Body=P,exports.Cache=e=>(t,s,r)=>{H(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},exports.Context=y,exports.Controller=e=>t=>{x.path(t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=U,exports.Ctx=L,exports.Delete=K,exports.Extends=e=>t=>{x.extends(t).push(e)},exports.Files=M,exports.ForbiddenError=class extends N{constructor(e="Forbidden"){super(e,g.FORBIDDEN)}},exports.Get=G,exports.Head=Q,exports.Headers=F,exports.HttpResponse=A,exports.InternalServerError=class extends N{constructor(e="Internal server error"){super(e,g.INTERNAL_SERVER_ERROR)}},exports.Metadata=x,exports.Methods=j,exports.Middleware=(e,t)=>(r,o)=>{let i=s.noop;if(s.isString(o)){const t=r;s.isFunction(t[e])&&(i=t[e])}x.middleware(r).push({method:e,argument:t,propertyKey:o,callback:i})},exports.NotFoundError=S,exports.Options=$,exports.Params=q,exports.Patch=z,exports.Post=Y,exports.Put=W,exports.Query=k,exports.ResponseError=N,exports.Session=w,exports.StatusCodes=g,exports.StatusText=O,exports.UnauthorizedError=class extends N{constructor(e="Unauthorized"){super(e,g.UNAUTHORIZED)}},exports.Upload=e=>{const t=s.merge({},e),r=E.diskStorage({destination(e,s,r){var o;const i=Z(t,s.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,s,r){var o;const i=Z(t,s.fieldname);r(null,J(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",X(s.originalname)))}}),o=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),i=E({storage:r,fileFilter(e,s,r){var o;const i=Z(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(X(e.originalname))||t.includes(e.mimetype.toLowerCase()))(s,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${s.fieldname}"`)):r(new Error(`UPLOAD FIELD "${s.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*o*1024}}).fields(Object.keys(t).map(e=>{var s,r;return{name:e,maxCount:null!==(r=null===(s=t[e])||void 0===s?void 0:s.count)&&void 0!==r?r:1}}));return(e,t,s)=>{H(e=>{i(e.req,e.res,t=>{if(!t)return e.next();"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t)})})(e,t,s)}},exports.Use=H,exports.Validate=e=>{const t=s.Validation.object(s.isFunction(e)?e(s.Validation):e).parse();return(e,s,r)=>{H(e=>T(void 0,void 0,void 0,function*(){var s,r;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{});if(o)return e.error(new f(null!=i?i:o));e.req.body=n,e.next()}))(e,s,r)}},exports.ValidationError=f,exports.methodFactory=B,exports.parameterFactory=b;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @andrewcaires/express v2.1.0
2
+ * @andrewcaires/express v2.2.0
3
3
  * Decorators for express
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
@@ -14,10 +14,52 @@ import { CorsOptions } from 'cors';
14
14
  import { SessionOptions } from 'express-session';
15
15
  import { CookieParseOptions } from 'cookie-parser';
16
16
 
17
- declare class Context<T = any, A = Application> {
17
+ interface ICookie extends CookieParseOptions {
18
+ secret?: string | Array<string>;
19
+ }
20
+
21
+ type ServerMode = "http" | "https" | "redirect" | "hybrid";
22
+
23
+ interface TlsOptions {
24
+ key: Buffer | string;
25
+ cert: Buffer | string;
26
+ ca?: Buffer | string;
27
+ }
28
+
29
+ interface ExpressOptions {
30
+ compression?: CompressionOptions;
31
+ cookie?: ICookie;
32
+ cross?: boolean | CorsOptions;
33
+ host?: string;
34
+ hybrid?: boolean;
35
+ json?: OptionsJson;
36
+ mode?: ServerMode;
37
+ notfound?: string;
38
+ path?: string;
39
+ port?: number;
40
+ public?: string;
41
+ redirect?: string;
42
+ redirectPort?: number;
43
+ session?: SessionOptions;
44
+ tls?: TlsOptions;
45
+ }
46
+
47
+ interface FileUpload {
48
+ fieldname: string;
49
+ originalname: string;
50
+ encoding: string;
51
+ mimetype: string;
52
+ destination: string;
53
+ filename: string;
54
+ path: string;
55
+ size: number;
56
+ }
57
+
58
+ declare class Context<T = any, A extends Application = Application> {
18
59
  readonly req: Request;
19
60
  readonly res: Response;
20
61
  readonly next: NextFunction;
62
+ readonly id: string;
21
63
  readonly app: A;
22
64
  readonly controller: T;
23
65
  private storage;
@@ -32,7 +74,7 @@ declare class Context<T = any, A = Application> {
32
74
  getBodyValue<T = any>(key: string): T | undefined;
33
75
  getCookie(key: string): string | undefined;
34
76
  getCookies<T = TypeAnyObject>(): T;
35
- getFiles<F = IFile, T = TypeObject<Array<F>>>(): T;
77
+ getFiles<F extends FileUpload = FileUpload, T = TypeObject<Array<F>>>(): T;
36
78
  getHeader(key: string): string | undefined;
37
79
  getHeaders<T = TypeAnyObject>(): T;
38
80
  getIp(): string;
@@ -44,6 +86,7 @@ declare class Context<T = any, A = Application> {
44
86
  isResponded(): boolean;
45
87
  json(value?: TypeAnyObject | Array<TypeAnyObject>): void;
46
88
  private normalize;
89
+ ok<T = any>(data: T, meta?: TypeAnyObject): void;
47
90
  prepare(status: number, value: TypeAnyObject | Array<TypeAnyObject>): void;
48
91
  send(status: number, value?: TypeAnyObject | Array<TypeAnyObject>): void;
49
92
  setCookie(key: string, value: string, options?: CookieOptions): void;
@@ -72,21 +115,6 @@ interface ICache {
72
115
  public?: boolean;
73
116
  }
74
117
 
75
- interface ICookie extends CookieParseOptions {
76
- secret?: string | Array<string>;
77
- }
78
-
79
- interface IFile {
80
- fieldname: string;
81
- originalname: string;
82
- encoding: string;
83
- mimetype: string;
84
- destination: string;
85
- filename: string;
86
- path: string;
87
- size: number;
88
- }
89
-
90
118
  type IHandler = (_ctx: Context) => any;
91
119
 
92
120
  interface IMiddlewares {
@@ -96,22 +124,6 @@ interface IMiddlewares {
96
124
  callback: TypeAnyFunction;
97
125
  }
98
126
 
99
- interface IOptions {
100
- cert?: Buffer;
101
- compression?: CompressionOptions;
102
- cookie?: ICookie;
103
- cross?: boolean | CorsOptions;
104
- hybrid?: boolean;
105
- json?: OptionsJson;
106
- key?: Buffer;
107
- notfound?: string;
108
- path?: string;
109
- port?: number;
110
- public?: string;
111
- redirect?: string;
112
- session?: SessionOptions;
113
- }
114
-
115
127
  interface IParameter {
116
128
  callback: TypeAnyFunction;
117
129
  key?: string;
@@ -148,13 +160,6 @@ interface IStore extends TypeAnyObject {
148
160
  touch(): this;
149
161
  }
150
162
 
151
- interface IUpload {
152
- count?: number;
153
- path?: string;
154
- size?: number;
155
- types?: Array<string>;
156
- }
157
-
158
163
  interface IUse {
159
164
  middleware: IHandler;
160
165
  propertyKey: string | symbol;
@@ -405,31 +410,75 @@ interface OpenAPIObject {
405
410
  externalDocs?: ExternalDocumentationObject;
406
411
  }
407
412
 
408
- type ParseFunction = (_$: typeof Validation) => TypeObject<ValidationBase>;
413
+ interface HttpResponseBase<T> {
414
+ success: true;
415
+ status: number;
416
+ data: T;
417
+ meta?: TypeAnyObject;
418
+ message?: string | null;
419
+ }
420
+
421
+ interface HttpResponseCreated extends HttpResponseBase<{
422
+ id?: string | number;
423
+ }> {
424
+ }
425
+
426
+ interface HttpResponseError {
427
+ success: false;
428
+ status: number;
429
+ error: string;
430
+ message: string;
431
+ path?: string;
432
+ timestamp?: string;
433
+ stack?: string;
434
+ }
435
+
436
+ interface HttpResponseOptions {
437
+ message?: string | null;
438
+ meta?: TypeAnyObject;
439
+ }
440
+
441
+ interface UploadOptions {
442
+ count?: number;
443
+ path?: string;
444
+ size?: number;
445
+ types?: Array<string>;
446
+ }
447
+
448
+ type ValidationFunction = (_$: typeof Validation) => TypeObject<ValidationBase>;
409
449
 
410
450
  declare class Application<T extends TypeAnyObject = TypeAnyObject> extends EventEmitter<T> {
411
451
  private readonly _app;
412
452
  private _server?;
453
+ private readonly _boundServers;
413
454
  private readonly _options;
414
- private readonly _base;
415
- private readonly _router;
455
+ private readonly _baseRouter;
456
+ private readonly _globalRouter;
416
457
  private readonly _controllers;
417
458
  get controllers(): Array<object>;
418
459
  get instance(): Express;
419
460
  get router(): Router;
420
461
  get server(): http.Server | https.Server | undefined;
421
- constructor(controllers: Array<object | TypeAnyConstructor>, options?: IOptions);
462
+ constructor(controllers: Array<object | TypeAnyConstructor>, options?: ExpressOptions);
422
463
  init(): void;
423
464
  error(message: any, _source?: string): void;
424
465
  log(message: string, _source?: string): void;
425
- private _args;
426
- private _handles;
427
- private _extends;
428
- private _indexes;
429
- private _middlewares;
430
- private _notFound;
431
- private _port;
466
+ private _resolveArgs;
467
+ private _buildMiddlewareChain;
468
+ private _collectExtends;
469
+ private _filterParamsByKey;
470
+ private _collectMiddlewares;
471
+ private _logRouteNotFound;
472
+ private _formatListeningMessage;
432
473
  listen(): Promise<void>;
474
+ close(): Promise<void>;
475
+ private _resolveMode;
476
+ private _resolveTls;
477
+ private _bindServer;
478
+ private _startHttp;
479
+ private _startHttps;
480
+ private _startHttpsWithRedirect;
481
+ private _startHybrid;
433
482
  }
434
483
 
435
484
  declare const Controller: (path?: string) => ClassDecorator;
@@ -458,11 +507,11 @@ declare const Put: (path?: string) => MethodDecorator;
458
507
 
459
508
  declare const Middleware: (method: string, argument?: any) => MethodDecorator;
460
509
 
461
- declare const Upload: (options: TypeObject<IUpload>) => MethodDecorator;
510
+ declare const Upload: (options: TypeObject<UploadOptions>) => MethodDecorator;
462
511
 
463
512
  declare const Use: (callback: IHandler, argument?: any) => MethodDecorator;
464
513
 
465
- declare const Validate: (value: TypeObject<ValidationBase> | ParseFunction) => MethodDecorator;
514
+ declare const Validate: (value: TypeObject<ValidationBase> | ValidationFunction) => MethodDecorator;
466
515
 
467
516
  declare const App: (key?: string) => ParameterDecorator;
468
517
 
@@ -515,6 +564,17 @@ declare class ValidationError extends ResponseError {
515
564
  constructor(message: string);
516
565
  }
517
566
 
567
+ declare class HttpResponse {
568
+ static created(res: Response, id?: string | number, options?: HttpResponseOptions): HttpResponseCreated;
569
+ static noContent(res: Response): void;
570
+ static ok<T = TypeAnyObject | Array<TypeAnyObject>>(res: Response, data: T, options?: HttpResponseOptions): HttpResponseBase<T>;
571
+ static error(req: Request, res: Response, error: unknown): HttpResponseError;
572
+ private static isDev;
573
+ private static normalizeError;
574
+ private static safeStatus;
575
+ private static safeMessage;
576
+ }
577
+
518
578
  declare class Metadata {
519
579
  static readonly EXTENDS: unique symbol;
520
580
  static readonly MIDDLEWARE: unique symbol;
@@ -528,7 +588,7 @@ declare class Metadata {
528
588
  static routers(target: any): Array<IRouter>;
529
589
  }
530
590
 
531
- declare class Status {
591
+ declare class StatusCodes {
532
592
  static readonly CONTINUE = 100;
533
593
  static readonly SWITCHING_PROTOCOLS = 101;
534
594
  static readonly PROCESSING = 102;
@@ -594,5 +654,64 @@ declare class Status {
594
654
  static readonly NETWORK_CONNECTION_TIMEOUT_ERROR = 599;
595
655
  }
596
656
 
597
- export { All, App, Application, Argument, BadRequestError, Body, Cache, Context, Controller, Cookies, Ctx, Delete, Extends, Files, ForbiddenError, Get, Head, Headers, InternalServerError, Metadata, Methods, Middleware, NotFoundError, Options, Params, Patch, Post, Put, Query, ResponseError, Session, Status, UnauthorizedError, Upload, Use, Validate, ValidationError, methodFactory, parameterFactory };
598
- export type { CallbackObject, ComponentsObject, ContactObject, EncodingObject, ExampleObject, ExternalDocumentationObject, HeaderObject, IArgs, ICache, ICookie, IFile, IHandler, IMiddlewares, IOptions, IParameter, IRouter, IStore, IUpload, IUse, InfoObject, LicenseObject, LinkObject, MediaTypeObject, Method, OAuthFlowObject, OAuthFlowsObject, OpenAPIObject, OperationObject, ParameterObject, ParseFunction, PathItemObject, PathsObject, ReferenceObject, RequestBodyObject, ResponseObject, ResponsesObject, SchemaObject, SecurityRequirementObject, SecuritySchemeObject, ServerObject, ServerVariableObject, TagObject };
657
+ declare class StatusText {
658
+ static readonly 100 = "Continue";
659
+ static readonly 101 = "Switching Protocols";
660
+ static readonly 102 = "Processing";
661
+ static readonly 200 = "OK";
662
+ static readonly 201 = "Created";
663
+ static readonly 202 = "Accepted";
664
+ static readonly 203 = "Non-Authoritative Information";
665
+ static readonly 204 = "No Content";
666
+ static readonly 205 = "Reset Content";
667
+ static readonly 206 = "Partial Content";
668
+ static readonly 207 = "Multi-Status";
669
+ static readonly 226 = "IM Used";
670
+ static readonly 300 = "Multiple Choices";
671
+ static readonly 301 = "Moved Permanently";
672
+ static readonly 302 = "Found";
673
+ static readonly 303 = "See Other";
674
+ static readonly 304 = "Not Modified";
675
+ static readonly 305 = "Use Proxy";
676
+ static readonly 307 = "Temporary Redirect";
677
+ static readonly 308 = "Permanent Redirect";
678
+ static readonly 400 = "Bad Request";
679
+ static readonly 401 = "Unauthorized";
680
+ static readonly 402 = "Payment Required";
681
+ static readonly 403 = "Forbidden";
682
+ static readonly 404 = "Not Found";
683
+ static readonly 405 = "Method Not Allowed";
684
+ static readonly 406 = "Not Acceptable";
685
+ static readonly 407 = "Proxy Authentication Required";
686
+ static readonly 408 = "Request Timeout";
687
+ static readonly 409 = "Conflict";
688
+ static readonly 410 = "Gone";
689
+ static readonly 411 = "Length Required";
690
+ static readonly 412 = "Precondition Failed";
691
+ static readonly 413 = "Payload Too Large";
692
+ static readonly 414 = "URI Too Long";
693
+ static readonly 415 = "Unsupported Media Type";
694
+ static readonly 416 = "Range Not Satisfiable";
695
+ static readonly 417 = "Expectation Failed";
696
+ static readonly 418 = "I'm a teapot";
697
+ static readonly 422 = "Unprocessable Entity";
698
+ static readonly 423 = "Locked";
699
+ static readonly 424 = "Failed Dependency";
700
+ static readonly 426 = "Upgrade Required";
701
+ static readonly 428 = "Precondition Required";
702
+ static readonly 429 = "Too Many Requests";
703
+ static readonly 431 = "Request Header Fields Too Large";
704
+ static readonly 451 = "Unavailable For Legal Reasons";
705
+ static readonly 500 = "Internal Server Error";
706
+ static readonly 501 = "Not Implemented";
707
+ static readonly 502 = "Bad Gateway";
708
+ static readonly 503 = "Service Unavailable";
709
+ static readonly 504 = "Gateway Time-out";
710
+ static readonly 505 = "HTTP Version Not Supported";
711
+ static readonly 506 = "Variant Also Negotiates";
712
+ static readonly 507 = "Insufficient Storage";
713
+ static readonly 511 = "Network Authentication Required";
714
+ }
715
+
716
+ export { All, App, Application, Argument, BadRequestError, Body, Cache, Context, Controller, Cookies, Ctx, Delete, Extends, Files, ForbiddenError, Get, Head, Headers, HttpResponse, InternalServerError, Metadata, Methods, Middleware, NotFoundError, Options, Params, Patch, Post, Put, Query, ResponseError, Session, StatusCodes, StatusText, UnauthorizedError, Upload, Use, Validate, ValidationError, methodFactory, parameterFactory };
717
+ export type { CallbackObject, ComponentsObject, ContactObject, EncodingObject, ExampleObject, ExpressOptions, ExternalDocumentationObject, FileUpload, HeaderObject, HttpResponseBase, HttpResponseCreated, HttpResponseError, HttpResponseOptions, IArgs, ICache, ICookie, IHandler, IMiddlewares, IParameter, IRouter, IStore, IUse, InfoObject, LicenseObject, LinkObject, MediaTypeObject, Method, OAuthFlowObject, OAuthFlowsObject, OpenAPIObject, OperationObject, ParameterObject, PathItemObject, PathsObject, ReferenceObject, RequestBodyObject, ResponseObject, ResponsesObject, SchemaObject, SecurityRequirementObject, SecuritySchemeObject, ServerMode, ServerObject, ServerVariableObject, TagObject, TlsOptions, UploadOptions, ValidationFunction };
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @andrewcaires/express v2.1.0
2
+ * @andrewcaires/express v2.2.0
3
3
  * Decorators for express
4
4
  * (c) 2026 Andrew Caires
5
5
  * @license: MIT
6
6
  */
7
- import{metadata as e,getInjectionArgs as t}from"@andrewcaires/decorator";import{Log as s}from"@andrewcaires/node";import{isNumber as r,forEachKey as o,map as i,isUndefined as n,isNull as a,isObject as l,EventEmitter as h,isConstructor as u,merge as d,isFunction as p,noop as E,isArray as c,uuidv7 as _,isString as T,Validation as O}from"@andrewcaires/utils.js";import m from"compression";import R from"cookie-parser";import v from"cors";import N,{Router as A,json as I,urlencoded as g}from"express";import S from"express-session";import{existsSync as D}from"fs";import*as f from"http";import*as y from"https";import{Server as x}from"net";import{resolve as L,join as C}from"path";import{getClientIp as U}from"request-ip";import P,{diskStorage as F}from"multer";function b(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}l((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class k{}k.CONTINUE=100,k.SWITCHING_PROTOCOLS=101,k.PROCESSING=102,k.OK=200,k.CREATED=201,k.ACCEPTED=202,k.NON_AUTHORITATIVE_INFORMATION=203,k.NO_CONTENT=204,k.RESET_CONTENT=205,k.PARTIAL_CONTENT=206,k.MULTI_STATUS=207,k.ALREADY_REPORTED=208,k.IM_USED=226,k.MULTIPLE_CHOICES=300,k.MOVED_PERMANENTLY=301,k.FOUND=302,k.SEE_OTHER=303,k.NOT_MODIFIED=304,k.USE_PROXY=305,k.TEMPORARY_REDIRECT=307,k.PERMANENT_REDIRECT=308,k.BAD_REQUEST=400,k.UNAUTHORIZED=401,k.PAYMENT_REQUIRED=402,k.FORBIDDEN=403,k.NOT_FOUND=404,k.METHOD_NOT_ALLOWED=405,k.NOT_ACCEPTABLE=406,k.PROXY_AUTHENTICATION_REQUIRED=407,k.REQUEST_TIMEOUT=408,k.CONFLICT=409,k.GONE=410,k.LENGTH_REQUIRED=411,k.PRECONDITION_FAILED=412,k.PAYLOAD_TOO_LARGE=413,k.REQUEST_URI_TOO_LONG=414,k.UNSUPPORTED_MEDIA_TYPE=415,k.REQUESTED_RANGE_NOT_SATISFIABLE=416,k.EXPECTATION_FAILED=417,k.IM_A_TEAPOT=418,k.MISDIRECTED_REQUEST=421,k.UNPROCESSABLE_ENTITY=422,k.LOCKED=423,k.FAILED_DEPENDENCY=424,k.UPGRADE_REQUIRED=426,k.PRECONDITION_REQUIRED=428,k.TOO_MANY_REQUESTS=429,k.REQUEST_HEADER_FIELDS_TOO_LARGE=431,k.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,k.UNAVAILABLE_FOR_LEGAL_REASONS=451,k.CLIENT_CLOSED_REQUEST=499,k.INTERNAL_SERVER_ERROR=500,k.NOT_IMPLEMENTED=501,k.BAD_GATEWAY=502,k.SERVICE_UNAVAILABLE=503,k.GATEWAY_TIMEOUT=504,k.HTTP_VERSION_NOT_SUPPORTED=505,k.VARIANT_ALSO_NEGOCIATES=506,k.INSUFFICIENT_STORAGE=507,k.LOOP_DETECTED=508,k.NOT_EXTENDED=510,k.NETWORK_AUTHENTICATION_REQUIRED=511,k.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class M extends Error{constructor(e,t=k.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class w extends M{constructor(e="Bad Request"){super(e,k.BAD_REQUEST)}}class H extends M{constructor(e="Forbidden"){super(e,k.FORBIDDEN)}}class q extends M{constructor(e="Internal server error"){super(e,k.INTERNAL_SERVER_ERROR)}}class Q extends M{constructor(e="Record not found"){super(e,k.NOT_FOUND)}}class $ extends M{constructor(e="Unauthorized"){super(e,k.UNAUTHORIZED)}}class G extends M{constructor(e){super(e,k.UNPROCESSABLE_ENTITY)}}class j{constructor(e,t,s,r,o){this.storage={},this.req=e,this.res=t,this.next=s,this.app=r,this.controller=o}cache(e){const t=Object.assign({},e),s=[];t.private?s.push("private"):t.public&&s.push("public"),t.noStore&&(t.noCache=!0,s.push("no-store")),t.noCache&&(t.maxAge=0,delete t.sMaxAge,s.push("no-cache")),t.noTransform&&s.push("no-transform"),t.proxyRevalidate&&s.push("proxy-revalidate"),t.mustRevalidate?s.push("must-revalidate"):t.noCache||(r(t.staleIfError)&&s.push(`stale-if-error=${t.staleIfError}`),r(t.staleWhileRevalidate)&&s.push(`stale-while-revalidate=${t.staleWhileRevalidate}`)),r(t.maxAge)&&s.push(`max-age=${t.maxAge}`),r(t.sMaxAge)&&s.push(`s-maxage=${t.sMaxAge}`),s.length&&(this.res.setHeader("Cache-Control",s.join(",")),t.noCache&&o({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}clearCookie(e,t){this.res.clearCookie(e,t)}close(e){this.isResponded()||this.res.json(null!=e?e:this.storage)}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){var t;let s=null!==(t=e.toString())&&void 0!==t?t:"",r=k.INTERNAL_SERVER_ERROR;e instanceof Error&&(s=e.message,e instanceof M&&(r=e.status)),this.send(r,{error:s})}file(e){this.isResponded()||(this.status(k.OK),this.res.sendFile(L(e)))}getBody(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.body)&&void 0!==t?t:{}}getBodyValue(e){var t;return null===(t=this.req.body)||void 0===t?void 0:t[e]}getCookie(e){var t;return this.normalize(null===(t=this.req.cookies)||void 0===t?void 0:t[e])}getCookies(){var e,t;return i(null!==(t=null===(e=this.req)||void 0===e?void 0:e.cookies)&&void 0!==t?t:{},e=>this.normalize(e))}getFiles(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.files)&&void 0!==t?t:{}}getHeader(e){var t;return this.normalize(null===(t=this.req.headers)||void 0===t?void 0:t[e])}getHeaders(){var e,t;return i(null!==(t=null===(e=this.req)||void 0===e?void 0:e.headers)&&void 0!==t?t:{},e=>this.normalize(e))}getIp(){return U(this.req)||"0.0.0.0"}getQuery(e){var t;return this.normalize(null===(t=this.req.query)||void 0===t?void 0:t[e])}getQueries(){var e,t;return i(null!==(t=null===(e=this.req)||void 0===e?void 0:e.query)&&void 0!==t?t:{},e=>this.normalize(e))}getParam(e){var t;const s=null===(t=this.req.params)||void 0===t?void 0:t[e];return n(s)?void 0:String(s)}getParams(){var e,t;return i(null!==(t=null===(e=this.req)||void 0===e?void 0:e.params)&&void 0!==t?t:{},e=>{if(!n(e)&&!a(e))return String(e)})}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}isResponded(){return this.res.headersSent||this.res.writableEnded}json(e){this.send(k.OK,e)}normalize(e){if(!n(e)&&!a(e))return l(e)?JSON.stringify(e):String(e)}prepare(e,t){this.isResponded()||(this.status(e),this.storage=t)}send(e,t){this.isResponded()||(this.status(e),204===e||304===e||n(t)?this.res.end():this.res.json(t))}setCookie(e,t,s){this.res.cookie(e,t,null!=s?s:{})}status(e){return n(e)||this.res.status(e),this.res.statusCode}success(e){this.send(k.OK,{message:e})}}class B{static extends(t){return e(B.EXTENDS,t,[])}static middleware(t){return e(B.MIDDLEWARE,t,[])}static parameters(t){return e(B.PARAMETERS,t,[])}static path(t,s){return e(B.PATH,t,s)}static routers(t){return e(B.ROUTERS,t,[])}}B.EXTENDS=Symbol("EXTENDS"),B.MIDDLEWARE=Symbol("MIDDLEWARE"),B.PARAMETERS=Symbol("PARAMETERS"),B.PATH=Symbol("PATH"),B.ROUTERS=Symbol("ROUTERS");class V extends h{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(e,s){var r,o;super(),this._app=N(),this._options={},this._base=A(),this._router=A(),this._controllers=[],this._controllers.push(...e.map(e=>u(e)?new e(...t(e)):e)),this._options=d({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=s?s:{}),this._app.use(I(this._options.json)),this._app.disable("x-powered-by"),this._app.use(g({extended:!0})),this._options.cross&&this._app.use(v(l(this._options.cross)?this._options.cross:{})),this._app.use(m(this._options.compression)),this._app.use(R(null===(r=this._options.cookie)||void 0===r?void 0:r.secret,this._options.cookie)),this._app.use(S(this._options.session)),this.init(),this._app.use(this._router);const i=(null===(o=this._options.path)||void 0===o?void 0:o.length)?this._options.path:"/";if(this._app.use(i,this._base),this._app.all(i+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(k.NOT_FOUND),t.json({message:"INVALID API"}))}),this._options.public){const e=L(this._options.public);D(e)&&this._app.use(N.static(e)),this._app.get("*path",(t,s)=>{D(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):(s.status(k.NOT_FOUND),s.json({message:'FILE "index.html" NOT FOUND'}))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(k.NOT_FOUND),t.json({message:"INVALID API"}))});this._controllers.forEach(e=>{const t=A(),s=this._middlewares(e),r=B.parameters(e);this._extends(e).forEach(e=>{s.push(...this._middlewares(e)),r.push(...B.parameters(e))}),B.routers(e).forEach(o=>{const i=o.propertyKey.toString();if(p(e[i])){if(!p(t[o.method]))return this._notFound(o.method);const n=this._handles(e,i,s,r);return t[o.method](o.path,...n,(t,s,o)=>b(this,void 0,void 0,function*(){const n=new j(t,s,o,this,e),a=this._args(n,this._indexes(i,r)),h=yield e[i](...a);n.close(c(h)||l(h)?h:void 0)}))}this._notFound(`${e.name}.${i}`)}),this._extends(e).forEach(o=>{B.routers(o).forEach(o=>{const i=o.propertyKey.toString();if(p(e[i])){if(!p(t[o.method]))return this._notFound(o.method);const n=this._handles(e,i,s,r);return t[o.method](o.path,...n,(t,s,o)=>b(this,void 0,void 0,function*(){const n=new j(t,s,o,this,e),a=this._args(n,this._indexes(i,r)),h=yield e[i](...a);n.close(c(h)||l(h)?h:void 0)}))}this._notFound(`${e.constructor.name}.${i}`)})}),this._base.use(B.path(e,"/"),t)})}init(){}error(e,t){s.error(e)}log(e,t){s.info(e)}_args(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_handles(e,t,s,r){return s.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=E){const s=this._indexes(t.method,r);return(r,o,i)=>b(this,void 0,void 0,function*(){const n=new j(r,o,i,this,e),a=p(t.argument)?t.argument(n):t.argument,h=yield t.callback.call(e,...this._args(n,s,a));(c(h)||l(h))&&n.close(h)})}this._notFound(t.method)}).filter(p)}_extends(e){return B.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...B.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return b(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=f.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=f.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(k.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()}),t=y.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new x(s=>{s.once("data",r=>{s.pause(),s.unshift(r),(22===r[0]?t:e).emit("connection",s),process.nextTick(()=>s.resume())})}).listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t}this._server||(443==this._options.port&&e.listen(80,()=>this.log(this._port(80),"express")),t.listen(this._options.port,()=>this.log(this._port(this._options.port),"express")),this._server=t)}})}}const Y=e=>t=>{B.path(t,(null==e?void 0:e.length)?e:"/")},K=e=>t=>{B.extends(t).push(e)},W=e=>t=>(s,r,o)=>{B.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},z=W(({app:e})=>e),X=W(({argument:e})=>e),Z=W(({ctx:e,key:t})=>t?e.getBodyValue(t):e.getBody()),J=W(({ctx:e,key:t})=>t?e.getCookie(t):e.getCookies()),ee=W(({ctx:e})=>e),te=W(({ctx:e})=>e.getFiles()),se=W(({ctx:e,key:t})=>t?e.getHeader(t):e.getHeaders()),re=W(({ctx:e,key:t})=>t?e.getParam(t):e.getParams()),oe=W(({ctx:e,key:t})=>t?e.getQuery(t):e.getQueries()),ie=W(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),ne=(e,t)=>(s,r)=>{const o=_();ee()(s,o,0),B.middleware(s).push({method:o,argument:t,propertyKey:r,callback:e})},ae=e=>(t,s,r)=>{ne(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},le={ALL:"all",GET:"get",POST:"post",PUT:"put",HEAD:"head",DELETE:"delete",OPTIONS:"options",PATCH:"patch"},he=e=>t=>(s,r)=>{B.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},ue=he(le.ALL),de=he(le.DELETE),pe=he(le.GET),Ee=he(le.HEAD),ce=he(le.OPTIONS),_e=he(le.PATCH),Te=he(le.POST),Oe=he(le.PUT),me=(e,t)=>(s,r)=>{let o=E;if(T(r)){const t=s;p(t[e])&&(o=t[e])}B.middleware(s).push({method:e,argument:t,propertyKey:r,callback:o})},Re=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},ve=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},Ne=(e,t)=>{const s=_()+"."+t;return D(C(e,s))?Ne(e,t):s},Ae=e=>{const t=d({},e),s=F({destination(e,s,r){var o;const i=ve(t,s.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,s,r){var o;const i=ve(t,s.fieldname);r(null,Ne(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",Re(s.originalname)))}}),r=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),o=P({storage:s,fileFilter(e,s,r){var o;const i=ve(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(Re(e.originalname))||t.includes(e.mimetype.toLowerCase()))(s,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${s.fieldname}"`)):r(new Error(`UPLOAD FIELD "${s.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*r*1024}}).fields(Object.keys(t).map(e=>{var s,r;return{name:e,maxCount:null!==(r=null===(s=t[e])||void 0===s?void 0:s.count)&&void 0!==r?r:1}}));return(e,t,s)=>{ne(e=>{o(e.req,e.res,t=>{if(t)return"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t);e.next()})})(e,t,s)}},Ie=e=>{const t=O.object(p(e)?e(O):e).parse();return(e,s,r)=>{ne(e=>b(void 0,void 0,void 0,function*(){var s,r;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{});if(o)return e.error(new G(null!=i?i:o));e.req.body=n,e.next()}))(e,s,r)}};export{ue as All,z as App,V as Application,X as Argument,w as BadRequestError,Z as Body,ae as Cache,j as Context,Y as Controller,J as Cookies,ee as Ctx,de as Delete,K as Extends,te as Files,H as ForbiddenError,pe as Get,Ee as Head,se as Headers,q as InternalServerError,B as Metadata,le as Methods,me as Middleware,Q as NotFoundError,ce as Options,re as Params,_e as Patch,Te as Post,Oe as Put,oe as Query,M as ResponseError,ie as Session,k as Status,$ as UnauthorizedError,Ae as Upload,ne as Use,Ie as Validate,G as ValidationError,he as methodFactory,W as parameterFactory};
7
+ import{metadata as e,getInjectionArgs as t}from"@andrewcaires/decorator";import{Log as s}from"@andrewcaires/node";import{isNumber as r,isString as o,isObject as i,uuidv7 as n,forEachKey as a,map as l,isUndefined as u,isNull as d,EventEmitter as h,isConstructor as c,merge as p,isFunction as E,noop as _,isArray as v,Validation as m}from"@andrewcaires/utils.js";import R from"compression";import T from"cookie-parser";import g from"cors";import N,{Router as O,json as S,urlencoded as f}from"express";import A from"express-session";import{existsSync as I}from"fs";import*as y from"http";import*as D from"https";import*as C from"net";import{resolve as P,join as L}from"path";import{getClientIp as b}from"request-ip";import U,{diskStorage as x}from"multer";function M(e,t,s,r){return new(s||(s=Promise))(function(o,i){function n(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(n,a)}l((r=r.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class F{}F.CONTINUE=100,F.SWITCHING_PROTOCOLS=101,F.PROCESSING=102,F.OK=200,F.CREATED=201,F.ACCEPTED=202,F.NON_AUTHORITATIVE_INFORMATION=203,F.NO_CONTENT=204,F.RESET_CONTENT=205,F.PARTIAL_CONTENT=206,F.MULTI_STATUS=207,F.ALREADY_REPORTED=208,F.IM_USED=226,F.MULTIPLE_CHOICES=300,F.MOVED_PERMANENTLY=301,F.FOUND=302,F.SEE_OTHER=303,F.NOT_MODIFIED=304,F.USE_PROXY=305,F.TEMPORARY_REDIRECT=307,F.PERMANENT_REDIRECT=308,F.BAD_REQUEST=400,F.UNAUTHORIZED=401,F.PAYMENT_REQUIRED=402,F.FORBIDDEN=403,F.NOT_FOUND=404,F.METHOD_NOT_ALLOWED=405,F.NOT_ACCEPTABLE=406,F.PROXY_AUTHENTICATION_REQUIRED=407,F.REQUEST_TIMEOUT=408,F.CONFLICT=409,F.GONE=410,F.LENGTH_REQUIRED=411,F.PRECONDITION_FAILED=412,F.PAYLOAD_TOO_LARGE=413,F.REQUEST_URI_TOO_LONG=414,F.UNSUPPORTED_MEDIA_TYPE=415,F.REQUESTED_RANGE_NOT_SATISFIABLE=416,F.EXPECTATION_FAILED=417,F.IM_A_TEAPOT=418,F.MISDIRECTED_REQUEST=421,F.UNPROCESSABLE_ENTITY=422,F.LOCKED=423,F.FAILED_DEPENDENCY=424,F.UPGRADE_REQUIRED=426,F.PRECONDITION_REQUIRED=428,F.TOO_MANY_REQUESTS=429,F.REQUEST_HEADER_FIELDS_TOO_LARGE=431,F.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,F.UNAVAILABLE_FOR_LEGAL_REASONS=451,F.CLIENT_CLOSED_REQUEST=499,F.INTERNAL_SERVER_ERROR=500,F.NOT_IMPLEMENTED=501,F.BAD_GATEWAY=502,F.SERVICE_UNAVAILABLE=503,F.GATEWAY_TIMEOUT=504,F.HTTP_VERSION_NOT_SUPPORTED=505,F.VARIANT_ALSO_NEGOCIATES=506,F.INSUFFICIENT_STORAGE=507,F.LOOP_DETECTED=508,F.NOT_EXTENDED=510,F.NETWORK_AUTHENTICATION_REQUIRED=511,F.NETWORK_CONNECTION_TIMEOUT_ERROR=599;class k{}k[100]="Continue",k[101]="Switching Protocols",k[102]="Processing",k[200]="OK",k[201]="Created",k[202]="Accepted",k[203]="Non-Authoritative Information",k[204]="No Content",k[205]="Reset Content",k[206]="Partial Content",k[207]="Multi-Status",k[226]="IM Used",k[300]="Multiple Choices",k[301]="Moved Permanently",k[302]="Found",k[303]="See Other",k[304]="Not Modified",k[305]="Use Proxy",k[307]="Temporary Redirect",k[308]="Permanent Redirect",k[400]="Bad Request",k[401]="Unauthorized",k[402]="Payment Required",k[403]="Forbidden",k[404]="Not Found",k[405]="Method Not Allowed",k[406]="Not Acceptable",k[407]="Proxy Authentication Required",k[408]="Request Timeout",k[409]="Conflict",k[410]="Gone",k[411]="Length Required",k[412]="Precondition Failed",k[413]="Payload Too Large",k[414]="URI Too Long",k[415]="Unsupported Media Type",k[416]="Range Not Satisfiable",k[417]="Expectation Failed",k[418]="I'm a teapot",k[422]="Unprocessable Entity",k[423]="Locked",k[424]="Failed Dependency",k[426]="Upgrade Required",k[428]="Precondition Required",k[429]="Too Many Requests",k[431]="Request Header Fields Too Large",k[451]="Unavailable For Legal Reasons",k[500]="Internal Server Error",k[501]="Not Implemented",k[502]="Bad Gateway",k[503]="Service Unavailable",k[504]="Gateway Time-out",k[505]="HTTP Version Not Supported",k[506]="Variant Also Negotiates",k[507]="Insufficient Storage",k[511]="Network Authentication Required";class w extends Error{constructor(e,t=F.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class H extends w{constructor(e="Bad Request"){super(e,F.BAD_REQUEST)}}class q extends w{constructor(e="Forbidden"){super(e,F.FORBIDDEN)}}class B extends w{constructor(e="Internal server error"){super(e,F.INTERNAL_SERVER_ERROR)}}class K extends w{constructor(e="Not Found"){super(e,F.NOT_FOUND)}}class G extends w{constructor(e="Unauthorized"){super(e,F.UNAUTHORIZED)}}class Q extends w{constructor(e){super(e,F.UNPROCESSABLE_ENTITY)}}class V{static created(e,t,s){var r,o;const i=F.CREATED,n={success:!0,status:i,data:t?{id:t}:{},meta:null!==(r=null==s?void 0:s.meta)&&void 0!==r?r:{},message:null!==(o=null==s?void 0:s.message)&&void 0!==o?o:null};return e.status(i).json(n),n}static noContent(e){e.status(F.NO_CONTENT).end()}static ok(e,t,s){var r,o;const i=F.OK,n={success:!0,status:i,data:t,meta:null!==(r=null==s?void 0:s.meta)&&void 0!==r?r:{},message:null!==(o=null==s?void 0:s.message)&&void 0!==o?o:null};return e.status(i).json(n),n}static error(e,t,s){var r,o;const{status:i,message:n}=this.normalizeError(s),a=Object.assign({success:!1,status:i,error:null!==(r=null==k?void 0:k[i])&&void 0!==r?r:"Internal Server Error",message:n,path:null!==(o=e.originalUrl)&&void 0!==o?o:e.url,timestamp:(new Date).toISOString()},this.isDev()&&s instanceof Error&&s.stack?{stack:s.stack}:{});return t.status(i).json(a),a}static isDev(){return"production"!==process.env.NODE_ENV}static normalizeError(e){let t=F.INTERNAL_SERVER_ERROR,s=k[500];if(e instanceof w)return t=this.safeStatus(e.status),s=this.safeMessage(e.message)||s,{status:t,message:s};if(e instanceof Error){const o=e;return r(o.statusCode)?t=this.safeStatus(o.statusCode):r(o.status)&&(t=this.safeStatus(o.status)),s=this.safeMessage(e.message)||s,{status:t,message:s}}if(o(e))return s=this.safeMessage(e)||s,{status:t,message:s};if(e&&i(e)){const i=e;return r(i.statusCode)?t=this.safeStatus(i.statusCode):r(i.status)&&(t=this.safeStatus(i.status)),o(i.message)&&(s=this.safeMessage(i.message)||s),{status:t,message:s}}return{status:t,message:s}}static safeStatus(e){if(!Number.isFinite(e))return F.INTERNAL_SERVER_ERROR;const t=Math.trunc(e);return t<400||t>599?F.INTERNAL_SERVER_ERROR:t}static safeMessage(e){if(!o(e))return"";const t=e.trim();return t.length>2e3?t.slice(0,2e3)+"...":t}}class ${constructor(e,t,s,r,o){this.storage={},this.req=e,this.res=t,this.next=s,this.id=n(),this.app=r,this.controller=o}cache(e){const t=Object.assign({},e),s=[];t.private?s.push("private"):t.public&&s.push("public"),t.noStore&&(t.noCache=!0,s.push("no-store")),t.noCache&&(t.maxAge=0,delete t.sMaxAge,s.push("no-cache")),t.noTransform&&s.push("no-transform"),t.proxyRevalidate&&s.push("proxy-revalidate"),t.mustRevalidate?s.push("must-revalidate"):t.noCache||(r(t.staleIfError)&&s.push(`stale-if-error=${t.staleIfError}`),r(t.staleWhileRevalidate)&&s.push(`stale-while-revalidate=${t.staleWhileRevalidate}`)),r(t.maxAge)&&s.push(`max-age=${t.maxAge}`),r(t.sMaxAge)&&s.push(`s-maxage=${t.sMaxAge}`),s.length&&(this.res.setHeader("Cache-Control",s.join(",")),t.noCache&&a({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}clearCookie(e,t){this.res.clearCookie(e,t)}close(e){this.isResponded()||this.res.json(null!=e?e:this.storage)}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){this.isResponded()||V.error(this.req,this.res,e)}file(e){this.isResponded()||(this.status(F.OK),this.res.sendFile(P(e)))}getBody(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.body)&&void 0!==t?t:{}}getBodyValue(e){var t;return null===(t=this.req.body)||void 0===t?void 0:t[e]}getCookie(e){var t;return this.normalize(null===(t=this.req.cookies)||void 0===t?void 0:t[e])}getCookies(){var e,t;return l(null!==(t=null===(e=this.req)||void 0===e?void 0:e.cookies)&&void 0!==t?t:{},e=>this.normalize(e))}getFiles(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.files)&&void 0!==t?t:{}}getHeader(e){var t;return this.normalize(null===(t=this.req.headers)||void 0===t?void 0:t[e])}getHeaders(){var e,t;return l(null!==(t=null===(e=this.req)||void 0===e?void 0:e.headers)&&void 0!==t?t:{},e=>this.normalize(e))}getIp(){return b(this.req)||"0.0.0.0"}getQuery(e){var t;return this.normalize(null===(t=this.req.query)||void 0===t?void 0:t[e])}getQueries(){var e,t;return l(null!==(t=null===(e=this.req)||void 0===e?void 0:e.query)&&void 0!==t?t:{},e=>this.normalize(e))}getParam(e){var t;const s=null===(t=this.req.params)||void 0===t?void 0:t[e];return u(s)?void 0:String(s)}getParams(){var e,t;return l(null!==(t=null===(e=this.req)||void 0===e?void 0:e.params)&&void 0!==t?t:{},e=>{if(!u(e)&&!d(e))return String(e)})}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}isResponded(){return this.res.headersSent||this.res.writableEnded}json(e){this.send(F.OK,e)}normalize(e){if(!u(e)&&!d(e))return i(e)?JSON.stringify(e):String(e)}ok(e,t){this.isResponded()||V.ok(this.res,e,t)}prepare(e,t){this.isResponded()||(this.status(e),this.storage=t)}send(e,t){this.isResponded()||(this.status(e),204===e||304===e||u(t)?this.res.end():this.res.json(t))}setCookie(e,t,s){this.res.cookie(e,t,null!=s?s:{})}status(e){return u(e)||this.res.status(e),this.res.statusCode}success(e){this.send(F.OK,{message:e})}}class j{static extends(t){return e(j.EXTENDS,t,[])}static middleware(t){return e(j.MIDDLEWARE,t,[])}static parameters(t){return e(j.PARAMETERS,t,[])}static path(t,s){return e(j.PATH,t,s)}static routers(t){return e(j.ROUTERS,t,[])}}j.EXTENDS=Symbol("EXTENDS"),j.MIDDLEWARE=Symbol("MIDDLEWARE"),j.PARAMETERS=Symbol("PARAMETERS"),j.PATH=Symbol("PATH"),j.ROUTERS=Symbol("ROUTERS");class Y extends h{get controllers(){return[...this._controllers]}get instance(){return this._app}get router(){return this._globalRouter}get server(){return this._server}constructor(e,s){var r,o;super(),this._app=N(),this._boundServers=[],this._options={},this._baseRouter=O(),this._globalRouter=O(),this._controllers=[],this._controllers.push(...e.map(e=>c(e)?new e(...t(e)):e)),this._options=p({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=s?s:{}),this._app.use(S(this._options.json)),this._app.disable("x-powered-by"),this._app.use(f({extended:!0})),this._options.cross&&this._app.use(g(i(this._options.cross)?this._options.cross:{})),this._app.use(R(this._options.compression)),this._app.use(T(null===(r=this._options.cookie)||void 0===r?void 0:r.secret,this._options.cookie)),this._app.use(A(this._options.session)),this.init(),this._app.use(this._globalRouter);const n=(null===(o=this._options.path)||void 0===o?void 0:o.length)?this._options.path:"/";if(this._app.use(n,this._baseRouter),this._app.all(n+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):V.error(e,t,new K("Endpoint Not Found"))}),this._options.public){const e=P(this._options.public);I(e)&&this._app.use(N.static(e)),this._app.get("*path",(t,s)=>{I(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):V.error(t,s,new K('FILE "index.html" Not Found'))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):V.error(e,t,new K("Endpoint not found"))});this._controllers.forEach(e=>{const t=O(),s=this._collectMiddlewares(e),r=j.parameters(e);this._collectExtends(e).forEach(e=>{s.push(...this._collectMiddlewares(e)),r.push(...j.parameters(e))}),j.routers(e).forEach(o=>{const n=o.propertyKey.toString();if(E(e[n])){if(!E(t[o.method]))return this._logRouteNotFound(o.method);const a=this._buildMiddlewareChain(e,n,s,r);return t[o.method](o.path,...a,(t,s,o)=>M(this,void 0,void 0,function*(){const a=new $(t,s,o,this,e),l=this._resolveArgs(a,this._filterParamsByKey(n,r)),u=yield e[n](...l);a.close(v(u)||i(u)?u:void 0)}))}this._logRouteNotFound(`${e.name}.${n}`)}),this._collectExtends(e).forEach(o=>{j.routers(o).forEach(o=>{const n=o.propertyKey.toString();if(E(e[n])){if(!E(t[o.method]))return this._logRouteNotFound(o.method);const a=this._buildMiddlewareChain(e,n,s,r);return t[o.method](o.path,...a,(t,s,o)=>M(this,void 0,void 0,function*(){const a=new $(t,s,o,this,e),l=this._resolveArgs(a,this._filterParamsByKey(n,r)),u=yield e[n](...l);a.close(v(u)||i(u)?u:void 0)}))}this._logRouteNotFound(`${e.constructor.name}.${n}`)})}),this._baseRouter.use(j.path(e,"/"),t)})}init(){}error(e,t){s.error(e)}log(e,t){s.info(e)}_resolveArgs(e,t,s){const r=[],o={ctx:e,key:"",app:this,argument:s};return t.forEach(e=>{r[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),r}_buildMiddlewareChain(e,t,s,r){return s.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=_){const s=this._filterParamsByKey(t.method,r);return(r,o,n)=>M(this,void 0,void 0,function*(){const a=new $(r,o,n,this,e),l=E(t.argument)?t.argument(a):t.argument,u=yield t.callback.call(e,...this._resolveArgs(a,s,l));(v(u)||i(u))&&a.close(u)})}this._logRouteNotFound(t.method)}).filter(E)}_collectExtends(e){return j.extends(e).reduce((e,t)=>(e.push(t,...this._collectExtends(t)),e),[]).filter((e,t,s)=>s.indexOf(e)===t)}_filterParamsByKey(e,t){return t.filter(t=>t.propertyKey==e)}_collectMiddlewares(e){return[...j.middleware(e)].reverse()}_logRouteNotFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_formatListeningMessage(e){return`Server listening on port ${e}`}listen(){return M(this,void 0,void 0,function*(){var e;const t=this._resolveMode(),s={http:this._startHttp,https:this._startHttps,hybrid:this._startHybrid,redirect:this._startHttpsWithRedirect};yield(null!==(e=s[t])&&void 0!==e?e:this._startHttp).call(this)})}close(){return M(this,void 0,void 0,function*(){yield Promise.all(this._boundServers.map(e=>new Promise((t,s)=>{e.close(e=>e?s(e):t())}))),this._boundServers.length=0,this._server=void 0})}_resolveMode(){return this._resolveTls()?this._options.mode?this._options.mode:this._options.hybrid?"hybrid":"https":"http"}_resolveTls(){if(this._options.tls&&this._options.tls.key&&this._options.tls.cert)return this._options.tls}_bindServer(e,t,s){return new Promise((r,o)=>{const i=t=>{e.off("listening",n),o(t)},n=()=>{e.off("error",i),this.log(this._formatListeningMessage(t),"express"),r()};e.once("error",i),e.once("listening",n),e.listen(t,s)})}_startHttp(){return M(this,void 0,void 0,function*(){var e;const t=y.createServer(this._app);this._server=t,this._boundServers.push(t),yield this._bindServer(t,null!==(e=this._options.port)&&void 0!==e?e:3e3,this._options.host)})}_startHttps(){return M(this,void 0,void 0,function*(){var e;const t=D.createServer(this._resolveTls(),this._app);this._server=t,this._boundServers.push(t),yield this._bindServer(t,null!==(e=this._options.port)&&void 0!==e?e:443,this._options.host)})}_startHttpsWithRedirect(){return M(this,void 0,void 0,function*(){var e,t;const s=D.createServer(this._resolveTls(),this._app),r=y.createServer((e,t)=>{var s,r;const o=(null!==(s=e.headers.host)&&void 0!==s?s:"").split(":")[0];t.writeHead(F.MOVED_PERMANENTLY,{Location:`https://${o}${null!==(r=e.url)&&void 0!==r?r:""}`}),t.end()});this._server=s,this._boundServers.push(s,r),yield Promise.all([this._bindServer(s,null!==(e=this._options.port)&&void 0!==e?e:443,this._options.host),this._bindServer(r,null!==(t=this._options.redirectPort)&&void 0!==t?t:80,this._options.host)])})}_startHybrid(){return M(this,void 0,void 0,function*(){var e;const t=y.createServer(this._app),s=D.createServer(this._resolveTls(),this._app),r=C.createServer(e=>{const r=setTimeout(()=>e.destroy(),5e3);e.once("data",o=>{clearTimeout(r),e.pause(),e.unshift(o),(22===o[0]?s:t).emit("connection",e),process.nextTick(()=>e.resume())}),e.once("error",()=>clearTimeout(r))});return this._server=s,this._boundServers.push(r,s,t),yield this._bindServer(r,null!==(e=this._options.port)&&void 0!==e?e:443,this._options.host),s})}}const W=e=>t=>{j.path(t,(null==e?void 0:e.length)?e:"/")},z=e=>t=>{j.extends(t).push(e)},X=e=>t=>(s,r,o)=>{j.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},Z=X(({app:e})=>e),J=X(({argument:e})=>e),ee=X(({ctx:e,key:t})=>t?e.getBodyValue(t):e.getBody()),te=X(({ctx:e,key:t})=>t?e.getCookie(t):e.getCookies()),se=X(({ctx:e})=>e),re=X(({ctx:e})=>e.getFiles()),oe=X(({ctx:e,key:t})=>t?e.getHeader(t):e.getHeaders()),ie=X(({ctx:e,key:t})=>t?e.getParam(t):e.getParams()),ne=X(({ctx:e,key:t})=>t?e.getQuery(t):e.getQueries()),ae=X(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),le=(e,t)=>(s,r)=>{const o=n();se()(s,o,0),j.middleware(s).push({method:o,argument:t,propertyKey:r,callback:e})},ue=e=>(t,s,r)=>{le(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},de={ALL:"all",GET:"get",POST:"post",PUT:"put",HEAD:"head",DELETE:"delete",OPTIONS:"options",PATCH:"patch"},he=e=>t=>(s,r)=>{j.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},ce=he(de.ALL),pe=he(de.DELETE),Ee=he(de.GET),_e=he(de.HEAD),ve=he(de.OPTIONS),me=he(de.PATCH),Re=he(de.POST),Te=he(de.PUT),ge=(e,t)=>(s,r)=>{let i=_;if(o(r)){const t=s;E(t[e])&&(i=t[e])}j.middleware(s).push({method:e,argument:t,propertyKey:r,callback:i})},Ne=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},Oe=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},Se=(e,t)=>{const s=n()+"."+t;return I(L(e,s))?Se(e,t):s},fe=e=>{const t=p({},e),s=x({destination(e,s,r){var o;const i=Oe(t,s.fieldname);r(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,s,r){var o;const i=Oe(t,s.fieldname);r(null,Se(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",Ne(s.originalname)))}}),r=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),o=U({storage:s,fileFilter(e,s,r){var o;const i=Oe(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(Ne(e.originalname))||t.includes(e.mimetype.toLowerCase()))(s,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void r(null,!0):r(new Error(`FILE TYPE NOT ALLOWED FOR "${s.fieldname}"`)):r(new Error(`UPLOAD FIELD "${s.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*r*1024}}).fields(Object.keys(t).map(e=>{var s,r;return{name:e,maxCount:null!==(r=null===(s=t[e])||void 0===s?void 0:s.count)&&void 0!==r?r:1}}));return(e,t,s)=>{le(e=>{o(e.req,e.res,t=>{if(!t)return e.next();"LIMIT_UNEXPECTED_FILE"==t.code&&(t.message=`FIELD "${t.field}" EXCEEDS MAX SIZE`),e.destroy(t)})})(e,t,s)}},Ae=e=>{const t=m.object(E(e)?e(m):e).parse();return(e,s,r)=>{le(e=>M(void 0,void 0,void 0,function*(){var s,r;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(r=null===(s=e.req)||void 0===s?void 0:s.body)&&void 0!==r?r:{});if(o)return e.error(new Q(null!=i?i:o));e.req.body=n,e.next()}))(e,s,r)}};export{ce as All,Z as App,Y as Application,J as Argument,H as BadRequestError,ee as Body,ue as Cache,$ as Context,W as Controller,te as Cookies,se as Ctx,pe as Delete,z as Extends,re as Files,q as ForbiddenError,Ee as Get,_e as Head,oe as Headers,V as HttpResponse,B as InternalServerError,j as Metadata,de as Methods,ge as Middleware,K as NotFoundError,ve as Options,ie as Params,me as Patch,Re as Post,Te as Put,ne as Query,w as ResponseError,ae as Session,F as StatusCodes,k as StatusText,G as UnauthorizedError,fe as Upload,le as Use,Ae as Validate,Q as ValidationError,he as methodFactory,X as parameterFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrewcaires/express",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Decorators for express",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs.js",
@@ -38,35 +38,35 @@
38
38
  "homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
39
39
  "dependencies": {
40
40
  "@andrewcaires/decorator": "^1.1.1",
41
- "@andrewcaires/node": "^1.3.1",
42
- "@andrewcaires/utils.js": "^0.4.31",
41
+ "@andrewcaires/node": "^1.3.3",
42
+ "@andrewcaires/utils.js": "^0.4.34",
43
43
  "compression": "^1.8.1",
44
44
  "cookie-parser": "^1.4.7",
45
45
  "cors": "^2.8.6",
46
46
  "express": "^5.2.1",
47
47
  "express-session": "^1.19.0",
48
- "multer": "^2.0.2",
48
+ "multer": "^2.1.1",
49
49
  "request-ip": "^3.3.0"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@eslint/js": "^10.0.1",
53
- "@rollup/plugin-commonjs": "^29.0.0",
54
- "@rollup/plugin-terser": "^0.4.4",
53
+ "@rollup/plugin-commonjs": "^29.0.2",
54
+ "@rollup/plugin-terser": "^1.0.0",
55
55
  "@rollup/plugin-typescript": "^12.3.0",
56
- "@rollup/rollup-darwin-arm64": "^4.58.0",
56
+ "@rollup/rollup-darwin-arm64": "^4.60.2",
57
57
  "@types/compression": "^1.8.1",
58
58
  "@types/cookie-parser": "^1.4.10",
59
59
  "@types/cors": "^2.8.19",
60
60
  "@types/express": "^5.0.6",
61
- "@types/express-session": "^1.18.2",
62
- "@types/multer": "^2.0.0",
63
- "@types/node": "^25.3.0",
61
+ "@types/express-session": "^1.19.0",
62
+ "@types/multer": "^2.1.0",
63
+ "@types/node": "^25.6.0",
64
64
  "@types/request-ip": "^0.0.41",
65
65
  "@types/swagger-ui-express": "^4.1.8",
66
- "eslint": "^10.0.1",
67
- "rollup-plugin-dts": "^6.3.0",
66
+ "eslint": "^10.3.0",
67
+ "rollup-plugin-dts": "^6.4.1",
68
68
  "swagger-ui-express": "^5.0.1",
69
69
  "tslib": "^2.8.1",
70
- "typescript-eslint": "^8.56.0"
70
+ "typescript-eslint": "^8.59.1"
71
71
  }
72
72
  }