Comparing version 0.2.7 to 0.3.0-exp-230217.335
/// <reference types="bun-types" /> | ||
import type { Serve, Server } from 'bun'; | ||
import { SCHEMA, DEFS } from './utils'; | ||
import { SCHEMA, DEFS, EXPOSED, exposePermission } from './utils'; | ||
import type { Context } from './context'; | ||
@@ -10,3 +10,3 @@ import type { Handler, BeforeRequestHandler, TypedRoute, ElysiaInstance, ElysiaConfig, HTTPMethod, InternalRoute, BodyParser, ErrorHandler, TypedSchema, LocalHook, LocalHandler, LifeCycle, LifeCycleEvent, LifeCycleStore, VoidLifeCycle, AfterRequestHandler, MergeIfNotNull, IsAny, OverwritableTypeRoute, MergeSchema, ListenCallback, NoReturnHandler, ElysiaRoute, MaybePromise, IsNever } from './types'; | ||
store: Instance['store']; | ||
protected decorators: Record<string, unknown> | null; | ||
protected decorators: ElysiaInstance['request'] | null; | ||
event: LifeCycleStore<Instance>; | ||
@@ -61,5 +61,5 @@ server: Server | null; | ||
route<Schema extends TypedSchema<Exclude<keyof Instance['store'][typeof DEFS], number | symbol>> = TypedSchema<Exclude<keyof Instance['store'][typeof DEFS], number | symbol>>, Method extends HTTPMethod = HTTPMethod, Path extends string = string, Response = unknown>(method: Method, path: Path, handler: LocalHandler<Schema, Instance, Path, Response>, hook?: LocalHook<Schema, Instance, Path>): ElysiaRoute<Method, Schema, Instance, Path, Response>; | ||
state<Key extends string | number | symbol = keyof Instance['store'], Value = Instance['store'][keyof Instance['store']], ReturnValue = Value extends () => infer Returned ? Returned extends Promise<infer AsyncReturned> ? AsyncReturned : Returned : Value, NewInstance = Elysia<{ | ||
state<Key extends string | number | symbol = keyof Instance['store'], Value = Instance['store'][keyof Instance['store']], NewInstance = Elysia<{ | ||
store: Instance['store'] & { | ||
[key in Key]: ReturnValue; | ||
[key in Key]: Value; | ||
}; | ||
@@ -88,2 +88,15 @@ request: Instance['request']; | ||
}>; | ||
expose<T extends Record<string, unknown> | ((app: Instance['request'] & { | ||
store: Instance['store']; | ||
permission: typeof exposePermission; | ||
}) => Record<string, unknown>) = Record<string, unknown> | ((app: Instance['request'] & { | ||
store: Instance['store']; | ||
permission: typeof exposePermission; | ||
}) => Record<string, unknown>)>(value: T): Elysia<{ | ||
store: Instance['store'] & { | ||
[EXPOSED]: T extends (store: any) => infer Returned ? Returned : T; | ||
}; | ||
request: Instance['request']; | ||
schema: Instance['schema']; | ||
}>; | ||
schema<Schema extends TypedSchema<Exclude<keyof Instance['store'][typeof DEFS], number | symbol>> = TypedSchema<Exclude<keyof Instance['store'][typeof DEFS], number | symbol>>, NewInstance = Elysia<{ | ||
@@ -99,3 +112,3 @@ request: Instance['request']; | ||
get modules(): Promise<Elysia<ElysiaInstance<{ | ||
store: Record<any, any> & Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}>; | ||
store: Record<any, any> & Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof EXPOSED, {}>; | ||
request: {}; | ||
@@ -114,4 +127,4 @@ schema: {}; | ||
export { Type as t } from '@sinclair/typebox'; | ||
export { SCHEMA, DEFS, createValidationError, getSchemaValidator, mergeDeep, mergeHook, mergeObjectArray, mapPathnameAndQueryRegEx, mapQuery } from './utils'; | ||
export { SCHEMA, DEFS, EXPOSED, createValidationError, getSchemaValidator, mergeDeep, mergeHook, mergeObjectArray, mapPathnameAndQueryRegEx, mapQuery } from './utils'; | ||
export type { Context, PreContext } from './context'; | ||
export type { Handler, RegisteredHook, BeforeRequestHandler, TypedRoute, OverwritableTypeRoute, ElysiaInstance, ElysiaConfig, HTTPMethod, ComposedHandler, InternalRoute, BodyParser, ErrorHandler, ErrorCode, TypedSchema, LocalHook, LocalHandler, LifeCycle, LifeCycleEvent, AfterRequestHandler, HookHandler, TypedSchemaToRoute, UnwrapSchema, LifeCycleStore, VoidLifeCycle, SchemaValidator, ElysiaRoute, ExtractPath, IsPathParameter, IsAny, IsNever, UnknownFallback, WithArray, ObjectValues, PickInOrder, MaybePromise, MergeIfNotNull } from './types'; |
@@ -1,1 +0,1 @@ | ||
import{Raikiri as e}from"raikiri";import{mapResponse as t,mapEarlyResponse as r}from"./handler";import{mapQuery as s,clone as a,mergeHook as i,mergeDeep as h,createValidationError as n,getSchemaValidator as o,SCHEMA as l,DEFS as d,getResponseSchemaValidator as u,mapPathnameAndQueryRegEx as f}from"./utils";import{registerSchemaPath as c}from"./schema";import{mapErrorCode as p,mapErrorStatus as m}from"./error";export default class v{store={[l]:{},[d]:{}};decorators=null;event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];lazyLoadModules=[];constructor(e={}){this.config={...e}}_addHandler(e,t,r,s){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:i(a(this.event),s)});let h=this.store[d],n=o(s?.schema?.body??this.$schema?.body,h),f=o(s?.schema?.headers??this.$schema?.headers,h,!0),p=o(s?.schema?.params??this.$schema?.params,h),m=o(s?.schema?.query??this.$schema?.query,h),v=u(s?.schema?.response??this.$schema?.response,h);c({schema:this.store[l],hook:s,method:e,path:t,models:this.store[d]});let g=i(a(this.event),s);g.schema||g.transform.length||g.beforeHandle.length||g.error.length||g.afterHandle.length||(g=void 0);let y={handle:r,hooks:g,validator:n||f||p||m||v?{body:n,header:f,params:p,query:m,response:v}:void 0};this.router.add(e,t,y)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t){let r=new v;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{"/"===r?this._addHandler(t,e,s,a):this._addHandler(t,`${e}${r}`,s,a)}),this}guard(e,t){let r=new v;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,i(e,a))}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),this):t}get(e,t,r){return this._addHandler("GET",e,t,r),this}post(e,t,r){return this._addHandler("POST",e,t,r),this}put(e,t,r){return this._addHandler("PUT",e,t,r),this}patch(e,t,r){return this._addHandler("PATCH",e,t,r),this}delete(e,t,r){return this._addHandler("DELETE",e,t,r),this}options(e,t,r){return this._addHandler("OPTIONS",e,t,r),this}all(e,t,r){return this._addHandler("ALL",e,t,r),this}head(e,t,r){return this._addHandler("HEAD",e,t,r),this}trace(e,t,r){return this._addHandler("TRACE",e,t,r),this}connect(e,t,r){return this._addHandler("CONNECT",e,t,r),this}route(e,t,r,s){return this._addHandler(e,t,r,s),this}state(e,t){return e in this.store||(this.store[e]=t),this}decorate(e,t){return this.decorators||(this.decorators={}),e in this.decorators||(this.decorators[e]=t),this}derive(e){return this.store=h(this.store,e(()=>this.store)),this}inject(e){return this.onTransform(t=>{Object.assign(t,e(t))})}schema(e){let t=this.store[d];return this.$schema={body:o(e.body,t),headers:o(e?.headers,t,!0),params:o(e?.params,t),query:o(e?.query,t),response:o(e?.response,t)},this}handle=async e=>{let i;let h={status:200,headers:{}};this.decorators?((i=a(this.decorators)).request=e,i.set=h,i.store=this.store,i.query={}):i={set:h,store:this.store,request:e,query:{}};try{let a;if(this.event.request.length)for(let e=0;e<this.event.request.length;e++){let t=this.event.request[e](i);if(t instanceof Promise&&(t=await t),t=r(t,h))return t}let o=e.url.match(f);if(!o)throw Error("NOT_FOUND");let l=this.router.match(e.method,o[1])??this.router.match("ALL",o[1]),d=l?.store;if(!d)throw Error("NOT_FOUND");if("GET"!==e.method){let t=e.headers.get("content-type");if(t){let r=t.indexOf(";");if(-1!==r&&(t=t.slice(0,r)),this.event.parse.length)for(let e=0;e<this.event.parse.length;e++){let r=this.event.parse[e](i,t);if(r instanceof Promise&&(r=await r),void 0!==r){a=r;break}}if(void 0===a)switch(t){case"application/json":a=await e.json();break;case"text/plain":a=await e.text();break;case"application/x-www-form-urlencoded":a=s(await e.text())}}}i.body=a,i.params=l.params,o[2]&&(i.query=s(o[2]));let u=d.hooks;if(u?.transform.length)for(let e=0;e<u.transform.length;e++){let t=u.transform[e](i);t instanceof Promise&&await t}if(d.validator){let t=d.validator;if(t.headers){let r={};for(let t in e.headers)r[t]=e.headers.get(t);if(!1===t.headers.Check(r))throw n("header",t.headers,r)}if(!1===t.params?.Check(i.params))throw n("params",t.params,i.params);if(!1===t.query?.Check(i.query))throw n("query",t.query,i.query);if(!1===t.body?.Check(a))throw n("body",t.body,a)}if(u?.beforeHandle.length)for(let e=0;e<u.beforeHandle.length;e++){let t=u.beforeHandle[e](i);if(t instanceof Promise&&(t=await t),null!=t){for(let e=0;e<u.afterHandle.length;e++){let r=u.afterHandle[e](i,t);r instanceof Promise&&(r=await r),r&&(t=r)}let e=r(t,i.set);if(e)return e}}let c=d.handle(i);if(c instanceof Promise&&(c=await c),!1===d.validator?.response?.Check(c))throw n("response",d.validator.response,c);if(u?.afterHandle.length)for(let e=0;e<u.afterHandle.length;e++){let t=u.afterHandle[e](i,c);t instanceof Promise&&(t=await t);let s=r(t,i.set);if(s)return s}return t(c,i.set)}catch(e){return this.handleError(e,h)}};async handleError(e,r={headers:{}}){for(let s=0;s<this.event.error.length;s++){let a=this.event.error[s]({code:p(e.message),error:e,set:r});if(a instanceof Promise&&(a=await a),null!=a)return t(a,r)}return new Response("string"==typeof e.cause?e.cause:e.message,{headers:r.headers,status:m(p(e.message))})}listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if("string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.handle,s="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r},a=`$$Elysia:${s.port}`;globalThis[a]?(this.server=globalThis[a],this.server.reload(s)):globalThis[a]=this.server=Bun.serve(s);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{this.server.pendingRequests||Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}setModel(e){return Object.entries(e).forEach(([e,t])=>{e in this.store[d]||(this.store[d][e]=t)}),this}}export{Type as t}from"@sinclair/typebox";export{SCHEMA,DEFS,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx,mapQuery}from"./utils";export{v as Elysia}; | ||
import{Raikiri as e}from"raikiri";import{mapResponse as t,mapEarlyResponse as r}from"./handler";import{mapQuery as s,clone as a,mergeHook as i,mergeDeep as o,createValidationError as n,getSchemaValidator as h,SCHEMA as l,DEFS as u,getResponseSchemaValidator as d,mapPathnameAndQueryRegEx as f,EXPOSED as c,exposePermission as p}from"./utils";import{registerSchemaPath as m}from"./schema";import{mapErrorCode as v,mapErrorStatus as y}from"./error";import{serialize as g,deserialize as b}from"superjson";export default class H{store={[l]:{},[u]:{},[c]:{}};decorators=null;event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];lazyLoadModules=[];constructor(e={}){this.config={...e}}_addHandler(e,t,r,s){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:i(a(this.event),s)});let o=this.store[u],n=h(s?.schema?.body??this.$schema?.body,o),f=h(s?.schema?.headers??this.$schema?.headers,o,!0),c=h(s?.schema?.params??this.$schema?.params,o),p=h(s?.schema?.query??this.$schema?.query,o),v=d(s?.schema?.response??this.$schema?.response,o);m({schema:this.store[l],hook:s,method:e,path:t,models:this.store[u]});let y=i(a(this.event),s);y.schema||y.transform.length||y.beforeHandle.length||y.error.length||y.afterHandle.length||(y=void 0);let g={handle:r,hooks:y,validator:n||f||c||p||v?{body:n,header:f,params:c,query:p,response:v}:void 0};this.router.add(e,t,g)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{"/"===r?this._addHandler(t,e,s,a):this._addHandler(t,`${e}${r}`,s,a)}),this}guard(e,t){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,i(e,a))}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),this):t}get(e,t,r){return this._addHandler("GET",e,t,r),this}post(e,t,r){return this._addHandler("POST",e,t,r),this}put(e,t,r){return this._addHandler("PUT",e,t,r),this}patch(e,t,r){return this._addHandler("PATCH",e,t,r),this}delete(e,t,r){return this._addHandler("DELETE",e,t,r),this}options(e,t,r){return this._addHandler("OPTIONS",e,t,r),this}all(e,t,r){return this._addHandler("ALL",e,t,r),this}head(e,t,r){return this._addHandler("HEAD",e,t,r),this}trace(e,t,r){return this._addHandler("TRACE",e,t,r),this}connect(e,t,r){return this._addHandler("CONNECT",e,t,r),this}route(e,t,r,s){return this._addHandler(e,t,r,s),this}state(e,t){return e in this.store||(this.store[e]=t),this}decorate(e,t){return this.decorators||(this.decorators={}),e in this.decorators||(this.decorators[e]=t),this}derive(e){return this.store=o(this.store,e(()=>this.store)),this}inject(e){return this.onTransform(t=>{Object.assign(t,e(t))})}expose(e){return 0===Object.keys(this.store[c]).length&&this.post("/~fn",e=>{let t=this.store[c],r=[],s=e.body;e:for(let a=0;a<s.length;a++){let i=s[a],o=t;if(!Array.isArray(i.n)){r.push(Error("Invalid procedure"));continue e}for(let t=0;t<i.n.length;t++){if(!(o=o[i.n[t]])){r.push(Error("Invalid procedure"));continue e}if(c in o){if(!1==o.allow){r.push(Error("Forbidden"));continue e}if(!0!==o.allow){try{let s=o.allow({...e,key:i.n.slice(t+1).join("."),params:i.p??null});if(s instanceof Error){r.push(s);continue e}}catch(e){r.push(e);continue e}o=o.value}}}"function"==typeof o?void 0!==i.p?r.push(o(i.p)):r.push(o()):r.push(Error("Invalid procedure"))}return Promise.all(r).then(g)}),this.store[c]=o(this.store[c],"function"==typeof e?e({...this.decorators,store:this.store,permission:p}):e),this}schema(e){let t=this.store[u];return this.$schema={body:h(e.body,t),headers:h(e?.headers,t,!0),params:h(e?.params,t),query:h(e?.query,t),response:h(e?.response,t)},this}handle=async e=>{let i;let o={status:200,headers:{}};this.decorators?((i=a(this.decorators)).request=e,i.set=o,i.store=this.store,i.query={}):i={set:o,store:this.store,request:e,query:{}};try{let a;if(this.event.request.length)for(let e=0;e<this.event.request.length;e++){let t=this.event.request[e](i);if(t instanceof Promise&&(t=await t),t=r(t,o))return t}let h=e.url.match(f);if(!h)throw Error("NOT_FOUND");let l=this.router.match(e.method,h[1])??this.router.match("ALL",h[1]),u=l?.store;if(!u)throw Error("NOT_FOUND");if("GET"!==e.method){let t=e.headers.get("content-type");if(t){let r=t.indexOf(";");if(-1!==r&&(t=t.slice(0,r)),this.event.parse.length)for(let e=0;e<this.event.parse.length;e++){let r=this.event.parse[e](i,t);if(r instanceof Promise&&(r=await r),void 0!==r){a=r;break}}if(void 0===a)switch(t){case"application/json":a=await e.json();break;case"text/plain":a=await e.text();break;case"application/x-www-form-urlencoded":a=s(await e.text());break;case"elysia/fn":a=b(await e.json())}}}i.body=a,i.params=l.params,h[2]&&(i.query=s(h[2]));let d=u.hooks;if(d?.transform.length)for(let e=0;e<d.transform.length;e++){let t=d.transform[e](i);t instanceof Promise&&await t}if(u.validator){let t=u.validator;if(t.headers){let r={};for(let t in e.headers)r[t]=e.headers.get(t);if(!1===t.headers.Check(r))throw n("header",t.headers,r)}if(!1===t.params?.Check(i.params))throw n("params",t.params,i.params);if(!1===t.query?.Check(i.query))throw n("query",t.query,i.query);if(!1===t.body?.Check(a))throw n("body",t.body,a)}if(d?.beforeHandle.length)for(let e=0;e<d.beforeHandle.length;e++){let t=d.beforeHandle[e](i);if(t instanceof Promise&&(t=await t),null!=t){for(let e=0;e<d.afterHandle.length;e++){let r=d.afterHandle[e](i,t);r instanceof Promise&&(r=await r),r&&(t=r)}let e=r(t,i.set);if(e)return e}}let c=u.handle(i);if(c instanceof Promise&&(c=await c),!1===u.validator?.response?.Check(c))throw n("response",u.validator.response,c);if(d?.afterHandle.length)for(let e=0;e<d.afterHandle.length;e++){let t=d.afterHandle[e](i,c);t instanceof Promise&&(t=await t);let s=r(t,i.set);if(s)return s}return t(c,i.set)}catch(e){return this.handleError(e,o)}};async handleError(e,r={headers:{}}){for(let s=0;s<this.event.error.length;s++){let a=this.event.error[s]({code:v(e.message),error:e,set:r});if(a instanceof Promise&&(a=await a),null!=a)return t(a,r)}return new Response("string"==typeof e.cause?e.cause:e.message,{headers:r.headers,status:y(v(e.message))})}listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if("string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.handle,s="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r},a=`$$Elysia:${s.port}`;globalThis[a]?(this.server=globalThis[a],this.server.reload(s)):globalThis[a]=this.server=Bun.serve(s);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{this.server.pendingRequests||Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}setModel(e){return Object.entries(e).forEach(([e,t])=>{e in this.store[u]||(this.store[u][e]=t)}),this}}export{Type as t}from"@sinclair/typebox";export{SCHEMA,DEFS,EXPOSED,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx,mapQuery}from"./utils";export{H as Elysia}; |
@@ -11,3 +11,3 @@ import { TSchema } from '@sinclair/typebox'; | ||
hook?: LocalHook<import("./types").TypedSchema<string>, import("./types").ElysiaInstance<{ | ||
store: Record<any, any> & Record<typeof import("./utils").SCHEMA, {}> & Record<typeof import("./utils").DEFS, {}>; | ||
store: Record<any, any> & Record<typeof import("./utils").SCHEMA, {}> & Record<typeof import("./utils").DEFS, {}> & Record<typeof import("./utils").EXPOSED, {}>; | ||
request: {}; | ||
@@ -14,0 +14,0 @@ schema: {}; |
@@ -7,3 +7,3 @@ /// <reference types="bun-types" /> | ||
import type { TypeCheck } from '@sinclair/typebox/compiler'; | ||
import type { SCHEMA, DEFS } from './utils'; | ||
import type { SCHEMA, DEFS, EXPOSED } from './utils'; | ||
import type { OpenAPIV2 } from 'openapi-types'; | ||
@@ -15,7 +15,7 @@ export type WithArray<T> = T | T[]; | ||
[x in string]: TSchema; | ||
}>; | ||
}> & Record<typeof EXPOSED, Record<string, Record<string, unknown>>>; | ||
request?: Record<any, any>; | ||
schema?: TypedSchema; | ||
} = { | ||
store: Record<any, any> & Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}>; | ||
store: Record<any, any> & Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}> & Record<typeof EXPOSED, {}>; | ||
request: {}; | ||
@@ -223,2 +223,8 @@ schema: {}; | ||
export type IsNever<T> = [T] extends [never] ? true : false; | ||
export type FunctionalKeys<T, Prefix extends string = ''> = { | ||
[K in keyof T]-?: T[K] extends Function ? `${Prefix}${K}` : never; | ||
}[keyof T] | { | ||
[K in keyof T]-?: T[K] extends object ? FunctionalKeys<T[K], `${Prefix}${K}.`> : never; | ||
}[keyof T]; | ||
export type ConnectedKeysType<T, K extends string> = K extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? ConnectedKeysType<T[Key], Rest> : never : K extends keyof T ? T[K] extends (...args: any) => any ? ReturnType<T[K]> : never : never; | ||
export {}; |
@@ -0,6 +1,8 @@ | ||
/// <reference types="bun-types" /> | ||
import { TSchema } from '@sinclair/typebox'; | ||
import { TypeCheck } from '@sinclair/typebox/compiler'; | ||
import type { DeepMergeTwoTypes, LifeCycleStore, LocalHook, TypedSchema, RegisteredHook } from './types'; | ||
import type { DeepMergeTwoTypes, LifeCycleStore, LocalHook, TypedSchema, RegisteredHook, ConnectedKeysType, FunctionalKeys } from './types'; | ||
export declare const SCHEMA: unique symbol; | ||
export declare const DEFS: unique symbol; | ||
export declare const EXPOSED: unique symbol; | ||
export declare const mergeObjectArray: <T>(a: T | T[], b: T | T[]) => T[]; | ||
@@ -15,1 +17,17 @@ export declare const mergeHook: (a: LocalHook<any> | LifeCycleStore<any>, b: LocalHook<any>) => RegisteredHook<any>; | ||
export declare const getResponseSchemaValidator: (s: TypedSchema['response'] | undefined, models: Record<string, TSchema>, additionalProperties?: boolean) => TypeCheck<TSchema> | undefined; | ||
export declare const exposePermission: <T, Key = T extends Record<any, any> ? FunctionalKeys<T, ""> : never>({ value, allow }: { | ||
value: T; | ||
allow?: boolean | ((context: { | ||
request: Request; | ||
key: Key; | ||
params: Key extends string ? ConnectedKeysType<T, Key> : unknown; | ||
}) => unknown) | undefined; | ||
}) => { | ||
value: T; | ||
allow?: boolean | ((context: { | ||
request: Request; | ||
key: Key; | ||
params: Key extends string ? ConnectedKeysType<T, Key> : unknown; | ||
}) => unknown) | undefined; | ||
[EXPOSED]: true; | ||
}; |
@@ -1,1 +0,1 @@ | ||
import{Kind as e,Type as r}from"@sinclair/typebox";import{TypeCompiler as t}from"@sinclair/typebox/compiler";export const SCHEMA=Symbol("schema");export const DEFS=Symbol("definitions");export const mergeObjectArray=(e,r)=>[...Array.isArray(e)?e:[e],...Array.isArray(r)?r:[r]];export const mergeHook=(e,r)=>{let t="schema"in e?e.schema:null,o=r&&"schema"in r?r.schema:null;return{schema:t||o?{body:o?.body??t?.body,header:o?.headers??t?.headers,params:o?.params??t?.params,query:o?.query??t?.query,response:o?.response??t?.response}:void 0,transform:mergeObjectArray(e.transform??[],r?.transform??[]),beforeHandle:mergeObjectArray(e.beforeHandle??[],r?.beforeHandle??[]),afterHandle:mergeObjectArray(e.afterHandle??[],r?.afterHandle??[]),error:mergeObjectArray(e.error??[],r?.error??[])}};export const clone=e=>e;export const mapPathnameAndQueryRegEx=/:\/\/[^/]+([^#?]+)(?:\?([^#]+))?/;export const mapQuery=e=>{let r={},t=e.split("&");for(let e=0;e<t.length;e++){let o=t[e],n=o.indexOf("="),a=o.slice(n+1);a.includes("%")&&(a=decodeURIComponent(a)),r[o.slice(0,n)]=a}return r};let o=e=>e&&"object"==typeof e&&!Array.isArray(e);export const mergeDeep=(e,r)=>{let t=Object.assign({},e);return o(e)&&o(r)&&Object.keys(r).forEach(n=>{o(r[n])&&n in e?t[n]=mergeDeep(e[n],r[n]):Object.assign(t,{[n]:r[n]})}),t};export const createValidationError=(e,r,t)=>{let o=r.Errors(t).next().value;return Error("VALIDATION",{cause:`Invalid ${e}: '${o?.path?.slice(1)||"root"}'. ${o.message}`})};export const getSchemaValidator=(e,r,o=!1)=>{if(!e||"string"==typeof e&&!(e in r))return;let n="string"==typeof e?r[e]:e;return"object"===n.type&&"additionalProperties"in n==!1&&(n.additionalProperties=o),t.Compile(n)};export const getResponseSchemaValidator=(o,n,a=!1)=>{if(!o||"string"==typeof o&&!(o in n))return;let s="string"==typeof o?n[o]:o,i=e in s?s:r.Union(Object.keys(s).map(e=>{let r=s[e];if("string"==typeof r){if(r in n){let e=n[r];return e}return}return r}).filter(e=>e));return"object"===i.type&&"additionalProperties"in i==!1&&(i.additionalProperties=a),t.Compile(i)}; | ||
import{Kind as e,Type as r}from"@sinclair/typebox";import{TypeCompiler as t}from"@sinclair/typebox/compiler";export const SCHEMA=Symbol("schema");export const DEFS=Symbol("definitions");export const EXPOSED=Symbol("exposed");export const mergeObjectArray=(e,r)=>[...Array.isArray(e)?e:[e],...Array.isArray(r)?r:[r]];export const mergeHook=(e,r)=>{let t="schema"in e?e.schema:null,o=r&&"schema"in r?r.schema:null;return{schema:t||o?{body:o?.body??t?.body,header:o?.headers??t?.headers,params:o?.params??t?.params,query:o?.query??t?.query,response:o?.response??t?.response}:void 0,transform:mergeObjectArray(e.transform??[],r?.transform??[]),beforeHandle:mergeObjectArray(e.beforeHandle??[],r?.beforeHandle??[]),afterHandle:mergeObjectArray(e.afterHandle??[],r?.afterHandle??[]),error:mergeObjectArray(e.error??[],r?.error??[])}};export const clone=e=>e;export const mapPathnameAndQueryRegEx=/:\/\/[^/]+([^#?]+)(?:\?([^#]+))?/;export const mapQuery=e=>{let r={},t=e.split("&");for(let e=0;e<t.length;e++){let o=t[e],n=o.indexOf("="),a=o.slice(n+1);a.includes("%")&&(a=decodeURIComponent(a)),r[o.slice(0,n)]=a}return r};let o=e=>e&&"object"==typeof e&&!Array.isArray(e);export const mergeDeep=(e,r)=>{let t=Object.assign({},e);return o(e)&&o(r)&&Object.keys(r).forEach(n=>{o(r[n])&&n in e?t[n]=mergeDeep(e[n],r[n]):Object.assign(t,{[n]:r[n]})}),t};export const createValidationError=(e,r,t)=>{let o=r.Errors(t).next().value;return Error("VALIDATION",{cause:`Invalid ${e}: '${o?.path?.slice(1)||"root"}'. ${o.message}`})};export const getSchemaValidator=(e,r,o=!1)=>{if(!e||"string"==typeof e&&!(e in r))return;let n="string"==typeof e?r[e]:e;return"object"===n.type&&"additionalProperties"in n==!1&&(n.additionalProperties=o),t.Compile(n)};export const getResponseSchemaValidator=(o,n,a=!1)=>{if(!o||"string"==typeof o&&!(o in n))return;let s="string"==typeof o?n[o]:o,i=e in s?s:r.Union(Object.keys(s).map(e=>{let r=s[e];if("string"==typeof r){if(r in n){let e=n[r];return e}return}return r}).filter(e=>e));return"object"===i.type&&"additionalProperties"in i==!1&&(i.additionalProperties=a),t.Compile(i)};export const exposePermission=({value:e,allow:r=!0})=>({[EXPOSED]:!0,value:e,allow:r}); |
103
package.json
{ | ||
"name": "elysia", | ||
"description": "Fast, and friendly Bun web framework", | ||
"version": "0.2.7", | ||
"author": { | ||
"name": "saltyAom", | ||
"url": "https://github.com/SaltyAom", | ||
"email": "saltyaom@gmail.com" | ||
}, | ||
"main": "./dist/index.js", | ||
"exports": { | ||
"require": "./dist/index.js", | ||
"import": "./dist/index.js", | ||
"node": "./dist/index.js", | ||
"default": "./dist/index.js" | ||
}, | ||
"types": "./dist/index.d.ts", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/elysiajs/elysia" | ||
}, | ||
"bugs": "https://github.com/elysiajs/elysia/issues", | ||
"homepage": "https://github.com/elysiajs/elysia", | ||
"keywords": [ | ||
"bun", | ||
"http", | ||
"web", | ||
"server" | ||
], | ||
"license": "MIT", | ||
"scripts": { | ||
"test": "bun wiptest", | ||
"dev": "bun run --hot example/http.ts", | ||
"build": "rimraf dist && swc src -d dist && tsc --project tsconfig.esm.json", | ||
"release": "npm run build && npm run test && npm publish" | ||
}, | ||
"dependencies": { | ||
"@sinclair/typebox": "^0.25.21", | ||
"openapi-types": "^12.1.0", | ||
"raikiri": "^0.0.0-beta.5" | ||
}, | ||
"devDependencies": { | ||
"@swc/cli": "^0.1.60", | ||
"@swc/core": "^1.3.32", | ||
"@types/node": "^18.11.18", | ||
"@typescript-eslint/eslint-plugin": "^5.48.2", | ||
"@typescript-eslint/parser": "^5.48.2", | ||
"bun-types": "^0.5.0", | ||
"eslint": "^8.32.0", | ||
"rimraf": "^3.0.2", | ||
"typescript": "^4.9.4" | ||
} | ||
"name": "elysia", | ||
"description": "Fast, and friendly Bun web framework", | ||
"version": "0.3.0-exp-230217.0335", | ||
"author": { | ||
"name": "saltyAom", | ||
"url": "https://github.com/SaltyAom", | ||
"email": "saltyaom@gmail.com" | ||
}, | ||
"main": "./dist/index.js", | ||
"exports": { | ||
"require": "./dist/index.js", | ||
"import": "./dist/index.js", | ||
"node": "./dist/index.js", | ||
"default": "./dist/index.js" | ||
}, | ||
"types": "./dist/index.d.ts", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/elysiajs/elysia" | ||
}, | ||
"bugs": "https://github.com/elysiajs/elysia/issues", | ||
"homepage": "https://github.com/elysiajs/elysia", | ||
"keywords": [ | ||
"bun", | ||
"http", | ||
"web", | ||
"server" | ||
], | ||
"license": "MIT", | ||
"scripts": { | ||
"test": "bun wiptest", | ||
"dev": "bun run --hot example/http.ts", | ||
"build": "rimraf dist && swc src -d dist && tsc --project tsconfig.esm.json", | ||
"release": "npm run build && npm run test && npm publish" | ||
}, | ||
"dependencies": { | ||
"@sinclair/typebox": "^0.25.21", | ||
"openapi-types": "^12.1.0", | ||
"raikiri": "^0.0.0-beta.5", | ||
"superjson": "^1.12.2" | ||
}, | ||
"devDependencies": { | ||
"@swc/cli": "^0.1.60", | ||
"@swc/core": "^1.3.32", | ||
"@types/node": "^18.11.18", | ||
"@typescript-eslint/eslint-plugin": "^5.48.2", | ||
"@typescript-eslint/parser": "^5.48.2", | ||
"bun-types": "^0.5.0", | ||
"eslint": "^8.32.0", | ||
"rimraf": "^3.0.2", | ||
"typescript": "^4.9.4" | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Manifest confusion
Supply chain riskThis package has inconsistent metadata. This could be malicious or caused by an error when publishing the package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
56985
443
4
1
+ Addedsuperjson@^1.12.2
+ Addedcopy-anything@3.0.5(transitive)
+ Addedis-what@4.1.16(transitive)
+ Addedsuperjson@1.13.3(transitive)