ivl 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -112,8 +112,8 @@ export const LOGIN_SCHEMA: SCHEMA = {
112
112
  };
113
113
 
114
114
  export const REGISTER_SCHEMA: SCHEMA = {
115
- // We can pass in an empty rule set to allow any value
116
- // Or we can omit the argument entirely and set the strict flag to false when checking the schema
115
+ // We can pass in an empty rule set to allow any value
116
+ // Or we can omit the argument entirely and set the strict flag to false when checking the schema
117
117
  organization_name: {}
118
118
  email: {
119
119
  ...EMAIL_REQUIREMENTS,
@@ -137,17 +137,17 @@ export const INVITATION_PARAM: SCHEMA = {
137
137
 
138
138
  ### `index.ts`
139
139
  ```typescript
140
- import { Hono } from 'hono';
140
+ import { Hono, ValidationTargets } from 'hono';
141
141
  import { validator } from 'hono/validator';
142
142
  import { getSchemaErrors } from 'ivl';
143
143
  import { LOGIN_SCHEMA, REGISTER_SCHEMA, INVITE_REGISTER_SCHEMA, INVITATION_PARAM } from './rules.ts';
144
144
 
145
145
  // Wrapper for hono validator middleware
146
- const validateWrapper = async (input_type:string, schema: SCHEMA) =>
147
- validate(input_type, async (value: any, c: Context) => {
146
+ export const validate = (input_type: keyof ValidationTargets, schema: SCHEMA) =>
147
+ validator(input_type, async (value: CHECKABLE_OBJECT) => {
148
148
  const errors = await getSchemaErrors(value, schema, { strict: true });
149
149
  if (Object.values(errors).filter((e) => e.length).length) {
150
- throw new HTTPException(error, {
150
+ throw new HTTPException(400, {
151
151
  message: JSON.stringify(errors),
152
152
  });
153
153
  }
@@ -157,20 +157,20 @@ const validateWrapper = async (input_type:string, schema: SCHEMA) =>
157
157
  const app = new Hono();
158
158
 
159
159
  app.post('/login',
160
- validateWrapper('json', LOGIN_SCHEMA),
160
+ validate('json', LOGIN_SCHEMA),
161
161
  (c) => c.text("Success"));
162
162
 
163
163
  app.all('/logout', (c) => c.text("Success"));
164
164
 
165
165
  app.put('/register',
166
- validateWrapper('json', REGISTER_SCHEMA),
166
+ validate('json', REGISTER_SCHEMA),
167
167
  (c) => c.text("Success"));
168
168
 
169
169
  // This first validates the invitation parameter against our database
170
170
  // And then validates the body of the request
171
171
  app.put('/register/:invitation_code',
172
- validateWrapper('param', INVITATION_PARAM),
173
- validateWrapper('json', INVITE_REGISTER_SCHEMA ),
172
+ validate('param', INVITATION_PARAM),
173
+ validate('json', INVITE_REGISTER_SCHEMA ),
174
174
  (c)=> c.text("Success"));
175
175
 
176
176
  export default app;
@@ -13,9 +13,17 @@ export declare const maxLength: (max_length?: number) => RULE_SYNC;
13
13
  export declare const minLength: (min_length?: number) => RULE_SYNC;
14
14
  export declare const stringBetween: (max?: number, min?: number) => RULE_SYNC;
15
15
  export declare const numberBetween: (max?: number, min?: number) => RULE_SYNC;
16
- export declare const acceptAny: (rules?: RULE[]) => RULE;
16
+ export declare const acceptAnyAsync: (rules?: RULE[]) => RULE;
17
17
  export declare const acceptAnySync: (rules?: RULE_SYNC[]) => RULE_SYNC;
18
- export declare const allowUndefined: (rules: RULES) => {};
19
- export declare const preprocess: (fn: Function, rules: RULES) => {};
18
+ declare const allowUndefined: (rules: RULES) => {};
19
+ declare const preprocess: (fn: Function, rules: RULES) => {};
20
+
21
+ declare namespace ruleSet {
22
+ export { allowUndefined, preprocess };
23
+ }
24
+
25
+ export {
26
+ ruleSet,
27
+ };
20
28
 
21
29
  export {};
@@ -1 +1 @@
1
- var s=(n)=>typeof n==="string"||n!==null&&typeof n==="object"&&("length"in n)&&typeof n.length==="number",c=(n)=>(e)=>typeof e===n,i=(n)=>(e)=>typeof e==="string"&&n.test(e),f=(n=1/0)=>(e)=>typeof e==="number"&&e<=n,m=(n=-1/0)=>(e)=>typeof e==="number"&&e>=n,y=(n=1/0)=>(e)=>s(e)&&e.length<=n,w=(n=0)=>(e)=>s(e)&&e.length>=n,a=(n=1/0,e=0)=>(t)=>typeof t==="string"&&t.length>=e&&t.length<=n,L=(n=1/0,e=-1/0)=>(t)=>typeof t==="number"&&t>=e&&t<=n,g=(n=[])=>async(e,...t)=>(await Promise.all(n.map((o)=>o(void 0,e,...t)))).some((o)=>o),h=(n=[])=>(e,...t)=>n.map((o)=>o(void 0,e,...t)).some((o)=>o);var l=(n)=>Object.entries(n).reduce((e,[t,o])=>({...e,[t]:(r,...u)=>typeof r==="undefined"?!0:o(r,...u)}),{}),x=(n,e)=>Object.entries(e).reduce((t,[o,r])=>({...t,[o]:(u,...p)=>r(n(u),...p)}),{});export{a as stringBetween,x as preprocess,L as numberBetween,w as minLength,m as min,y as maxLength,f as max,i as matchesRegex,c as isType,l as allowUndefined,h as acceptAnySync,g as acceptAny};
1
+ var i=Object.defineProperty;var m=(e,n)=>{for(var t in n)i(e,t,{get:n[t],enumerable:!0,configurable:!0,set:(o)=>n[t]=()=>o})};var u=(e)=>typeof e==="string"||e!==null&&typeof e==="object"&&("length"in e)&&typeof e.length==="number",a=(e)=>(n)=>typeof n===e,L=(e)=>(n)=>typeof n==="string"&&e.test(n),g=(e=1/0)=>(n)=>typeof n==="number"&&n<=e,h=(e=-1/0)=>(n)=>typeof n==="number"&&n>=e,l=(e=1/0)=>(n)=>u(n)&&n.length<=e,R=(e=0)=>(n)=>u(n)&&n.length>=e,x=(e=1/0,n=0)=>(t)=>typeof t==="string"&&t.length>=n&&t.length<=e,E=(e=1/0,n=-1/0)=>(t)=>typeof t==="number"&&t>=n&&t<=e,U=(e=[])=>async(n,...t)=>(await Promise.all(e.map((o)=>o(n,...t)))).some((o)=>o),b=(e=[])=>(n,...t)=>e.map((o)=>o(n,...t)).some((o)=>o);var p={};m(p,{preprocess:()=>f,allowUndefined:()=>y});var y=(e)=>Object.entries(e).reduce((n,[t,o])=>({...n,[t]:(r,...s)=>typeof r==="undefined"?!0:o(r,...s)}),{}),f=(e,n)=>Object.entries(n).reduce((t,[o,r])=>({...t,[o]:(s,...c)=>r(e(s),...c)}),{});export{x as stringBetween,p as ruleSet,E as numberBetween,R as minLength,h as min,l as maxLength,g as max,L as matchesRegex,a as isType,b as acceptAnySync,U as acceptAnyAsync};
package/lib/index.d.ts CHANGED
@@ -9,31 +9,31 @@ export type RULES = {
9
9
  [index: string]: RULE;
10
10
  };
11
11
  export type SCHEMA_SYNC = {
12
- [index: string]: RULES_SYNC;
12
+ [index: string]: RULES_SYNC | RULES_SYNC[];
13
13
  };
14
14
  export type SCHEMA = {
15
- [index: string]: RULES;
16
- };
17
- export type CHECKABLE_OBJECT = {
18
- [index: string]: unknown;
15
+ [index: string]: RULES | RULES[];
19
16
  };
20
17
  /**
21
18
  * @arg {boolean} strict --- Don't allow object to have keys not included in the schema
22
- */
19
+ */
23
20
  export type SCHEMA_OPTIONS = {
24
21
  strict?: boolean;
25
22
  };
26
- export type CHECKED_SCHEMA_SYNC = {
27
- [index: string]: string[];
23
+ export type CHECKABLE_OBJECT = {
24
+ [index: string]: unknown;
28
25
  };
29
- export type CHECKED_SCHEMA = Promise<CHECKED_SCHEMA_SYNC>;
26
+ export type CHECKED_SCHEMA_SYNC<T extends keyof CHECKABLE_OBJECT> = {
27
+ [K in T]: string[] | string[][];
28
+ };
29
+ export type CHECKED_SCHEMA<T extends keyof CHECKABLE_OBJECT> = Promise<CHECKED_SCHEMA_SYNC<T>>;
30
30
  /**
31
31
  * Detect if a RULES object has any async rules in it
32
32
  *
33
- * @param {Record<string, RULE>} rules a rules object
33
+ * @param {Record<string, RULE>|Record<string, RULE>[]} rules a rules object
34
34
  * @returns {boolean} true if any of the rules is an async function otherwise false
35
35
  */
36
- export declare const hasAsyncFunction: (rules: Record<string, RULE>) => boolean;
36
+ export declare const hasAsyncFunction: (rules: Record<string, RULE> | Record<string, RULE>[]) => boolean;
37
37
  /**
38
38
  * Check the input against all provided validation rules asynchronously
39
39
  *
@@ -46,13 +46,15 @@ export declare const getValueErrorsAsync: (value: unknown, rules: RULES, ...over
46
46
  /**
47
47
  * Check a schema against all provided validation rules asynchronously
48
48
  *
49
- * @param {CHECKABLE_OBJECT} object object to be validated
49
+ * @param {CHECKABLE_OBJECT} object_to_check object to be validated
50
50
  * @param {SCHEMA} schema schema to validate against
51
51
  * @param {SCHEMA_OPTIONS} options options affecting how the rules are run
52
52
  * @param {unknown[]} overload array of extra values the validator rules might need to properly validate the value
53
- * @returns {CHECKED_SCHEMA} an object containing keys and their respective lists of failed rule names
53
+ * @returns {CHECKED_SCHEMA<T>} an object containing keys and their respective lists of failed rule names
54
54
  */
55
- export declare const getSchemaErrorsAsync: (object: CHECKABLE_OBJECT, schema: SCHEMA, options?: SCHEMA_OPTIONS, ...overload: unknown[]) => CHECKED_SCHEMA;
55
+ export declare const getSchemaErrorsAsync: <T extends keyof CHECKABLE_OBJECT>(object_to_check: Pick<CHECKABLE_OBJECT, T>, schema: {
56
+ [K in T]: RULES | RULES[];
57
+ }, options?: SCHEMA_OPTIONS, ...overload: unknown[]) => Promise<CHECKED_SCHEMA_SYNC<T>>;
56
58
  /**
57
59
  *
58
60
  * @param {unknown} value the value to check
@@ -68,26 +70,25 @@ export declare const getValueErrorsSync: (value: unknown, rules: RULES_SYNC, ...
68
70
  * @param {SCHEMA} schema schema to validate against
69
71
  * @param {SCHEMA_OPTIONS} options options affecting how the rules are run
70
72
  * @param {unknown[]} overload array of extra values the validator rules might need to properly validate the value
71
- * @returns {CHECKED_SCHEMA} an object containing keys and their respective lists of failed rule names
73
+ * @returns {CHECKED_SCHEMA_SYNC<T>} an object containing keys and their respective lists of failed rule names
72
74
  */
73
- export declare const getSchemaErrorsSync: (object: CHECKABLE_OBJECT, schema: SCHEMA_SYNC, options?: SCHEMA_OPTIONS, ...overload: unknown[]) => CHECKED_SCHEMA_SYNC;
75
+ export declare const getSchemaErrorsSync: <T extends keyof CHECKABLE_OBJECT>(object: CHECKABLE_OBJECT, schema: SCHEMA_SYNC, options?: SCHEMA_OPTIONS, ...overload: unknown[]) => CHECKED_SCHEMA_SYNC<T>;
74
76
  /**
75
- *
76
77
  * @param {unknown} value the value to check
77
78
  * @param {RULES|RULES_SYNC} rules rules object to use for validating the provided value
78
79
  * @param {unknown[]} overload array of extra values the validator rules might need to properly validate the value
79
- * @returns {string[]} a list of rule names which failed validation
80
+ * @returns {Promise<string[]>|string[]} a list of rule names which failed validation
80
81
  */
81
- export declare const getValueErrors: (value: unknown, rules: RULES | RULES_SYNC, ...overload: unknown[]) => string[] | Promise<string[]>;
82
+ export declare const getValueErrors: (value: unknown, rules: RULES | RULES_SYNC, ...overload: unknown[]) => Promise<string[]> | string[];
82
83
  /**
83
84
  * Check a schema against all provided validation rules
84
85
  *
85
86
  * @param {CHECKABLE_OBJECT} object object to be validated
86
- * @param {SCHEMA} schema schema to validate against
87
+ * @param {SCHEMA|SCHEMA_SYNC} schema schema to validate against
87
88
  * @param {SCHEMA_OPTIONS} options options affecting how the rules are run
88
89
  * @param {unknown[]} overload array of extra values the validator rules might need to properly validate the value
89
90
  * @returns {CHECKED_SCHEMA} an object containing keys and their respective lists of failed rule names
90
91
  */
91
- export declare const getSchemaErrors: (object: CHECKABLE_OBJECT, schema: SCHEMA_SYNC | SCHEMA, options?: SCHEMA_OPTIONS, ...overload: unknown[]) => CHECKED_SCHEMA_SYNC | CHECKED_SCHEMA;
92
+ export declare const getSchemaErrors: <T extends keyof CHECKABLE_OBJECT>(object: CHECKABLE_OBJECT, schema: SCHEMA_SYNC | SCHEMA, options?: SCHEMA_OPTIONS, ...overload: unknown[]) => CHECKED_SCHEMA<T> | CHECKED_SCHEMA_SYNC<T>;
92
93
 
93
94
  export {};
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- var Z={strict:!1},$=(z)=>Object.values(z).some((q)=>typeof q==="function"&&q.constructor.name==="AsyncFunction"),J=async(z,q,...W)=>{const G={};return Object.entries(q).forEach(([x,Q])=>{G[x]=Promise.resolve(!1).then(()=>Q(z,...W)).then((R)=>G[x]=R).catch((R)=>{return console.warn(`Rule validation functions for "${x}" didn't exit cleanly`,R),G[x]=!1})}),await Promise.allSettled(Object.values(G)),Object.entries(G).reduce((x,[Q,R])=>R?x:[...x,Q],[])},K=async(z,q,W=Z,...G)=>{const x={};if(Object.entries(q).forEach(([Q,R])=>{x[Q]=J(z[Q],R,...G).then((X)=>{x[Q]=X}).catch((X)=>{x[Q]=X})}),W.strict){const Q=Object.keys(z),R=new Set(Object.keys(q));Q.filter((Y)=>!R.has(Y)).forEach((Y)=>{x[Y]=["Key not allowed"]})}return await Promise.allSettled(Object.values(x)),x},B=(z,q,...W)=>Object.entries(q).reduce((G,[x,Q])=>{try{return Q(z,...W)?G:[...G,x]}catch(R){return console.warn(`Rule validation function for "${x}" didn't exit cleanly`,R),[...G,x]}},[]),f=(z,q,W=Z,...G)=>{const x=Object.entries(q).reduce((Q,[R,X])=>({...Q,[R]:B(z[R],X,...G)}),{});if(W.strict){const Q=Object.keys(z),R=new Set(Object.keys(q));Q.filter((Y)=>!R.has(Y)).forEach((Y)=>{x[Y]=["Key not allowed"]})}return x},U=(z,q,...W)=>{if($(q))return J(z,q,...W);return B(z,q,...W)},I=(z,q,W=Z,...G)=>{if(Object.values(q).some($))return K(z,q,W,...G);return f(z,q,W,...G)};export{$ as hasAsyncFunction,B as getValueErrorsSync,J as getValueErrorsAsync,U as getValueErrors,f as getSchemaErrorsSync,K as getSchemaErrorsAsync,I as getSchemaErrors};
1
+ var K={strict:!1},U=(x)=>{if(Array.isArray(x))return x.some((z)=>Object.values(z).some((W)=>typeof W==="function"&&W.constructor.name==="AsyncFunction"));return Object.values(x).some((z)=>typeof z==="function"&&z.constructor.name==="AsyncFunction")},Y=async(x,z,...W)=>{const Q={};return Object.entries(z).forEach(([G,X])=>{Q[G]=Promise.resolve(!1).then(()=>X(x,...W)).then((q)=>Q[G]=q).catch(()=>{return Q[G]=!1})}),await Promise.allSettled(Object.values(Q)),Object.entries(Q).reduce((G,[X,q])=>q?G:[...G,X],[])},I=async(x,z,W=K,...Q)=>{const G={},X=[];if(Object.entries(z).forEach(([q,$])=>{let Z;if(Array.isArray($))Z=Promise.allSettled($.map((R)=>Y(x[q],R,...Q))).then((R)=>{const f=R.map((J)=>{if(J.status==="fulfilled")return J.value;return["Unknown error occurred"]},[]);if(f.some((J)=>!J.length))G[q]=[];else G[q]=f}).catch((R)=>{if(R instanceof Error)G[q]=[R.message];else G[q]=["Unknown error occurred"]});else Z=Y(x[q],$,...Q).then((R)=>{G[q]=R}).catch((R)=>{G[q]=R});X.push(Z)}),W.strict){const q=Object.keys(x),$=new Set(Object.keys(z));q.filter((R)=>!$.has(R)).forEach((R)=>{G[R]=["Key not allowed"]})}return await Promise.allSettled(X),G},B=(x,z,...W)=>Object.entries(z).reduce((Q,[G,X])=>{try{return X(x,...W)?Q:[...Q,G]}catch(q){return[...Q,G]}},[]),L=(x,z,W=K,...Q)=>{const G=Object.entries(z).reduce((X,[q,$])=>{if(Array.isArray($)){const Z=$.map((R)=>B(x[q],R,...Q));if(Z.some((R)=>!R.length))return{...X,[q]:[]};return{...X,[q]:Z}}return{...X,[q]:B(x[q],$,...Q)}},{});if(W.strict){const X=Object.keys(x),q=new Set(Object.keys(z));X.filter((Z)=>!q.has(Z)).forEach((Z)=>{G[Z]=["Key not allowed"]})}return G},D=(x,z,...W)=>{if(U(z))return Y(x,z,...W);return B(x,z,...W)},w=(x)=>Object.values(x).some(U),F=(x,z,W=K,...Q)=>{if(w(z))return I(x,z,W,...Q);return L(x,z,W,...Q)};export{U as hasAsyncFunction,B as getValueErrorsSync,Y as getValueErrorsAsync,D as getValueErrors,L as getSchemaErrorsSync,I as getSchemaErrorsAsync,F as getSchemaErrors};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ivl",
3
- "version": "0.2.7",
3
+ "version": "0.3.0",
4
4
  "author": {
5
5
  "name": "Oskar Voorel",
6
6
  "email": "oskar@voorel.com"