@celosiajs/core
Version:
CelosiaJS Core. A framework for REST API based on Express.js
3 lines (2 loc) • 18.6 kB
JavaScript
import ne from"express";import oe from"cookie-parser";import ae from"qs";import{createLogger as z}from"winston";var X={logger:z({silent:!0})},P=X;var v=class{constructor(e){this.loggingSource=e;this.logger=P.logger.child({source:e})}logger},d=v;var Y=(i,e,s)=>{i.signedCookies={},i.cookies={},s()},$=Y;var ee=(i,e,s)=>{i.__CELOSIAJS__={postValidationQuery:{}},i.celosiaInstance=i.app.celosiaInstance,e.celosiaInstance=i.app.celosiaInstance;let r=new H(i),t=new _(e);i.celosiaRequest=r,i.celosiaResponse=t,e.celosiaRequest=r,e.celosiaResponse=t,s()},U=ee;import se from"body-parser";var te=i=>(e,s,r)=>{if(!e.header("content-type")?.startsWith("application/json"))return r();e.body={};let t=n=>{if(n instanceof Error){s.status(422).json({errors:{others:["Invalid json body"]},data:{}});return}r()};se.json(i)(e,s,t)},D=te;import re from"body-parser";var ie=i=>(e,s,r)=>{if(!e.header("content-type")?.startsWith("application/x-www-form-urlencoded"))return r();e.body={};let t=n=>{if(n instanceof Error){s.status(422).json({errors:{others:["Invalid urlencoded body"]},data:{}});return}r()};re.urlencoded(i)(e,s,t)},G=ie;var Q=(s=>(s[s.Simple=0]="Simple",s[s.Extended=1]="Extended",s))(Q||{}),O=class extends d{_cachedExtensionsProxy=null;_express;_server=null;_options;hasErrorHandlerAdded=!1;constructor(e){if(super("CelosiaJS"),this._options=e,this._express=ne(),this._express.celosiaInstance=this,this._express.disable("x-powered-by"),this.options.trustProxy!==void 0&&this._express.set("trust proxy",this.options.trustProxy),this.options.rootRouter?.caseSensitive!==void 0&&this._express.set("case sensitive routing",this.options.rootRouter.caseSensitive),this.options.rootRouter?.strictTrailingSlashes!==void 0&&this._express.set("strict routing",this.options.rootRouter.strictTrailingSlashes),this.options.queryParser?.enabled??!0?(this.options.queryParser?.mode??0)==0?this._express.set("query parser","simple"):this._express.set("query parser fn",s=>ae.parse(s,this.options.queryParser?.extendedOptions)):this._express.set("query parser",!1),this._express.use(U),this.options.urlencodedBodyParser?.enabled??!0){let{enabled:s,...r}=this.options.urlencodedBodyParser??{};this._express.use(G(r))}if(this.options.jsonBodyParser?.enabled??!0){let{enabled:s,...r}=this.options.jsonBodyParser??{};this._express.use(D(r))}if(this.options.cookieParser?.enabled??!0){let{enabled:s,secret:r,...t}=this.options.cookieParser??{};this._express.use(oe(r,t))}else this._express.use($)}get express(){return this._express}get options(){return this._options}get extensions(){return this._cachedExtensionsProxy??=new Proxy({},{get:(e,s,r)=>{let t=p.getCelosiaInstanceExtension(s);if(t===void 0)throw new a(`Use of unregistered extension "${s.toString()}".`);return(...n)=>t(this,...n)}}),this._cachedExtensionsProxy}get server(){return this._server}get isListening(){return this._server?.listening??!1}addErrorHandler(){this.hasErrorHandlerAdded||(this.hasErrorHandlerAdded=!0,this._express.use((e,s,r,t)=>{this.logger.error("Global error handler",{requestId:s.celosiaRequest.id},e),r.status(500).json({errors:{others:["Internal Server Error"]},data:{}})}))}listen(e){if(this._server!==null)throw new Error("Server already running");return new Promise((s,r)=>{this._server=this._express.listen(e.port??0,e.host??"127.0.0.1",e.backlog??511,t=>{if(t)return r(t);s()})})}close(){if(this._server===null)throw new Error("Server is not running");return new Promise((e,s)=>{this._server?.close(r=>{r?s(r):e()})})}useRouters(...e){let s=e[0],r=typeof s=="string"?s:null;return(r===null?e:e.filter((n,o)=>o!==0)).forEach(n=>{r===null?this._express.use(n.expressRouter):this._express.use(r,n.expressRouter)}),this}useMiddlewares(...e){let s=e[0],r=typeof s=="string"?s:null;return(r===null?e:e.filter((n,o)=>o!==0)).forEach(n=>{let o=(l,c,y)=>{try{n.index({},l.celosiaRequest,c.celosiaResponse,()=>{y()})}catch(h){this.logger.error("Unknown middleware error occured",{requestId:l.celosiaRequest.id},h)}};r===null?this._express.use(o):this._express.use(r,o)}),this}generateRequestId(e){return this.options.generateRequestId?.(e)??crypto.randomUUID()}},le=O;var V=class{_expressRequest;_cachedExtensionsProxy=null;id;constructor(e){this._expressRequest=e,this.id=e.celosiaInstance.generateRequestId(this)}get extensions(){return this._cachedExtensionsProxy??=new Proxy({},{get:(e,s,r)=>{let t=p.getCelosiaRequestExtension(s);if(t===void 0)throw new a(`Use of unregistered extension "${s.toString()}".`);return(...n)=>t(this,...n)}}),this._cachedExtensionsProxy}get expressRequest(){return this._expressRequest}get instance(){return this.expressRequest.celosiaInstance}get response(){return this.expressRequest.celosiaResponse}get body(){return this.expressRequest.body}set body(e){this.expressRequest.body=e}get query(){return this.expressRequest.query}get params(){return this.expressRequest.params}set params(e){this.expressRequest.params=e}get cookies(){return this.expressRequest.cookies}set cookies(e){this.expressRequest.cookies=e}get headers(){return this.expressRequest.headers}set headers(e){this.expressRequest.headers=e}header(e){return this.expressRequest.header(e)}accepts(...e){return this.expressRequest.accepts(e)}acceptsCharsets(...e){return this.expressRequest.acceptsCharsets(e)}acceptsEncodings(...e){return this.expressRequest.acceptsEncodings(e)}acceptsLanguages(...e){return this.expressRequest.acceptsLanguages(e)}range(e,s){return this.expressRequest.range(e,s)}get protocol(){return this.expressRequest.protocol}get ip(){return this.expressRequest.ip}get ips(){return this.expressRequest.ips}get subdomains(){return this.expressRequest.subdomains}get path(){return this.expressRequest.path}get hostname(){return this.expressRequest.hostname}get fresh(){return this.expressRequest.fresh}get xhr(){return this.expressRequest.xhr}get method(){return this.expressRequest.method}get httpVersion(){return this.expressRequest.httpVersion}get httpVersionMajor(){return this.expressRequest.httpVersionMajor}get httpVersionMinor(){return this.expressRequest.httpVersionMinor}get complete(){return this.expressRequest.complete}get socket(){return this.expressRequest.socket}get headersDistinct(){return this.expressRequest.headersDistinct}get rawHeaders(){return this.expressRequest.rawHeaders}get trailers(){return this.expressRequest.trailers}get trailersDistinct(){return this.expressRequest.trailersDistinct}get rawTrailers(){return this.expressRequest.rawTrailers}setTimeout(e,s){return this.expressRequest.setTimeout(e,s),this}get url(){return this.expressRequest.url}destroy(e){return this.expressRequest.destroy(e),this}},H=V;var I=class{_expressResponse;_cachedExtensionsProxy=null;constructor(e){this._expressResponse=e}get extensions(){return this._cachedExtensionsProxy??=new Proxy({},{get:(e,s,r)=>{let t=p.getCelosiaResponseExtension(s);if(t===void 0)throw new a(`Use of unregistered extension "${s.toString()}".`);return(...n)=>t(this,...n)}}),this._cachedExtensionsProxy}get expressResponse(){return this._expressResponse}get instance(){return this.expressResponse.celosiaInstance}get request(){return this.expressResponse.celosiaRequest}status(e){return this.expressResponse.status(e),this}sendStatus(e){return this.expressResponse.sendStatus(e),this}send(e){return this.expressResponse.send(e),this}json(e){return this.expressResponse.json(e),this}async sendFile(e,s){return new Promise((r,t)=>{let n=o=>{if(o){t(o);return}r()};s?this.expressResponse.sendFile(e,s,n):this.expressResponse.sendFile(e,n)})}async download(e,s,r){return new Promise((t,n)=>{let o=l=>{if(l){n(l);return}t()};r&&s?this.expressResponse.download(e,s,r,o):s?this.expressResponse.download(e,s,o):this.expressResponse.download(e,o)})}attachment(e){return this.expressResponse.attachment(e),this}contentType(e){return this.expressResponse.contentType(e),this}write(e){return this.expressResponse.write(e),this}header(e,s){return typeof e=="string"?s?(this.expressResponse.header(e,s),this):this.expressResponse.getHeader(e):(this.expressResponse.header(e),this)}get headers(){return this.expressResponse.getHeaders()}get headersSent(){return this.expressResponse.headersSent}clearCookie(e,s){return s?this.expressResponse.clearCookie(e,s):this.expressResponse.clearCookie(e),this}cookie(e,s,r){return r?this.expressResponse.cookie(e,s,r):this.expressResponse.cookie(e,s),this}location(e){return this.expressResponse.location(e),this}redirect(e,s){return typeof e=="string"?this.expressResponse.redirect(e):this.expressResponse.redirect(e,s),this}get statusCode(){return this.expressResponse.statusCode}get statusMessage(){return this.expressResponse.statusMessage}get strictContentLength(){return this.expressResponse.strictContentLength}assignSocket(e){this.expressResponse.assignSocket(e)}detachSocket(e){this.expressResponse.detachSocket(e)}writeContinue(e){this.expressResponse.writeContinue(e)}writeEarlyHints(e,s){this.expressResponse.writeEarlyHints(e,s)}writeHead(e,s,r){return typeof s=="string"?this.expressResponse.writeHead(e,s,r):this.expressResponse.writeHead(e,s),this}writeProcessing(){this.expressResponse.writeProcessing()}sendInternalServerError(){return this.status(500).json(this.instance.options.response?.internalServerErrorResponse??{errors:{others:["Internal server error"]},data:{}})}vary(e){return this.expressResponse.vary(e),this}},_=I;import de from"express";import f from"zod/v4";var k=class i extends d{_celosiaRouterOptions;_isStrict;_expressRouter;_cachedExtensionsProxy=null;constructor(e){super("CelosiaJS"),this._celosiaRouterOptions=e,this._isStrict=e.strict,this._expressRouter=de.Router({strict:e.strictTrailingSlashes,caseSensitive:e.caseSensitive,mergeParams:e.mergeParams})}get celosiaRouterOptions(){return this._celosiaRouterOptions}get extensions(){return this._cachedExtensionsProxy??=new Proxy({},{get:(e,s,r)=>{let t=p.getCelosiaRouterExtension(s);if(t===void 0)throw new a(`Use of unregistered extension "${s.toString()}".`);return(...n)=>t(this,...n)}}),this._cachedExtensionsProxy}get isStrict(){return this._isStrict}get expressRouter(){return this._expressRouter}useRouters(...e){let s=e[0],r=typeof s=="string"?s:null;return(r===null?e:e.filter((n,o)=>o!==0)).forEach(n=>{r===null?this._expressRouter.use(n.expressRouter):this._expressRouter.use(r,n.expressRouter)}),this}useMiddlewares(...e){let s=e[0],r=typeof s=="string"?s:null;return(r===null?e:e.filter((n,o)=>o!==0)).forEach(n=>{let o=async(l,c,y)=>{try{await n.index({},l.celosiaRequest,c.celosiaResponse,()=>{y()})}catch(h){this.logger.error("Unknown middleware error occured",{requestId:l.celosiaRequest.id},h)}};r===null?this._expressRouter.use(o):this._expressRouter.use(r,o)}),this}group(e,s,r){let t;typeof e=="string"?(typeof s=="function"?(t=new i(this.celosiaRouterOptions),s(t)):(t=new i({...this.celosiaRouterOptions,...s}),r(t)),this.useRouters(e,t)):(typeof e=="function"?(t=new i(this.celosiaRouterOptions),e(t)):(t=new i({...this.celosiaRouterOptions,...e}),s(t)),this.useRouters(t))}get(e,s,r,t){return t?this._expressRouter.get(e,this.handler(s,r,t)):this._expressRouter.get(e,this.handler([],s,r)),this}head(e,s,r,t){return t?this._expressRouter.head(e,this.handler(s,r,t)):this._expressRouter.head(e,this.handler([],s,r)),this}post(e,s,r,t){return t?this._expressRouter.post(e,this.handler(s,r,t)):this._expressRouter.post(e,this.handler([],s,r)),this}put(e,s,r,t){return t?this._expressRouter.put(e,this.handler(s,r,t)):this._expressRouter.put(e,this.handler([],s,r)),this}patch(e,s,r,t){return t?this._expressRouter.patch(e,this.handler(s,r,t)):this._expressRouter.patch(e,this.handler([],s,r)),this}delete(e,s,r,t){return t?this._expressRouter.delete(e,this.handler(s,r,t)):this._expressRouter.delete(e,this.handler([],s,r)),this}options(e,s,r,t){return t?this._expressRouter.options(e,this.handler(s,r,t)):this._expressRouter.options(e,this.handler([],s,r)),this}all(e,s,r,t){return t?this._expressRouter.all(e,this.handler(s,r,t)):this._expressRouter.all(e,this.handler([],s,r)),this}handler(e,s,r){return async(t,n)=>{let o={};for(let q of e)try{o=await new Promise((S,b)=>{try{let u=q.index(o,t.celosiaRequest,n.celosiaResponse,g=>{S(g)});u instanceof Promise&&u.catch(g=>{b(g)})}catch(u){b(u)}})??{}}catch(R){this.logger.error("Unknown handler preValidationMiddleware error occured",{requestId:t.celosiaRequest.id},R),n.writableEnded||n.celosiaResponse.sendInternalServerError();return}if(n.writableEnded){this.logger.warn("A pre validation middleware calls next after writing response. Request won't be processed further.",{requestId:t.celosiaRequest.id,url:t.url,method:t.method});return}let l=await r.body.safeParseAsync(t.body),c=await r.query.safeParseAsync(t.query),y=await r.params.safeParseAsync(t.params),h=await r.cookies.safeParseAsync(t.cookies),C={parsing:{}};if(l.success||(C.parsing.body=f.treeifyError(l.error)),c.success||(C.parsing.query=f.treeifyError(c.error)),y.success||(C.parsing.params=f.treeifyError(y.error)),h.success||(C.parsing.cookies=f.treeifyError(h.error)),!l.success||!c.success||!y.success||!h.success){n.status(422).json({data:{},errors:C});return}t.body=l.data,t.__CELOSIAJS__.postValidationQuery=c.data,Object.defineProperty(t,"query",{configurable:!0,enumerable:!0,get:()=>t.__CELOSIAJS__.postValidationQuery}),t.params=y.data,t.cookies=h.data;for(let q of s)try{let R=await new Promise((S,b)=>{try{let u=q.index(o,t.celosiaRequest,n.celosiaResponse,g=>{S(g)});u instanceof Promise&&u.catch(g=>{b(g)})}catch(u){b(u)}});o={...o,...R??{}}}catch(R){this.logger.error("Unknown handler middleware error occured",{requestId:t.celosiaRequest.id},R),n.writableEnded||n.celosiaResponse.sendInternalServerError();return}if(n.writableEnded){this.logger.warn("A middleware calls next after writing response. Request won't be processed further.",{requestId:t.celosiaRequest.id,url:t.url,method:t.method});return}r.index(o,t.celosiaRequest,n.celosiaResponse)}}},ue=k;var pe=(i,e)=>class extends w{constructor(){super(i)}async index(s,r,t,n){await e(r.expressRequest,t.expressResponse,o=>{if(!o||o==="route"||o==="router")return n();throw o})}},ce=pe;var a=class extends Error{constructor(e,s){super(e,s),this.name="InvalidExtensionError"}},x=class extends Error{constructor(e,s){super(e,s),this.name="DuplicateExtensionError"}};var j=class extends Error{constructor(e,s){super(e,s),this.name="RepositoryError"}},ye=j;var B=class extends d{constructor(e){super(e)}},he=B;var N=class extends Error{constructor(e,s){super(e,s),this.name="ServiceError"}},ge=N;var T=class extends d{constructor(e){super(e)}},xe=T;var m=Symbol("providerKey"),W=(s=>(s[s.Singleton=0]="Singleton",s[s.Transient=1]="Transient",s))(W||{}),Re=(i=1,e)=>s=>{let r=s;e===void 0&&r[m]===void 0&&(r[m]=Symbol());let t=e??r[m];M.registerProvider(t,s,i)},M=class i{static providers=new Map;static singletonCache=new Map;constructor(){}static registerProvider(e,s,r=1){let t=this.resolveKey(e);if(i.providers.has(t))throw new Error(`Provider for ${t.description} already exist`);i.providers.set(t,{key:t,provider:s,scope:r})}static get(e){let s=this.resolveKey(e),r=i.providers.get(s);if(!r)throw new Error(`Provider for ${s.description} does not exist`);if(r.scope===0){if(i.singletonCache.has(s))return i.singletonCache.get(s);let t=new r.provider;return i.singletonCache.set(s,t),t}return new r.provider}static resolveKey(e){if(typeof e=="symbol")return e;if(typeof e=="string")return Symbol.for(e);if(!e[m])throw new Error(`${e.name} is not a registered provider`);return e[m]}},K=M;var J=class extends d{constructor(e){super(e)}},w=J;var A=class extends w{constructor(){super("SendRequestId")}index(e,s,r,t){r.header("Request-Id",s.id),t()}},Ce=A;import Z from"zod/v4";var L=Z.object({}),F=class extends d{constructor(e){super(e)}get body(){return Z.object({}).optional()}get query(){return L}get params(){return L}get cookies(){return L}},be=F;var E=class{celosiaInstanceExtensionsHandler=new Map;celosiaRouterExtensionsHandler=new Map;celosiaRequestExtensionsHandler=new Map;celosiaResponseExtensionsHandler=new Map;registerCelosiaInstanceExtension(e,s){if(this.celosiaInstanceExtensionsHandler.has(e))throw new x(`Cannot register key "${e.toString()}" because the same key already exists.`);this.celosiaInstanceExtensionsHandler.set(e,s)}removeCelosiaInstanceExtension(e){if(!this.celosiaInstanceExtensionsHandler.has(e))throw new a(`Cannot remove key "${e.toString()}" because key doesn't exist.`);this.celosiaInstanceExtensionsHandler.delete(e)}getCelosiaInstanceExtension(e){return this.celosiaInstanceExtensionsHandler.get(e)}registerCelosiaRouterExtension(e,s){if(this.celosiaRouterExtensionsHandler.has(e))throw new x(`Cannot register key "${e.toString()}" because the same key already exists.`);this.celosiaRouterExtensionsHandler.set(e,s)}removeCelosiaRouterExtension(e){if(!this.celosiaRouterExtensionsHandler.has(e))throw new a(`Cannot remove key "${e.toString()}" because key doesn't exist.`);this.celosiaRouterExtensionsHandler.delete(e)}getCelosiaRouterExtension(e){return this.celosiaRouterExtensionsHandler.get(e)}registerCelosiaRequestExtension(e,s){if(this.celosiaRequestExtensionsHandler.has(e))throw new x(`Cannot register key "${e.toString()}" because the same key already exists.`);this.celosiaRequestExtensionsHandler.set(e,s)}removeCelosiaRequestExtension(e){if(!this.celosiaRequestExtensionsHandler.has(e))throw new a(`Cannot remove key "${e.toString()}" because key doesn't exist.`);this.celosiaRequestExtensionsHandler.delete(e)}getCelosiaRequestExtension(e){return this.celosiaRequestExtensionsHandler.get(e)}registerCelosiaResponseExtension(e,s){if(this.celosiaResponseExtensionsHandler.has(e))throw new x(`Cannot register key "${e.toString()}" because the same key already exists.`);this.celosiaResponseExtensionsHandler.set(e,s)}removeCelosiaResponseExtension(e){if(!this.celosiaResponseExtensionsHandler.has(e))throw new a(`Cannot remove key "${e.toString()}" because key doesn't exist.`);this.celosiaResponseExtensionsHandler.delete(e)}getCelosiaResponseExtension(e){return this.celosiaResponseExtensionsHandler.get(e)}},we=new E,p=we;export{le as CelosiaInstance,H as CelosiaRequest,_ as CelosiaResponse,ue as CelosiaRouter,be as Controller,K as DI,K as DependencyInjection,W as DependencyScope,x as DuplicateExtensionError,ce as ExpressMiddlewareCompat,p as ExtensionsRegistry,E as ExtensionsRegistryClass,P as Globals,Re as Injectable,a as InvalidExtensionError,d as LoggerBase,w as Middleware,Q as QueryParserMode,he as Repository,ye as RepositoryError,Ce as SendRequestId,xe as Service,ge as ServiceError};
//# sourceMappingURL=index.js.map