@kairojsmodule/validation 0.0.0-stage → 1.1.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/index.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ export declare class ValidationError extends Error {
2
+ status: number;
3
+ statusCode: number;
4
+ code: string;
5
+ errors: Record<string, string[]>;
6
+ constructor(errors?: Record<string, string[]>);
7
+ }
8
+
9
+ export declare class Rule {
10
+ required(): this;
11
+ optional(): this;
12
+ string(): this;
13
+ number(): this;
14
+ integer(): this;
15
+ boolean(): this;
16
+ email(): this;
17
+ min(limit: number): this;
18
+ max(limit: number): this;
19
+ enum(values: any[]): this;
20
+ regex(pattern: RegExp | string): this;
21
+ custom(fn: (val: any, field: string) => string | void): this;
22
+ validate(field: string, val: any): string[];
23
+ }
24
+
25
+ export declare class Validator {
26
+ constructor(schema?: Record<string, Rule>);
27
+ static schema(definition?: Record<string, Rule>): Validator;
28
+ static rule(): Rule;
29
+ static string(): Rule;
30
+ static number(): Rule;
31
+ static integer(): Rule;
32
+ static boolean(): Rule;
33
+ static email(): Rule;
34
+ check(data?: Record<string, any>): { valid: boolean; errors: Record<string, string[]>; data: Record<string, any> };
35
+ validate(data?: Record<string, any>): Record<string, any>;
36
+ }
37
+
38
+ export declare function validate(validatorOrSchema: Validator | Record<string, Rule>): (ctx: any, next: () => Promise<void>) => Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@kairojsmodule/validation",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Fluent schema validator and 422 middleware for KairoJS",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": "./src/index.js"
10
+ },
11
+ "keywords": [
12
+ "kairojs",
13
+ "validation",
14
+ "schema",
15
+ "sanitization"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "author": "Riski Ardiane <@kairojsmodule>"
21
+ }
package/src/Rule.js ADDED
@@ -0,0 +1,137 @@
1
+ export class Rule {
2
+ constructor() {
3
+ this._required = false;
4
+ this._type = null;
5
+ this._min = null;
6
+ this._max = null;
7
+ this._enum = null;
8
+ this._regex = null;
9
+ this._email = false;
10
+ this._customValidators = [];
11
+ }
12
+
13
+ required() {
14
+ this._required = true;
15
+ return this;
16
+ }
17
+
18
+ optional() {
19
+ this._required = false;
20
+ return this;
21
+ }
22
+
23
+ string() {
24
+ this._type = 'string';
25
+ return this;
26
+ }
27
+
28
+ number() {
29
+ this._type = 'number';
30
+ return this;
31
+ }
32
+
33
+ integer() {
34
+ this._type = 'integer';
35
+ return this;
36
+ }
37
+
38
+ boolean() {
39
+ this._type = 'boolean';
40
+ return this;
41
+ }
42
+
43
+ email() {
44
+ this._type = 'string';
45
+ this._email = true;
46
+ return this;
47
+ }
48
+
49
+ min(limit) {
50
+ this._min = limit;
51
+ return this;
52
+ }
53
+
54
+ max(limit) {
55
+ this._max = limit;
56
+ return this;
57
+ }
58
+
59
+ enum(values) {
60
+ this._enum = Array.isArray(values) ? values : [values];
61
+ return this;
62
+ }
63
+
64
+ regex(pattern) {
65
+ this._regex = pattern instanceof RegExp ? pattern : new RegExp(pattern);
66
+ return this;
67
+ }
68
+
69
+ custom(fn) {
70
+ this._customValidators.push(fn);
71
+ return this;
72
+ }
73
+
74
+ validate(field, val) {
75
+ const errors = [];
76
+
77
+ // Required check
78
+ if (val === undefined || val === null || val === '') {
79
+ if (this._required) {
80
+ errors.push(`${field} is required.`);
81
+ }
82
+ return errors;
83
+ }
84
+
85
+ // Type checks
86
+ if (this._type === 'string') {
87
+ if (typeof val !== 'string') {
88
+ errors.push(`${field} must be a string.`);
89
+ } else {
90
+ if (this._email) {
91
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
92
+ if (!emailRegex.test(val)) {
93
+ errors.push(`${field} must be a valid email address.`);
94
+ }
95
+ }
96
+ if (this._min !== null && val.length < this._min) {
97
+ errors.push(`${field} must be at least ${this._min} characters.`);
98
+ }
99
+ if (this._max !== null && val.length > this._max) {
100
+ errors.push(`${field} must not exceed ${this._max} characters.`);
101
+ }
102
+ if (this._regex && !this._regex.test(val)) {
103
+ errors.push(`${field} format is invalid.`);
104
+ }
105
+ }
106
+ } else if (this._type === 'number' || this._type === 'integer') {
107
+ const num = Number(val);
108
+ if (Number.isNaN(num)) {
109
+ errors.push(`${field} must be a number.`);
110
+ } else if (this._type === 'integer' && !Number.isInteger(num)) {
111
+ errors.push(`${field} must be an integer.`);
112
+ } else {
113
+ if (this._min !== null && num < this._min) {
114
+ errors.push(`${field} must be at least ${this._min}.`);
115
+ }
116
+ if (this._max !== null && num > this._max) {
117
+ errors.push(`${field} must not exceed ${this._max}.`);
118
+ }
119
+ }
120
+ } else if (this._type === 'boolean') {
121
+ if (typeof val !== 'boolean' && val !== 'true' && val !== 'false' && val !== 0 && val !== 1) {
122
+ errors.push(`${field} must be a boolean.`);
123
+ }
124
+ }
125
+
126
+ if (this._enum && !this._enum.includes(val)) {
127
+ errors.push(`${field} must be one of: ${this._enum.join(', ')}.`);
128
+ }
129
+
130
+ for (const customFn of this._customValidators) {
131
+ const customErr = customFn(val, field);
132
+ if (customErr) errors.push(customErr);
133
+ }
134
+
135
+ return errors;
136
+ }
137
+ }
package/src/Schema.js ADDED
@@ -0,0 +1,70 @@
1
+ import { Rule } from './Rule.js';
2
+ import { ValidationError } from './ValidationError.js';
3
+
4
+ export class Validator {
5
+ constructor(schema = {}) {
6
+ this.schema = schema;
7
+ }
8
+
9
+ static schema(definition = {}) {
10
+ return new Validator(definition);
11
+ }
12
+
13
+ static rule() {
14
+ return new Rule();
15
+ }
16
+
17
+ static string() {
18
+ return new Rule().string();
19
+ }
20
+
21
+ static number() {
22
+ return new Rule().number();
23
+ }
24
+
25
+ static integer() {
26
+ return new Rule().integer();
27
+ }
28
+
29
+ static boolean() {
30
+ return new Rule().boolean();
31
+ }
32
+
33
+ static email() {
34
+ return new Rule().email();
35
+ }
36
+
37
+ /**
38
+ * Validate data against the schema.
39
+ * @param {Record<string, any>} data
40
+ * @returns {{ valid: boolean, errors: Record<string, string[]>, data: Record<string, any> }}
41
+ */
42
+ check(data = {}) {
43
+ const errors = {};
44
+ let valid = true;
45
+
46
+ for (const [field, rule] of Object.entries(this.schema)) {
47
+ const val = data[field];
48
+ const fieldErrors = rule.validate(field, val);
49
+ if (fieldErrors.length > 0) {
50
+ valid = false;
51
+ errors[field] = fieldErrors;
52
+ }
53
+ }
54
+
55
+ return { valid, errors, data };
56
+ }
57
+
58
+ /**
59
+ * Validate data, throwing a ValidationError on failure.
60
+ * @param {Record<string, any>} data
61
+ * @returns {Record<string, any>} Validated data
62
+ */
63
+ validate(data = {}) {
64
+ const { valid, errors } = this.check(data);
65
+ if (!valid) {
66
+ throw new ValidationError(errors);
67
+ }
68
+ return data;
69
+ }
70
+ }
@@ -0,0 +1,10 @@
1
+ export class ValidationError extends Error {
2
+ constructor(errors = {}) {
3
+ super('The given data was invalid.');
4
+ this.name = 'ValidationError';
5
+ this.status = 422;
6
+ this.statusCode = 422;
7
+ this.code = 'VALIDATION_ERROR';
8
+ this.errors = errors;
9
+ }
10
+ }
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { Rule } from './Rule.js';
2
+ export { Validator } from './Schema.js';
3
+ export { ValidationError } from './ValidationError.js';
4
+ export { validate } from './middleware.js';
@@ -0,0 +1,33 @@
1
+ import { Validator } from './Schema.js';
2
+
3
+ /**
4
+ * Middleware that validates request body against a schema.
5
+ * Intercepts invalid requests and responds with HTTP status 422.
6
+ * @param {Validator|Record<string, any>} validatorOrSchema
7
+ */
8
+ export function validate(validatorOrSchema) {
9
+ const validator = validatorOrSchema instanceof Validator ? validatorOrSchema : Validator.schema(validatorOrSchema);
10
+
11
+ return async (ctx, next) => {
12
+ let body = {};
13
+ if (typeof ctx.req.body === 'function') {
14
+ body = await ctx.req.body();
15
+ } else {
16
+ body = ctx.req.body || {};
17
+ }
18
+
19
+ const { valid, errors } = validator.check(body);
20
+ if (!valid) {
21
+ ctx.res.status(422).json({
22
+ error: {
23
+ code: 'VALIDATION_ERROR',
24
+ message: 'The given data was invalid.',
25
+ errors
26
+ }
27
+ });
28
+ return;
29
+ }
30
+
31
+ await next();
32
+ };
33
+ }
@@ -0,0 +1,84 @@
1
+ import { test, describe } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { Validator, validate, ValidationError } from '../src/index.js';
4
+
5
+ describe('Validator', () => {
6
+ test('validates valid input according to rules', () => {
7
+ const validator = Validator.schema({
8
+ email: Validator.email().required(),
9
+ age: Validator.integer().min(18).required(),
10
+ role: Validator.string().enum(['admin', 'user', 'guest']),
11
+ bio: Validator.string().max(100).optional()
12
+ });
13
+
14
+ const data = {
15
+ email: 'john@example.com',
16
+ age: 25,
17
+ role: 'admin',
18
+ bio: 'Developer at KairoJS'
19
+ };
20
+
21
+ const res = validator.check(data);
22
+ assert.equal(res.valid, true);
23
+ assert.deepEqual(res.errors, {});
24
+ });
25
+
26
+ test('reports structured errors on validation failure', () => {
27
+ const validator = Validator.schema({
28
+ email: Validator.email().required(),
29
+ age: Validator.integer().min(18).required(),
30
+ role: Validator.string().enum(['admin', 'user'])
31
+ });
32
+
33
+ const data = {
34
+ email: 'not-an-email',
35
+ age: 15,
36
+ role: 'superman'
37
+ };
38
+
39
+ const res = validator.check(data);
40
+ assert.equal(res.valid, false);
41
+ assert.ok(res.errors.email);
42
+ assert.ok(res.errors.age);
43
+ assert.ok(res.errors.role);
44
+ assert.match(res.errors.email[0], /valid email address/);
45
+ assert.match(res.errors.age[0], /at least 18/);
46
+ assert.match(res.errors.role[0], /must be one of: admin, user/);
47
+
48
+ assert.throws(() => validator.validate(data), ValidationError);
49
+ });
50
+
51
+ test('validate middleware returns 422 for invalid body', async () => {
52
+ const mw = validate({
53
+ name: Validator.string().required(),
54
+ email: Validator.email().required()
55
+ });
56
+
57
+ const ctx = {
58
+ req: {
59
+ body: async () => ({ name: 'John', email: 'invalid' })
60
+ },
61
+ res: {
62
+ statusCode: 200,
63
+ status(code) {
64
+ this.statusCode = code;
65
+ return this;
66
+ },
67
+ json(data) {
68
+ this.body = data;
69
+ return this;
70
+ }
71
+ }
72
+ };
73
+
74
+ let nextCalled = false;
75
+ await mw(ctx, async () => {
76
+ nextCalled = true;
77
+ });
78
+
79
+ assert.equal(nextCalled, false);
80
+ assert.equal(ctx.res.statusCode, 422);
81
+ assert.equal(ctx.res.body.error.code, 'VALIDATION_ERROR');
82
+ assert.ok(ctx.res.body.error.errors.email);
83
+ });
84
+ });
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.