@andrewcaires/express 2.0.6 → 2.1.1
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 +2 -2
- package/dist/index.d.ts +127 -23
- package/dist/index.esm.js +2 -2
- package/package.json +7 -6
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/express v2.
|
|
2
|
+
* @andrewcaires/express v2.1.1
|
|
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"),r=require("@andrewcaires/utils.js"),s=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"),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(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var v=_(u),T=_(d);function O(e,t,r,s){return new(r||(r=Promise))(function(o,i){function n(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,a)}l((s=s.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 x extends Error{constructor(e,t=R.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class N extends x{constructor(e){super(e,R.UNPROCESSABLE_ENTITY)}}class A{constructor(e,t,r,s,o){this.req=e,this.res=t,this.next=r,this.app=s,this.controller=o}cache(e){const t=[];e.private?t.push("private"):e.public&&t.push("public"),e.noStore&&(e.noCache=!0,t.push("no-store")),e.noCache&&(e.maxAge=0,delete e.sMaxAge,t.push("no-cache")),e.noTransform&&t.push("no-transform"),e.proxyRevalidate&&t.push("proxy-revalidate"),e.mustRevalidate?t.push("must-revalidate"):e.noCache||(r.isNumber(e.staleIfError)&&t.push(`stale-if-error=${e.staleIfError}`),r.isNumber(e.staleWhileRevalidate)&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`)),r.isNumber(e.maxAge)&&t.push(`max-age=${e.maxAge}`),r.isNumber(e.sMaxAge)&&t.push(`s-maxage=${e.sMaxAge}`),t.length&&(this.res.setHeader("Cache-Control",t.join(",")),e.noCache&&r.forEachKey({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}close(e){this.res.headersSent||this.res.json(e||this.storage)}cookie(e,t,s){r.isUndefined(t)?this.res.clearCookie(e):this.res.cookie(e,t,null!=s?s:{})}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){var t;let r=null!==(t=e.toString())&&void 0!==t?t:"",s=R.INTERNAL_SERVER_ERROR;e instanceof Error&&(r=e.message,e instanceof x&&(s=e.status)),this.send(s,{error:r})}file(e){this.res.headersSent||(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,r,s;return null!==(s=null===(r=null===(t=this.req.cookies)||void 0===t?void 0:t[e])||void 0===r?void 0:r.toString())&&void 0!==s?s:""}getCookies(){var e;return null!==(e=this.req.cookies)&&void 0!==e?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,r,s;return null!==(s=null===(r=null===(t=this.req)||void 0===t?void 0:t.header(e))||void 0===r?void 0:r.toString())&&void 0!==s?s:""}getHeaders(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.headers)&&void 0!==t?t:{}}getIp(){return E.getClientIp(this.req)||"0.0.0.0"}getQuery(e){var t;return null===(t=this.req.query)||void 0===t?void 0:t[e]}getQueries(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.query)&&void 0!==t?t:{}}getParam(e){var t,r,s;return null!==(s=null===(r=null===(t=this.req.params)||void 0===t?void 0:t[e])||void 0===r?void 0:r.toString())&&void 0!==s?s:""}getParams(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.params)&&void 0!==t?t:{}}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}json(e){this.send(R.OK,e)}prepare(e,t){this.res.headersSent||(this.status(e),this.storage=t)}send(e,t){this.res.headersSent||(this.status(e),this.res.json(t))}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.send(R.OK,{message:e})}}class m{static extends(t){return e.metadata(m.EXTENDS,t,[])}static middleware(t){return e.metadata(m.MIDDLEWARE,t,[])}static parameters(t){return e.metadata(m.PARAMETERS,t,[])}static path(t,r){return e.metadata(m.PATH,t,r)}static routers(t){return e.metadata(m.ROUTERS,t,[])}}m.EXTENDS=Symbol("EXTENDS"),m.MIDDLEWARE=Symbol("MIDDLEWARE"),m.PARAMETERS=Symbol("PARAMETERS"),m.PATH=Symbol("PATH"),m.ROUTERS=Symbol("ROUTERS");class I extends r.EventEmitter{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(t,u){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=>r.isConstructor(t)?new t(...e.getInjectionArgs(t)):t)),this._options=r.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(r.isObject(this._options.cross)?this._options.cross:{})),this._app.use(s(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);l.existsSync(e)&&this._app.use(n.static(e)),this._app.get("*path",(t,r)=>{l.existsSync(e)?r.sendFile(e+"/index.html"):this._options.notfound?r.redirect(this._options.notfound):(r.status(R.NOT_FOUND),r.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(),s=this._middlewares(e),o=m.parameters(e);this._extends(e).forEach(e=>{s.push(...this._middlewares(e)),o.push(...m.parameters(e))}),m.routers(e).forEach(i=>{const n=i.propertyKey.toString();if(r.isFunction(e[n])){if(!r.isFunction(t[i.method]))return this._notFound(i.method);const a=this._handles(e,n,s,o);return t[i.method](i.path,...a,(t,s,i)=>O(this,void 0,void 0,function*(){const a=new A(t,s,i,this,e),l=this._args(a,this._indexes(n,o)),u=yield e[n](...l);a.close(r.isArray(u)||r.isObject(u)?u:void 0)}))}this._notFound(`${e.name}.${n}`)}),this._extends(e).forEach(i=>{m.routers(i).forEach(i=>{const n=i.propertyKey.toString();if(r.isFunction(e[n])){if(!r.isFunction(t[i.method]))return this._notFound(i.method);const a=this._handles(e,n,s,o);return t[i.method](i.path,...a,(t,s,i)=>O(this,void 0,void 0,function*(){const a=new A(t,s,i,this,e),l=this._args(a,this._indexes(n,o)),u=yield e[n](...l);a.close(r.isArray(u)||r.isObject(u)?u:void 0)}))}this._notFound(`${e.constructor.name}.${n}`)})}),this._base.use(m.path(e,"/"),t)})}init(){}error(e,r){t.Log.error(e)}log(e,r){t.Log.info(e)}_args(e,t,r){const s=[],o={ctx:e,key:"",app:this,argument:r};return t.forEach(e=>{s[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),s}_handles(e,t,s,o){return s.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=r.noop){const s=this._indexes(t.method,o);return(o,i,n)=>O(this,void 0,void 0,function*(){const a=new A(o,i,n,this,e),l=r.isFunction(t.argument)?t.argument(a):t.argument,u=yield t.callback.call(e,...this._args(a,s,l));(r.isArray(u)||r.isObject(u))&&a.close(u)})}this._notFound(t.method)}).filter(r.isFunction)}_extends(e){return m.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,r)=>r.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...m.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return O(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=v.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=v.createServer((e,t)=>{const r=80==this._options.port?":80":"";t.writeHead(R.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${r}${e.url}`}),t.end()}),t=T.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new p.Server(r=>{r.once("data",s=>{r.pause(),r.unshift(s),(22===s[0]?t:e).emit("connection",r),process.nextTick(()=>r.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 S=e=>t=>(r,s,o)=>{m.parameters(r).push({callback:e,key:t,propertyKey:s,parameterIndex:o})},g=S(({app:e})=>e),D=S(({argument:e})=>e),y=(e,t)=>r.isUndefined(t)?e:e[t],f=S(({ctx:e,key:t})=>{var r,s;return y(null!==(s=null===(r=e.req)||void 0===r?void 0:r.body)&&void 0!==s?s:{},t)}),L=S(({ctx:e,key:t})=>{var r,s;return y(null!==(s=null===(r=e.req)||void 0===r?void 0:r.cookies)&&void 0!==s?s:{},t)}),U=S(({ctx:e})=>e),C=S(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.files)&&void 0!==r?r:{}}),P=S(({ctx:e,key:t})=>{var r,s;return y(null!==(s=null===(r=e.req)||void 0===r?void 0:r.headers)&&void 0!==s?s:{},t)}),F=S(({ctx:e,key:t})=>{var r,s;return y(null!==(s=null===(r=e.req)||void 0===r?void 0:r.params)&&void 0!==s?s:{},t)}),b=S(({ctx:e,key:t})=>{var r,s,o;return String(null!==(o=y(null!==(s=null===(r=e.req)||void 0===r?void 0:r.query)&&void 0!==s?s:{},t))&&void 0!==o?o:"")}),q=S(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),M=(e,t)=>(s,o)=>{const i=r.uuidv7();U()(s,i,0),m.middleware(s).push({method:i,argument:t,propertyKey:o,callback:e})};var k;exports.Methods=void 0,(k=exports.Methods||(exports.Methods={})).ALL="all",k.GET="get",k.POST="post",k.PUT="put",k.HEAD="head",k.DELETE="delete",k.OPTIONS="options",k.PATCH="patch";const w=e=>t=>(r,s)=>{m.routers(r).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:s})},j=w(exports.Methods.ALL),H=w(exports.Methods.DELETE),V=w(exports.Methods.GET),$=w(exports.Methods.HEAD),G=w(exports.Methods.OPTIONS),Q=w(exports.Methods.PATCH),B=w(exports.Methods.POST),K=w(exports.Methods.PUT),Y=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},W=(e,t)=>{var r;return null!==(r=e[t])&&void 0!==r?r:null},X=(e,t)=>{const s=r.uuidv7()+"."+t;return l.existsSync(h.join(e,s))?X(e,t):s};exports.All=j,exports.App=g,exports.Application=I,exports.Argument=D,exports.BadRequestError=class extends x{constructor(e="Bad Request"){super(e,R.BAD_REQUEST)}},exports.Body=f,exports.Cache=e=>(t,r,s)=>{M(t=>{t.cache(Object.assign({},e)),t.next()})(t,r,s)},exports.Context=A,exports.Controller=e=>t=>{m.path(t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=L,exports.Ctx=U,exports.Delete=H,exports.Extends=e=>t=>{m.extends(t).push(e)},exports.Files=C,exports.ForbiddenError=class extends x{constructor(e="Forbidden"){super(e,R.FORBIDDEN)}},exports.Get=V,exports.Head=$,exports.Headers=P,exports.InternalServerError=class extends x{constructor(e="Internal server error"){super(e,R.INTERNAL_SERVER_ERROR)}},exports.Metadata=m,exports.Middleware=(e,t)=>(s,o)=>{let i=r.noop;if(r.isString(o)){const t=s;r.isFunction(t[e])&&(i=t[e])}m.middleware(s).push({method:e,argument:t,propertyKey:o,callback:i})},exports.NotFoundError=class extends x{constructor(e="Record not found"){super(e,R.NOT_FOUND)}},exports.Options=G,exports.Params=F,exports.Patch=Q,exports.Post=B,exports.Put=K,exports.Query=b,exports.ResponseError=x,exports.Session=q,exports.Status=R,exports.UnauthorizedError=class extends x{constructor(e="Unauthorized"){super(e,R.UNAUTHORIZED)}},exports.Upload=e=>{const t=r.merge({},e),s=c.diskStorage({destination(e,r,s){var o;const i=W(t,r.fieldname);s(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,r,s){var o;const i=W(t,r.fieldname);s(null,X(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",Y(r.originalname)))}}),o=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),i=c({storage:s,fileFilter(e,r,s){var o;const i=W(t,r.fieldname);return i?((e,t)=>!t.length||t.includes(Y(e.originalname))||t.includes(e.mimetype.toLowerCase()))(r,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void s(null,!0):s(new Error(`FILE TYPE NOT ALLOWED FOR "${r.fieldname}"`)):s(new Error(`UPLOAD FIELD "${r.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*o*1024}}).fields(Object.keys(t).map(e=>{var r,s;return{name:e,maxCount:null!==(s=null===(r=t[e])||void 0===r?void 0:r.count)&&void 0!==s?s:1}}));return(e,t,r)=>{M(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,r)}},exports.Use=M,exports.Validate=e=>{const t=r.Validation.object(r.isFunction(e)?e(r.Validation):e).parse();return(e,r,s)=>{M(e=>O(void 0,void 0,void 0,function*(){var r,s;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(s=null===(r=e.req)||void 0===r?void 0:r.body)&&void 0!==s?s:{});if(o)return e.error(new N(null!=i?i:o));e.req.body=n,e.next()}))(e,r,s)}},exports.ValidationError=N,exports.methodFactory=w,exports.parameterFactory=S;
|
|
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"),c=require("path"),h=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 R=_(l),v=_(d);function T(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 m{}m.CONTINUE=100,m.SWITCHING_PROTOCOLS=101,m.PROCESSING=102,m.OK=200,m.CREATED=201,m.ACCEPTED=202,m.NON_AUTHORITATIVE_INFORMATION=203,m.NO_CONTENT=204,m.RESET_CONTENT=205,m.PARTIAL_CONTENT=206,m.MULTI_STATUS=207,m.ALREADY_REPORTED=208,m.IM_USED=226,m.MULTIPLE_CHOICES=300,m.MOVED_PERMANENTLY=301,m.FOUND=302,m.SEE_OTHER=303,m.NOT_MODIFIED=304,m.USE_PROXY=305,m.TEMPORARY_REDIRECT=307,m.PERMANENT_REDIRECT=308,m.BAD_REQUEST=400,m.UNAUTHORIZED=401,m.PAYMENT_REQUIRED=402,m.FORBIDDEN=403,m.NOT_FOUND=404,m.METHOD_NOT_ALLOWED=405,m.NOT_ACCEPTABLE=406,m.PROXY_AUTHENTICATION_REQUIRED=407,m.REQUEST_TIMEOUT=408,m.CONFLICT=409,m.GONE=410,m.LENGTH_REQUIRED=411,m.PRECONDITION_FAILED=412,m.PAYLOAD_TOO_LARGE=413,m.REQUEST_URI_TOO_LONG=414,m.UNSUPPORTED_MEDIA_TYPE=415,m.REQUESTED_RANGE_NOT_SATISFIABLE=416,m.EXPECTATION_FAILED=417,m.IM_A_TEAPOT=418,m.MISDIRECTED_REQUEST=421,m.UNPROCESSABLE_ENTITY=422,m.LOCKED=423,m.FAILED_DEPENDENCY=424,m.UPGRADE_REQUIRED=426,m.PRECONDITION_REQUIRED=428,m.TOO_MANY_REQUESTS=429,m.REQUEST_HEADER_FIELDS_TOO_LARGE=431,m.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,m.UNAVAILABLE_FOR_LEGAL_REASONS=451,m.CLIENT_CLOSED_REQUEST=499,m.INTERNAL_SERVER_ERROR=500,m.NOT_IMPLEMENTED=501,m.BAD_GATEWAY=502,m.SERVICE_UNAVAILABLE=503,m.GATEWAY_TIMEOUT=504,m.HTTP_VERSION_NOT_SUPPORTED=505,m.VARIANT_ALSO_NEGOCIATES=506,m.INSUFFICIENT_STORAGE=507,m.LOOP_DETECTED=508,m.NOT_EXTENDED=510,m.NETWORK_AUTHENTICATION_REQUIRED=511,m.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 g extends Error{constructor(e,t=m.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class N extends g{constructor(e="Not Found"){super(e,m.NOT_FOUND)}}class S extends g{constructor(e){super(e,m.UNPROCESSABLE_ENTITY)}}class x{static created(e,t,s){var r,o;const i=m.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(m.NO_CONTENT).end()}static ok(e,t,s){var r,o;const i=m.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=m.INTERNAL_SERVER_ERROR,r=O[500];if(e instanceof g)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 m.INTERNAL_SERVER_ERROR;const t=Math.trunc(e);return t<400||t>599?m.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 A{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){this.isResponded()||x.error(this.req,this.res,e)}file(e){this.isResponded()||(this.status(m.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 h.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(m.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()||x.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(m.OK,{message:e})}}class I{static extends(t){return e.metadata(I.EXTENDS,t,[])}static middleware(t){return e.metadata(I.MIDDLEWARE,t,[])}static parameters(t){return e.metadata(I.PARAMETERS,t,[])}static path(t,s){return e.metadata(I.PATH,t,s)}static routers(t){return e.metadata(I.ROUTERS,t,[])}}I.EXTENDS=Symbol("EXTENDS"),I.MIDDLEWARE=Symbol("MIDDLEWARE"),I.PARAMETERS=Symbol("PARAMETERS"),I.PATH=Symbol("PATH"),I.ROUTERS=Symbol("ROUTERS");class f 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 h=(null===(p=this._options.path)||void 0===p?void 0:p.length)?this._options.path:"/";if(this._app.use(h,this._base),this._app.all(h+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):x.error(e,t,new N("Endpoint Not Found"))}),this._options.public){const e=c.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):x.error(t,s,new N('FILE "index.html" Not Found'))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):x.error(e,t,new N("Endpoint not found"))});this._controllers.forEach(e=>{const t=n.Router(),r=this._middlewares(e),o=I.parameters(e);this._extends(e).forEach(e=>{r.push(...this._middlewares(e)),o.push(...I.parameters(e))}),I.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)=>T(this,void 0,void 0,function*(){const a=new A(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=>{I.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)=>T(this,void 0,void 0,function*(){const a=new A(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(I.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)=>T(this,void 0,void 0,function*(){const a=new A(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 I.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[...I.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return T(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=R.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=R.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(m.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${s}${e.url}`}),t.end()}),t=v.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 y=e=>t=>(s,r,o)=>{I.parameters(s).push({callback:e,key:t,propertyKey:r,parameterIndex:o})},C=y(({app:e})=>e),D=y(({argument:e})=>e),U=y(({ctx:e,key:t})=>t?e.getBodyValue(t):e.getBody()),P=y(({ctx:e,key:t})=>t?e.getCookie(t):e.getCookies()),L=y(({ctx:e})=>e),b=y(({ctx:e})=>e.getFiles()),F=y(({ctx:e,key:t})=>t?e.getHeader(t):e.getHeaders()),q=y(({ctx:e,key:t})=>t?e.getParam(t):e.getParams()),M=y(({ctx:e,key:t})=>t?e.getQuery(t):e.getQueries()),k=y(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),w=(e,t)=>(r,o)=>{const i=s.uuidv7();L()(r,i,0),I.middleware(r).push({method:i,argument:t,propertyKey:o,callback:e})},H={ALL:"all",GET:"get",POST:"post",PUT:"put",HEAD:"head",DELETE:"delete",OPTIONS:"options",PATCH:"patch"},j=e=>t=>(s,r)=>{I.routers(s).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:r})},V=j(H.ALL),G=j(H.DELETE),B=j(H.GET),Q=j(H.HEAD),$=j(H.OPTIONS),K=j(H.PATCH),z=j(H.POST),Y=j(H.PUT),W=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},X=(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(c.join(e,r))?Z(e,t):r};exports.All=V,exports.App=C,exports.Application=f,exports.Argument=D,exports.BadRequestError=class extends g{constructor(e="Bad Request"){super(e,m.BAD_REQUEST)}},exports.Body=U,exports.Cache=e=>(t,s,r)=>{w(t=>{t.cache(Object.assign({},e)),t.next()})(t,s,r)},exports.Context=A,exports.Controller=e=>t=>{I.path(t,(null==e?void 0:e.length)?e:"/")},exports.Cookies=P,exports.Ctx=L,exports.Delete=G,exports.Extends=e=>t=>{I.extends(t).push(e)},exports.Files=b,exports.ForbiddenError=class extends g{constructor(e="Forbidden"){super(e,m.FORBIDDEN)}},exports.Get=B,exports.Head=Q,exports.Headers=F,exports.HttpResponse=x,exports.InternalServerError=class extends g{constructor(e="Internal server error"){super(e,m.INTERNAL_SERVER_ERROR)}},exports.Metadata=I,exports.Methods=H,exports.Middleware=(e,t)=>(r,o)=>{let i=s.noop;if(s.isString(o)){const t=r;s.isFunction(t[e])&&(i=t[e])}I.middleware(r).push({method:e,argument:t,propertyKey:o,callback:i})},exports.NotFoundError=N,exports.Options=$,exports.Params=q,exports.Patch=K,exports.Post=z,exports.Put=Y,exports.Query=M,exports.ResponseError=g,exports.Session=k,exports.StatusCodes=m,exports.StatusText=O,exports.UnauthorizedError=class extends g{constructor(e="Unauthorized"){super(e,m.UNAUTHORIZED)}},exports.Upload=e=>{const t=s.merge({},e),r=E.diskStorage({destination(e,s,r){var o;const i=X(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=X(t,s.fieldname);r(null,Z(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",W(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=X(t,s.fieldname);return i?((e,t)=>!t.length||t.includes(W(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)=>{w(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=w,exports.Validate=e=>{const t=s.Validation.object(s.isFunction(e)?e(s.Validation):e).parse();return(e,s,r)=>{w(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 S(null!=i?i:o));e.req.body=n,e.next()}))(e,s,r)}},exports.ValidationError=S,exports.methodFactory=j,exports.parameterFactory=y;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/express v2.
|
|
2
|
+
* @andrewcaires/express v2.1.1
|
|
3
3
|
* Decorators for express
|
|
4
4
|
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
@@ -20,30 +20,34 @@ declare class Context<T = any, A = Application> {
|
|
|
20
20
|
readonly next: NextFunction;
|
|
21
21
|
readonly app: A;
|
|
22
22
|
readonly controller: T;
|
|
23
|
-
private storage
|
|
23
|
+
private storage;
|
|
24
24
|
constructor(req: Request, res: Response, next: NextFunction, app: A, controller: T);
|
|
25
25
|
cache(options: ICache): void;
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
clearCookie(key: string, options?: CookieOptions): void;
|
|
27
|
+
close(value?: TypeAnyObject | Array<TypeAnyObject>): void;
|
|
28
28
|
destroy(error?: Error): void;
|
|
29
29
|
error(error: string | Error): void;
|
|
30
30
|
file(path: string): void;
|
|
31
31
|
getBody<T = TypeAnyObject>(): T;
|
|
32
32
|
getBodyValue<T = any>(key: string): T | undefined;
|
|
33
|
-
getCookie(key: string): string;
|
|
33
|
+
getCookie(key: string): string | undefined;
|
|
34
34
|
getCookies<T = TypeAnyObject>(): T;
|
|
35
35
|
getFiles<F = IFile, T = TypeObject<Array<F>>>(): T;
|
|
36
|
-
getHeader(key: string): string;
|
|
36
|
+
getHeader(key: string): string | undefined;
|
|
37
37
|
getHeaders<T = TypeAnyObject>(): T;
|
|
38
38
|
getIp(): string;
|
|
39
|
-
getQuery
|
|
39
|
+
getQuery(key: string): string | undefined;
|
|
40
40
|
getQueries<T = TypeAnyObject>(): T;
|
|
41
|
-
getParam(key: string): string;
|
|
41
|
+
getParam(key: string): string | undefined;
|
|
42
42
|
getParams<T = TypeAnyObject>(): T;
|
|
43
43
|
getUrl(): string;
|
|
44
|
+
isResponded(): boolean;
|
|
44
45
|
json(value?: TypeAnyObject | Array<TypeAnyObject>): void;
|
|
46
|
+
private normalize;
|
|
47
|
+
ok<T = any>(data: T, meta?: TypeAnyObject): void;
|
|
45
48
|
prepare(status: number, value: TypeAnyObject | Array<TypeAnyObject>): void;
|
|
46
49
|
send(status: number, value?: TypeAnyObject | Array<TypeAnyObject>): void;
|
|
50
|
+
setCookie(key: string, value: string, options?: CookieOptions): void;
|
|
47
51
|
status(value?: number): number;
|
|
48
52
|
success(message: string): void;
|
|
49
53
|
}
|
|
@@ -116,19 +120,21 @@ interface IParameter {
|
|
|
116
120
|
parameterIndex: number;
|
|
117
121
|
}
|
|
118
122
|
|
|
119
|
-
declare
|
|
120
|
-
ALL
|
|
121
|
-
GET
|
|
122
|
-
POST
|
|
123
|
-
PUT
|
|
124
|
-
HEAD
|
|
125
|
-
DELETE
|
|
126
|
-
OPTIONS
|
|
127
|
-
PATCH
|
|
128
|
-
}
|
|
123
|
+
declare const Methods: {
|
|
124
|
+
readonly ALL: "all";
|
|
125
|
+
readonly GET: "get";
|
|
126
|
+
readonly POST: "post";
|
|
127
|
+
readonly PUT: "put";
|
|
128
|
+
readonly HEAD: "head";
|
|
129
|
+
readonly DELETE: "delete";
|
|
130
|
+
readonly OPTIONS: "options";
|
|
131
|
+
readonly PATCH: "patch";
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
type Method = typeof Methods[keyof typeof Methods];
|
|
129
135
|
|
|
130
136
|
interface IRouter {
|
|
131
|
-
method:
|
|
137
|
+
method: Method;
|
|
132
138
|
path: string;
|
|
133
139
|
propertyKey: string | symbol;
|
|
134
140
|
}
|
|
@@ -402,6 +408,34 @@ interface OpenAPIObject {
|
|
|
402
408
|
|
|
403
409
|
type ParseFunction = (_$: typeof Validation) => TypeObject<ValidationBase>;
|
|
404
410
|
|
|
411
|
+
interface HttpResponseBase<T> {
|
|
412
|
+
success: true;
|
|
413
|
+
status: number;
|
|
414
|
+
data: T;
|
|
415
|
+
meta?: TypeAnyObject;
|
|
416
|
+
message?: string | null;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
interface HttpResponseCreated extends HttpResponseBase<{
|
|
420
|
+
id?: string | number;
|
|
421
|
+
}> {
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
interface HttpResponseError {
|
|
425
|
+
success: false;
|
|
426
|
+
status: number;
|
|
427
|
+
error: string;
|
|
428
|
+
message: string;
|
|
429
|
+
path?: string;
|
|
430
|
+
timestamp?: string;
|
|
431
|
+
stack?: string;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
interface HttpResponseOptions {
|
|
435
|
+
message?: string | null;
|
|
436
|
+
meta?: TypeAnyObject;
|
|
437
|
+
}
|
|
438
|
+
|
|
405
439
|
declare class Application<T extends TypeAnyObject = TypeAnyObject> extends EventEmitter<T> {
|
|
406
440
|
private readonly _app;
|
|
407
441
|
private _server?;
|
|
@@ -441,7 +475,7 @@ declare const Get: (path?: string) => MethodDecorator;
|
|
|
441
475
|
|
|
442
476
|
declare const Head: (path?: string) => MethodDecorator;
|
|
443
477
|
|
|
444
|
-
declare const methodFactory: (method:
|
|
478
|
+
declare const methodFactory: (method: Method) => (path?: string) => MethodDecorator;
|
|
445
479
|
|
|
446
480
|
declare const Options: (path?: string) => MethodDecorator;
|
|
447
481
|
|
|
@@ -510,6 +544,17 @@ declare class ValidationError extends ResponseError {
|
|
|
510
544
|
constructor(message: string);
|
|
511
545
|
}
|
|
512
546
|
|
|
547
|
+
declare class HttpResponse {
|
|
548
|
+
static created(res: Response, id?: string | number, options?: HttpResponseOptions): HttpResponseCreated;
|
|
549
|
+
static noContent(res: Response): void;
|
|
550
|
+
static ok<T = TypeAnyObject | Array<TypeAnyObject>>(res: Response, data: T, options?: HttpResponseOptions): HttpResponseBase<T>;
|
|
551
|
+
static error(req: Request, res: Response, error: unknown): HttpResponseError;
|
|
552
|
+
private static isDev;
|
|
553
|
+
private static normalizeError;
|
|
554
|
+
private static safeStatus;
|
|
555
|
+
private static safeMessage;
|
|
556
|
+
}
|
|
557
|
+
|
|
513
558
|
declare class Metadata {
|
|
514
559
|
static readonly EXTENDS: unique symbol;
|
|
515
560
|
static readonly MIDDLEWARE: unique symbol;
|
|
@@ -523,7 +568,7 @@ declare class Metadata {
|
|
|
523
568
|
static routers(target: any): Array<IRouter>;
|
|
524
569
|
}
|
|
525
570
|
|
|
526
|
-
declare class
|
|
571
|
+
declare class StatusCodes {
|
|
527
572
|
static readonly CONTINUE = 100;
|
|
528
573
|
static readonly SWITCHING_PROTOCOLS = 101;
|
|
529
574
|
static readonly PROCESSING = 102;
|
|
@@ -589,5 +634,64 @@ declare class Status {
|
|
|
589
634
|
static readonly NETWORK_CONNECTION_TIMEOUT_ERROR = 599;
|
|
590
635
|
}
|
|
591
636
|
|
|
592
|
-
|
|
593
|
-
|
|
637
|
+
declare class StatusText {
|
|
638
|
+
static readonly 100 = "Continue";
|
|
639
|
+
static readonly 101 = "Switching Protocols";
|
|
640
|
+
static readonly 102 = "Processing";
|
|
641
|
+
static readonly 200 = "OK";
|
|
642
|
+
static readonly 201 = "Created";
|
|
643
|
+
static readonly 202 = "Accepted";
|
|
644
|
+
static readonly 203 = "Non-Authoritative Information";
|
|
645
|
+
static readonly 204 = "No Content";
|
|
646
|
+
static readonly 205 = "Reset Content";
|
|
647
|
+
static readonly 206 = "Partial Content";
|
|
648
|
+
static readonly 207 = "Multi-Status";
|
|
649
|
+
static readonly 226 = "IM Used";
|
|
650
|
+
static readonly 300 = "Multiple Choices";
|
|
651
|
+
static readonly 301 = "Moved Permanently";
|
|
652
|
+
static readonly 302 = "Found";
|
|
653
|
+
static readonly 303 = "See Other";
|
|
654
|
+
static readonly 304 = "Not Modified";
|
|
655
|
+
static readonly 305 = "Use Proxy";
|
|
656
|
+
static readonly 307 = "Temporary Redirect";
|
|
657
|
+
static readonly 308 = "Permanent Redirect";
|
|
658
|
+
static readonly 400 = "Bad Request";
|
|
659
|
+
static readonly 401 = "Unauthorized";
|
|
660
|
+
static readonly 402 = "Payment Required";
|
|
661
|
+
static readonly 403 = "Forbidden";
|
|
662
|
+
static readonly 404 = "Not Found";
|
|
663
|
+
static readonly 405 = "Method Not Allowed";
|
|
664
|
+
static readonly 406 = "Not Acceptable";
|
|
665
|
+
static readonly 407 = "Proxy Authentication Required";
|
|
666
|
+
static readonly 408 = "Request Timeout";
|
|
667
|
+
static readonly 409 = "Conflict";
|
|
668
|
+
static readonly 410 = "Gone";
|
|
669
|
+
static readonly 411 = "Length Required";
|
|
670
|
+
static readonly 412 = "Precondition Failed";
|
|
671
|
+
static readonly 413 = "Payload Too Large";
|
|
672
|
+
static readonly 414 = "URI Too Long";
|
|
673
|
+
static readonly 415 = "Unsupported Media Type";
|
|
674
|
+
static readonly 416 = "Range Not Satisfiable";
|
|
675
|
+
static readonly 417 = "Expectation Failed";
|
|
676
|
+
static readonly 418 = "I'm a teapot";
|
|
677
|
+
static readonly 422 = "Unprocessable Entity";
|
|
678
|
+
static readonly 423 = "Locked";
|
|
679
|
+
static readonly 424 = "Failed Dependency";
|
|
680
|
+
static readonly 426 = "Upgrade Required";
|
|
681
|
+
static readonly 428 = "Precondition Required";
|
|
682
|
+
static readonly 429 = "Too Many Requests";
|
|
683
|
+
static readonly 431 = "Request Header Fields Too Large";
|
|
684
|
+
static readonly 451 = "Unavailable For Legal Reasons";
|
|
685
|
+
static readonly 500 = "Internal Server Error";
|
|
686
|
+
static readonly 501 = "Not Implemented";
|
|
687
|
+
static readonly 502 = "Bad Gateway";
|
|
688
|
+
static readonly 503 = "Service Unavailable";
|
|
689
|
+
static readonly 504 = "Gateway Time-out";
|
|
690
|
+
static readonly 505 = "HTTP Version Not Supported";
|
|
691
|
+
static readonly 506 = "Variant Also Negotiates";
|
|
692
|
+
static readonly 507 = "Insufficient Storage";
|
|
693
|
+
static readonly 511 = "Network Authentication Required";
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
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 };
|
|
697
|
+
export type { CallbackObject, ComponentsObject, ContactObject, EncodingObject, ExampleObject, ExternalDocumentationObject, HeaderObject, HttpResponseBase, HttpResponseCreated, HttpResponseError, HttpResponseOptions, 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 };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/express v2.
|
|
2
|
+
* @andrewcaires/express v2.1.1
|
|
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 r}from"@andrewcaires/node";import{isNumber as s,forEachKey as o,isUndefined as i,EventEmitter as n,isConstructor as a,merge as l,isObject as u,isFunction as h,noop as d,isArray as E,uuidv7 as p,isString as c,Validation as _}from"@andrewcaires/utils.js";import v from"compression";import T from"cookie-parser";import O from"cors";import R,{Router as m,json as N,urlencoded as A}from"express";import I from"express-session";import{existsSync as S}from"fs";import*as D from"http";import*as f from"https";import{Server as g}from"net";import{resolve as y,join as x}from"path";import{getClientIp as L}from"request-ip";import U,{diskStorage as C}from"multer";function P(e,t,r,s){return new(r||(r=Promise))(function(o,i){function n(e){try{l(s.next(e))}catch(e){i(e)}}function a(e){try{l(s.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,a)}l((s=s.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 b extends Error{constructor(e,t=F.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class M extends b{constructor(e="Bad Request"){super(e,F.BAD_REQUEST)}}class k extends b{constructor(e="Forbidden"){super(e,F.FORBIDDEN)}}class q extends b{constructor(e="Internal server error"){super(e,F.INTERNAL_SERVER_ERROR)}}class w extends b{constructor(e="Record not found"){super(e,F.NOT_FOUND)}}class H extends b{constructor(e="Unauthorized"){super(e,F.UNAUTHORIZED)}}class $ extends b{constructor(e){super(e,F.UNPROCESSABLE_ENTITY)}}class G{constructor(e,t,r,s,o){this.req=e,this.res=t,this.next=r,this.app=s,this.controller=o}cache(e){const t=[];e.private?t.push("private"):e.public&&t.push("public"),e.noStore&&(e.noCache=!0,t.push("no-store")),e.noCache&&(e.maxAge=0,delete e.sMaxAge,t.push("no-cache")),e.noTransform&&t.push("no-transform"),e.proxyRevalidate&&t.push("proxy-revalidate"),e.mustRevalidate?t.push("must-revalidate"):e.noCache||(s(e.staleIfError)&&t.push(`stale-if-error=${e.staleIfError}`),s(e.staleWhileRevalidate)&&t.push(`stale-while-revalidate=${e.staleWhileRevalidate}`)),s(e.maxAge)&&t.push(`max-age=${e.maxAge}`),s(e.sMaxAge)&&t.push(`s-maxage=${e.sMaxAge}`),t.length&&(this.res.setHeader("Cache-Control",t.join(",")),e.noCache&&o({"Surrogate-Control":"no-store",Pragma:"no-cache",ETag:"false",Expires:"0"},(e,t)=>this.res.setHeader(t,e)))}close(e){this.res.headersSent||this.res.json(e||this.storage)}cookie(e,t,r){i(t)?this.res.clearCookie(e):this.res.cookie(e,t,null!=r?r:{})}destroy(e){var t;e&&this.error(e),null===(t=this.res.socket)||void 0===t||t.destroy(e)}error(e){var t;let r=null!==(t=e.toString())&&void 0!==t?t:"",s=F.INTERNAL_SERVER_ERROR;e instanceof Error&&(r=e.message,e instanceof b&&(s=e.status)),this.send(s,{error:r})}file(e){this.res.headersSent||(this.status(F.OK),this.res.sendFile(y(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,r,s;return null!==(s=null===(r=null===(t=this.req.cookies)||void 0===t?void 0:t[e])||void 0===r?void 0:r.toString())&&void 0!==s?s:""}getCookies(){var e;return null!==(e=this.req.cookies)&&void 0!==e?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,r,s;return null!==(s=null===(r=null===(t=this.req)||void 0===t?void 0:t.header(e))||void 0===r?void 0:r.toString())&&void 0!==s?s:""}getHeaders(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.headers)&&void 0!==t?t:{}}getIp(){return L(this.req)||"0.0.0.0"}getQuery(e){var t;return null===(t=this.req.query)||void 0===t?void 0:t[e]}getQueries(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.query)&&void 0!==t?t:{}}getParam(e){var t,r,s;return null!==(s=null===(r=null===(t=this.req.params)||void 0===t?void 0:t[e])||void 0===r?void 0:r.toString())&&void 0!==s?s:""}getParams(){var e,t;return null!==(t=null===(e=this.req)||void 0===e?void 0:e.params)&&void 0!==t?t:{}}getUrl(){return`${this.req.protocol}://${this.req.get("host")}${this.req.originalUrl}`}json(e){this.send(F.OK,e)}prepare(e,t){this.res.headersSent||(this.status(e),this.storage=t)}send(e,t){this.res.headersSent||(this.status(e),this.res.json(t))}status(e){return e&&this.res.status(e),this.res.statusCode}success(e){this.send(F.OK,{message:e})}}class Q{static extends(t){return e(Q.EXTENDS,t,[])}static middleware(t){return e(Q.MIDDLEWARE,t,[])}static parameters(t){return e(Q.PARAMETERS,t,[])}static path(t,r){return e(Q.PATH,t,r)}static routers(t){return e(Q.ROUTERS,t,[])}}Q.EXTENDS=Symbol("EXTENDS"),Q.MIDDLEWARE=Symbol("MIDDLEWARE"),Q.PARAMETERS=Symbol("PARAMETERS"),Q.PATH=Symbol("PATH"),Q.ROUTERS=Symbol("ROUTERS");class Y extends n{get controllers(){return this._controllers}get instance(){return this._app}get router(){return this._router}get server(){return this._server}constructor(e,r){var s,o;super(),this._app=R(),this._options={},this._base=m(),this._router=m(),this._controllers=[],this._controllers.push(...e.map(e=>a(e)?new e(...t(e)):e)),this._options=l({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=r?r:{}),this._app.use(N(this._options.json)),this._app.disable("x-powered-by"),this._app.use(A({extended:!0})),this._options.cross&&this._app.use(O(u(this._options.cross)?this._options.cross:{})),this._app.use(v(this._options.compression)),this._app.use(T(null===(s=this._options.cookie)||void 0===s?void 0:s.secret,this._options.cookie)),this._app.use(I(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(F.NOT_FOUND),t.json({message:"INVALID API"}))}),this._options.public){const e=y(this._options.public);S(e)&&this._app.use(R.static(e)),this._app.get("*path",(t,r)=>{S(e)?r.sendFile(e+"/index.html"):this._options.notfound?r.redirect(this._options.notfound):(r.status(F.NOT_FOUND),r.json({message:'FILE "index.html" NOT FOUND'}))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):(t.status(F.NOT_FOUND),t.json({message:"INVALID API"}))});this._controllers.forEach(e=>{const t=m(),r=this._middlewares(e),s=Q.parameters(e);this._extends(e).forEach(e=>{r.push(...this._middlewares(e)),s.push(...Q.parameters(e))}),Q.routers(e).forEach(o=>{const i=o.propertyKey.toString();if(h(e[i])){if(!h(t[o.method]))return this._notFound(o.method);const n=this._handles(e,i,r,s);return t[o.method](o.path,...n,(t,r,o)=>P(this,void 0,void 0,function*(){const n=new G(t,r,o,this,e),a=this._args(n,this._indexes(i,s)),l=yield e[i](...a);n.close(E(l)||u(l)?l:void 0)}))}this._notFound(`${e.name}.${i}`)}),this._extends(e).forEach(o=>{Q.routers(o).forEach(o=>{const i=o.propertyKey.toString();if(h(e[i])){if(!h(t[o.method]))return this._notFound(o.method);const n=this._handles(e,i,r,s);return t[o.method](o.path,...n,(t,r,o)=>P(this,void 0,void 0,function*(){const n=new G(t,r,o,this,e),a=this._args(n,this._indexes(i,s)),l=yield e[i](...a);n.close(E(l)||u(l)?l:void 0)}))}this._notFound(`${e.constructor.name}.${i}`)})}),this._base.use(Q.path(e,"/"),t)})}init(){}error(e,t){r.error(e)}log(e,t){r.info(e)}_args(e,t,r){const s=[],o={ctx:e,key:"",app:this,argument:r};return t.forEach(e=>{s[e.parameterIndex]=e.callback(Object.assign(Object.assign({},o),{key:e.key}))}),s}_handles(e,t,r,s){return r.filter(e=>e.propertyKey==t).map(t=>{if(t.callback!=d){const r=this._indexes(t.method,s);return(s,o,i)=>P(this,void 0,void 0,function*(){const n=new G(s,o,i,this,e),a=h(t.argument)?t.argument(n):t.argument,l=yield t.callback.call(e,...this._args(n,r,a));(E(l)||u(l))&&n.close(l)})}this._notFound(t.method)}).filter(h)}_extends(e){return Q.extends(e).reduce((e,t)=>(e.push(t,...this._extends(t)),e),[]).filter((e,t,r)=>r.indexOf(e)===t)}_indexes(e,t){return t.filter(t=>t.propertyKey==e)}_middlewares(e){return[...Q.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return P(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=D.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=D.createServer((e,t)=>{const r=80==this._options.port?":80":"";t.writeHead(F.MOVED_PERMANENTLY,{Location:`https://${e.headers.host}${r}${e.url}`}),t.end()}),t=f.createServer({key:this._options.key,cert:this._options.cert},this._app);if(this._options.hybrid){new g(r=>{r.once("data",s=>{r.pause(),r.unshift(s),(22===s[0]?t:e).emit("connection",r),process.nextTick(()=>r.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 j=e=>t=>{Q.path(t,(null==e?void 0:e.length)?e:"/")},K=e=>t=>{Q.extends(t).push(e)},V=e=>t=>(r,s,o)=>{Q.parameters(r).push({callback:e,key:t,propertyKey:s,parameterIndex:o})},B=V(({app:e})=>e),W=V(({argument:e})=>e),X=(e,t)=>i(t)?e:e[t],z=V(({ctx:e,key:t})=>{var r,s;return X(null!==(s=null===(r=e.req)||void 0===r?void 0:r.body)&&void 0!==s?s:{},t)}),Z=V(({ctx:e,key:t})=>{var r,s;return X(null!==(s=null===(r=e.req)||void 0===r?void 0:r.cookies)&&void 0!==s?s:{},t)}),J=V(({ctx:e})=>e),ee=V(({ctx:e})=>{var t,r;return null!==(r=null===(t=e.req)||void 0===t?void 0:t.files)&&void 0!==r?r:{}}),te=V(({ctx:e,key:t})=>{var r,s;return X(null!==(s=null===(r=e.req)||void 0===r?void 0:r.headers)&&void 0!==s?s:{},t)}),re=V(({ctx:e,key:t})=>{var r,s;return X(null!==(s=null===(r=e.req)||void 0===r?void 0:r.params)&&void 0!==s?s:{},t)}),se=V(({ctx:e,key:t})=>{var r,s,o;return String(null!==(o=X(null!==(s=null===(r=e.req)||void 0===r?void 0:r.query)&&void 0!==s?s:{},t))&&void 0!==o?o:"")}),oe=V(({ctx:e})=>{var t;return null===(t=e.req)||void 0===t?void 0:t.session}),ie=(e,t)=>(r,s)=>{const o=p();J()(r,o,0),Q.middleware(r).push({method:o,argument:t,propertyKey:s,callback:e})},ne=e=>(t,r,s)=>{ie(t=>{t.cache(Object.assign({},e)),t.next()})(t,r,s)};var ae;!function(e){e.ALL="all",e.GET="get",e.POST="post",e.PUT="put",e.HEAD="head",e.DELETE="delete",e.OPTIONS="options",e.PATCH="patch"}(ae||(ae={}));const le=e=>t=>(r,s)=>{Q.routers(r).push({method:e,path:(null==t?void 0:t.length)?t:"/",propertyKey:s})},ue=le(ae.ALL),he=le(ae.DELETE),de=le(ae.GET),Ee=le(ae.HEAD),pe=le(ae.OPTIONS),ce=le(ae.PATCH),_e=le(ae.POST),ve=le(ae.PUT),Te=(e,t)=>(r,s)=>{let o=d;if(c(s)){const t=r;h(t[e])&&(o=t[e])}Q.middleware(r).push({method:e,argument:t,propertyKey:s,callback:o})},Oe=e=>{var t;return(null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"bin"},Re=(e,t)=>{var r;return null!==(r=e[t])&&void 0!==r?r:null},me=(e,t)=>{const r=p()+"."+t;return S(x(e,r))?me(e,t):r},Ne=e=>{const t=l({},e),r=C({destination(e,r,s){var o;const i=Re(t,r.fieldname);s(null,null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./")},filename(e,r,s){var o;const i=Re(t,r.fieldname);s(null,me(null!==(o=null==i?void 0:i.path)&&void 0!==o?o:"./",Oe(r.originalname)))}}),s=Math.max(...Object.values(t).map(e=>{var t;return null!==(t=e.size)&&void 0!==t?t:0})),o=U({storage:r,fileFilter(e,r,s){var o;const i=Re(t,r.fieldname);return i?((e,t)=>!t.length||t.includes(Oe(e.originalname))||t.includes(e.mimetype.toLowerCase()))(r,null!==(o=null==i?void 0:i.types)&&void 0!==o?o:[])?void s(null,!0):s(new Error(`FILE TYPE NOT ALLOWED FOR "${r.fieldname}"`)):s(new Error(`UPLOAD FIELD "${r.fieldname}" IS NOT CONFIGURED`))},limits:{fileSize:1024*s*1024}}).fields(Object.keys(t).map(e=>{var r,s;return{name:e,maxCount:null!==(s=null===(r=t[e])||void 0===r?void 0:r.count)&&void 0!==s?s:1}}));return(e,t,r)=>{ie(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,r)}},Ae=e=>{const t=_.object(h(e)?e(_):e).parse();return(e,r,s)=>{ie(e=>P(void 0,void 0,void 0,function*(){var r,s;const{error:o,message:i,value:n}=yield t.validateAsync(null!==(s=null===(r=e.req)||void 0===r?void 0:r.body)&&void 0!==s?s:{});if(o)return e.error(new $(null!=i?i:o));e.req.body=n,e.next()}))(e,r,s)}};export{ue as All,B as App,Y as Application,W as Argument,M as BadRequestError,z as Body,ne as Cache,G as Context,j as Controller,Z as Cookies,J as Ctx,he as Delete,K as Extends,ee as Files,k as ForbiddenError,de as Get,Ee as Head,te as Headers,q as InternalServerError,Q as Metadata,ae as Methods,Te as Middleware,w as NotFoundError,pe as Options,re as Params,ce as Patch,_e as Post,ve as Put,se as Query,b as ResponseError,oe as Session,F as Status,H as UnauthorizedError,Ne as Upload,ie as Use,Ae as Validate,$ as ValidationError,le as methodFactory,V 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,forEachKey as n,map as a,isUndefined as l,isNull as u,EventEmitter as d,isConstructor as h,merge as c,isFunction as p,noop as E,isArray as _,uuidv7 as m,Validation as R}from"@andrewcaires/utils.js";import T from"compression";import v from"cookie-parser";import O from"cors";import N,{Router as g,json as A,urlencoded as f}from"express";import I from"express-session";import{existsSync as S}from"fs";import*as D from"http";import*as y from"https";import{Server as C}from"net";import{resolve as L,join as x}from"path";import{getClientIp as P}from"request-ip";import U,{diskStorage as M}from"multer";function F(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 b{}b.CONTINUE=100,b.SWITCHING_PROTOCOLS=101,b.PROCESSING=102,b.OK=200,b.CREATED=201,b.ACCEPTED=202,b.NON_AUTHORITATIVE_INFORMATION=203,b.NO_CONTENT=204,b.RESET_CONTENT=205,b.PARTIAL_CONTENT=206,b.MULTI_STATUS=207,b.ALREADY_REPORTED=208,b.IM_USED=226,b.MULTIPLE_CHOICES=300,b.MOVED_PERMANENTLY=301,b.FOUND=302,b.SEE_OTHER=303,b.NOT_MODIFIED=304,b.USE_PROXY=305,b.TEMPORARY_REDIRECT=307,b.PERMANENT_REDIRECT=308,b.BAD_REQUEST=400,b.UNAUTHORIZED=401,b.PAYMENT_REQUIRED=402,b.FORBIDDEN=403,b.NOT_FOUND=404,b.METHOD_NOT_ALLOWED=405,b.NOT_ACCEPTABLE=406,b.PROXY_AUTHENTICATION_REQUIRED=407,b.REQUEST_TIMEOUT=408,b.CONFLICT=409,b.GONE=410,b.LENGTH_REQUIRED=411,b.PRECONDITION_FAILED=412,b.PAYLOAD_TOO_LARGE=413,b.REQUEST_URI_TOO_LONG=414,b.UNSUPPORTED_MEDIA_TYPE=415,b.REQUESTED_RANGE_NOT_SATISFIABLE=416,b.EXPECTATION_FAILED=417,b.IM_A_TEAPOT=418,b.MISDIRECTED_REQUEST=421,b.UNPROCESSABLE_ENTITY=422,b.LOCKED=423,b.FAILED_DEPENDENCY=424,b.UPGRADE_REQUIRED=426,b.PRECONDITION_REQUIRED=428,b.TOO_MANY_REQUESTS=429,b.REQUEST_HEADER_FIELDS_TOO_LARGE=431,b.CONNECTION_CLOSED_WITHOUT_RESPONSE=444,b.UNAVAILABLE_FOR_LEGAL_REASONS=451,b.CLIENT_CLOSED_REQUEST=499,b.INTERNAL_SERVER_ERROR=500,b.NOT_IMPLEMENTED=501,b.BAD_GATEWAY=502,b.SERVICE_UNAVAILABLE=503,b.GATEWAY_TIMEOUT=504,b.HTTP_VERSION_NOT_SUPPORTED=505,b.VARIANT_ALSO_NEGOCIATES=506,b.INSUFFICIENT_STORAGE=507,b.LOOP_DETECTED=508,b.NOT_EXTENDED=510,b.NETWORK_AUTHENTICATION_REQUIRED=511,b.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=b.INTERNAL_SERVER_ERROR){super(e),this.status=t}}class q extends w{constructor(e="Bad Request"){super(e,b.BAD_REQUEST)}}class H extends w{constructor(e="Forbidden"){super(e,b.FORBIDDEN)}}class G extends w{constructor(e="Internal server error"){super(e,b.INTERNAL_SERVER_ERROR)}}class Q extends w{constructor(e="Not Found"){super(e,b.NOT_FOUND)}}class V extends w{constructor(e="Unauthorized"){super(e,b.UNAUTHORIZED)}}class $ extends w{constructor(e){super(e,b.UNPROCESSABLE_ENTITY)}}class B{static created(e,t,s){var r,o;const i=b.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(b.NO_CONTENT).end()}static ok(e,t,s){var r,o;const i=b.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=b.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 b.INTERNAL_SERVER_ERROR;const t=Math.trunc(e);return t<400||t>599?b.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 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&&n({"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()||B.error(this.req,this.res,e)}file(e){this.isResponded()||(this.status(b.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 a(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 a(null!==(t=null===(e=this.req)||void 0===e?void 0:e.headers)&&void 0!==t?t:{},e=>this.normalize(e))}getIp(){return P(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 a(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 l(s)?void 0:String(s)}getParams(){var e,t;return a(null!==(t=null===(e=this.req)||void 0===e?void 0:e.params)&&void 0!==t?t:{},e=>{if(!l(e)&&!u(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(b.OK,e)}normalize(e){if(!l(e)&&!u(e))return i(e)?JSON.stringify(e):String(e)}ok(e,t){this.isResponded()||B.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||l(t)?this.res.end():this.res.json(t))}setCookie(e,t,s){this.res.cookie(e,t,null!=s?s:{})}status(e){return l(e)||this.res.status(e),this.res.statusCode}success(e){this.send(b.OK,{message:e})}}class K{static extends(t){return e(K.EXTENDS,t,[])}static middleware(t){return e(K.MIDDLEWARE,t,[])}static parameters(t){return e(K.PARAMETERS,t,[])}static path(t,s){return e(K.PATH,t,s)}static routers(t){return e(K.ROUTERS,t,[])}}K.EXTENDS=Symbol("EXTENDS"),K.MIDDLEWARE=Symbol("MIDDLEWARE"),K.PARAMETERS=Symbol("PARAMETERS"),K.PATH=Symbol("PATH"),K.ROUTERS=Symbol("ROUTERS");class Y extends d{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=g(),this._router=g(),this._controllers=[],this._controllers.push(...e.map(e=>h(e)?new e(...t(e)):e)),this._options=c({},{cross:!1,hybrid:!1,path:"/",port:3e3,session:{secret:"yoursecret",resave:!0,saveUninitialized:!1,cookie:{maxAge:864e5}}},null!=s?s:{}),this._app.use(A(this._options.json)),this._app.disable("x-powered-by"),this._app.use(f({extended:!0})),this._options.cross&&this._app.use(O(i(this._options.cross)?this._options.cross:{})),this._app.use(T(this._options.compression)),this._app.use(v(null===(r=this._options.cookie)||void 0===r?void 0:r.secret,this._options.cookie)),this._app.use(I(this._options.session)),this.init(),this._app.use(this._router);const n=(null===(o=this._options.path)||void 0===o?void 0:o.length)?this._options.path:"/";if(this._app.use(n,this._base),this._app.all(n+"/*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):B.error(e,t,new Q("Endpoint Not Found"))}),this._options.public){const e=L(this._options.public);S(e)&&this._app.use(N.static(e)),this._app.get("*path",(t,s)=>{S(e)?s.sendFile(e+"/index.html"):this._options.notfound?s.redirect(this._options.notfound):B.error(t,s,new Q('FILE "index.html" Not Found'))})}else this._app.all("*path",(e,t)=>{this._options.redirect?t.redirect(this._options.redirect):B.error(e,t,new Q("Endpoint not found"))});this._controllers.forEach(e=>{const t=g(),s=this._middlewares(e),r=K.parameters(e);this._extends(e).forEach(e=>{s.push(...this._middlewares(e)),r.push(...K.parameters(e))}),K.routers(e).forEach(o=>{const n=o.propertyKey.toString();if(p(e[n])){if(!p(t[o.method]))return this._notFound(o.method);const a=this._handles(e,n,s,r);return t[o.method](o.path,...a,(t,s,o)=>F(this,void 0,void 0,function*(){const a=new j(t,s,o,this,e),l=this._args(a,this._indexes(n,r)),u=yield e[n](...l);a.close(_(u)||i(u)?u:void 0)}))}this._notFound(`${e.name}.${n}`)}),this._extends(e).forEach(o=>{K.routers(o).forEach(o=>{const n=o.propertyKey.toString();if(p(e[n])){if(!p(t[o.method]))return this._notFound(o.method);const a=this._handles(e,n,s,r);return t[o.method](o.path,...a,(t,s,o)=>F(this,void 0,void 0,function*(){const a=new j(t,s,o,this,e),l=this._args(a,this._indexes(n,r)),u=yield e[n](...l);a.close(_(u)||i(u)?u:void 0)}))}this._notFound(`${e.constructor.name}.${n}`)})}),this._base.use(K.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,n)=>F(this,void 0,void 0,function*(){const a=new j(r,o,n,this,e),l=p(t.argument)?t.argument(a):t.argument,u=yield t.callback.call(e,...this._args(a,s,l));(_(u)||i(u))&&a.close(u)})}this._notFound(t.method)}).filter(p)}_extends(e){return K.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[...K.middleware(e)].reverse()}_notFound(e){this.error(new Error(`Router "${e}" not found`),"express")}_port(e){return`Server listening on port ${e}`}listen(){return F(this,void 0,void 0,function*(){if(this._options.cert&&this._options.key||(this._server=D.createServer(this._app),this._server.listen(this._options.port,()=>this.log(this._port(this._options.port),"express"))),!this._server){const e=D.createServer((e,t)=>{const s=80==this._options.port?":80":"";t.writeHead(b.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 C(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 z=e=>t=>{K.path(t,(null==e?void 0:e.length)?e:"/")},W=e=>t=>{K.extends(t).push(e)},X=e=>t=>(s,r,o)=>{K.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=m();se()(s,o,0),K.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)=>{K.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),me=he(de.OPTIONS),Re=he(de.PATCH),Te=he(de.POST),ve=he(de.PUT),Oe=(e,t)=>(s,r)=>{let i=E;if(o(r)){const t=s;p(t[e])&&(i=t[e])}K.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"},ge=(e,t)=>{var s;return null!==(s=e[t])&&void 0!==s?s:null},Ae=(e,t)=>{const s=m()+"."+t;return S(x(e,s))?Ae(e,t):s},fe=e=>{const t=c({},e),s=M({destination(e,s,r){var o;const i=ge(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=ge(t,s.fieldname);r(null,Ae(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=ge(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"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=R.object(p(e)?e(R):e).parse();return(e,s,r)=>{le(e=>F(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 $(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,q as BadRequestError,ee as Body,ue as Cache,j as Context,z as Controller,te as Cookies,se as Ctx,pe as Delete,W as Extends,re as Files,H as ForbiddenError,Ee as Get,_e as Head,oe as Headers,B as HttpResponse,G as InternalServerError,K as Metadata,de as Methods,Oe as Middleware,Q as NotFoundError,me as Options,ie as Params,Re as Patch,Te as Post,ve as Put,ne as Query,w as ResponseError,ae as Session,b as StatusCodes,k as StatusText,V as UnauthorizedError,fe as Upload,le as Use,Ie as Validate,$ 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.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "Decorators for express",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs.js",
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
],
|
|
21
21
|
"scripts": {
|
|
22
22
|
"dev": "tsx-dev --watch --clear ./src/dev.ts",
|
|
23
|
-
"build": "rollup --bundleConfigAsCjs -c rollup.config.js"
|
|
23
|
+
"build": "npm run lint && rollup --bundleConfigAsCjs -c rollup.config.js",
|
|
24
|
+
"lint": "eslint \"src/**/*.{ts,tsx,js,jsx}\" --max-warnings=0"
|
|
24
25
|
},
|
|
25
26
|
"repository": {
|
|
26
27
|
"type": "git",
|
|
@@ -38,7 +39,7 @@
|
|
|
38
39
|
"dependencies": {
|
|
39
40
|
"@andrewcaires/decorator": "^1.1.1",
|
|
40
41
|
"@andrewcaires/node": "^1.3.1",
|
|
41
|
-
"@andrewcaires/utils.js": "^0.4.
|
|
42
|
+
"@andrewcaires/utils.js": "^0.4.31",
|
|
42
43
|
"compression": "^1.8.1",
|
|
43
44
|
"cookie-parser": "^1.4.7",
|
|
44
45
|
"cors": "^2.8.6",
|
|
@@ -52,7 +53,7 @@
|
|
|
52
53
|
"@rollup/plugin-commonjs": "^29.0.0",
|
|
53
54
|
"@rollup/plugin-terser": "^0.4.4",
|
|
54
55
|
"@rollup/plugin-typescript": "^12.3.0",
|
|
55
|
-
"@rollup/rollup-darwin-arm64": "^4.
|
|
56
|
+
"@rollup/rollup-darwin-arm64": "^4.59.0",
|
|
56
57
|
"@types/compression": "^1.8.1",
|
|
57
58
|
"@types/cookie-parser": "^1.4.10",
|
|
58
59
|
"@types/cors": "^2.8.19",
|
|
@@ -62,10 +63,10 @@
|
|
|
62
63
|
"@types/node": "^25.3.0",
|
|
63
64
|
"@types/request-ip": "^0.0.41",
|
|
64
65
|
"@types/swagger-ui-express": "^4.1.8",
|
|
65
|
-
"eslint": "^10.0.
|
|
66
|
+
"eslint": "^10.0.2",
|
|
66
67
|
"rollup-plugin-dts": "^6.3.0",
|
|
67
68
|
"swagger-ui-express": "^5.0.1",
|
|
68
69
|
"tslib": "^2.8.1",
|
|
69
|
-
"typescript-eslint": "^8.56.
|
|
70
|
+
"typescript-eslint": "^8.56.1"
|
|
70
71
|
}
|
|
71
72
|
}
|