@esmj/schema 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+
2
+ Copyright 2025 Miroslav Jancarik jancarikmiroslav@gmail.com
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,162 @@
1
+ # Schema
2
+
3
+ This small library provides a simple schema validation system for JavaScript/TypeScript. The library has basic types with opportunity for extending.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install @esmj/schema
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Basic Usage
14
+
15
+ ```typescript
16
+ import { s } from '@esmj/schema';
17
+
18
+ const schema = s.object({
19
+ username: s.string().optional(),
20
+ password: s.string().default('unknown'),
21
+ account: s.number().default(0),
22
+ address: s.object({
23
+ street: s.string(),
24
+ city: s.string().optional(),
25
+ }).default({ street: 'unknown' }),
26
+ records: s.array(s.object({ name: s.string() })).default([]),
27
+ });
28
+
29
+ const result = schema.parse({
30
+ username: 'john_doe',
31
+ address: { city: 'New York' },
32
+ });
33
+
34
+ console.log(result);
35
+ ```
36
+
37
+ ### Schema Types
38
+
39
+ #### `s.string()`
40
+
41
+ Creates a string schema.
42
+
43
+ ```typescript
44
+ const stringSchema = s.string();
45
+ ```
46
+
47
+ #### `s.number()`
48
+
49
+ Creates a number schema.
50
+
51
+ ```typescript
52
+ const numberSchema = s.number();
53
+ ```
54
+
55
+ #### `s.boolean()`
56
+
57
+ Creates a boolean schema.
58
+
59
+ ```typescript
60
+ const booleanSchema = s.boolean();
61
+ ```
62
+
63
+ #### `s.object(definition)`
64
+
65
+ Creates an object schema with the given definition.
66
+
67
+ ```typescript
68
+ const objectSchema = s.object({
69
+ key: s.string(),
70
+ value: s.number(),
71
+ });
72
+ ```
73
+
74
+ #### `s.array(definition)`
75
+
76
+ Creates an array schema with the given item definition.
77
+
78
+ ```typescript
79
+ const arraySchema = s.array(s.string());
80
+ ```
81
+
82
+ #### `s.any()`
83
+
84
+ Creates a schema that accepts any value.
85
+
86
+ ```typescript
87
+ const anySchema = s.any();
88
+ ```
89
+
90
+ ### Schema Methods
91
+
92
+ #### `parse(value)`
93
+
94
+ Parses the given value according to the schema.
95
+
96
+ ```typescript
97
+ const result = stringSchema.parse('hello');
98
+ ```
99
+
100
+ #### `safeParse(value)`
101
+
102
+ Safely parses the given value according to the schema, returning a success or error result.
103
+
104
+ ```typescript
105
+ // correct
106
+ const result = stringSchema.safeParse('hello'); // { success: true, data: 'hello' };
107
+ // bad
108
+ const result = stringSchema.safeParse('hello'); // { success: false, error: new Error() };
109
+ ```
110
+
111
+ #### `optional()`
112
+
113
+ Makes the schema optional.
114
+
115
+ ```typescript
116
+ const optionalSchema = stringSchema.optional();
117
+ ```
118
+
119
+ #### `nullable()`
120
+
121
+ Makes the schema nullable.
122
+
123
+ ```typescript
124
+ const nullableSchema = stringSchema.nullable();
125
+ ```
126
+
127
+ #### `nullish()`
128
+
129
+ Makes the schema nullish (nullable and optional).
130
+
131
+ ```typescript
132
+ const nullishSchema = stringSchema.nullish();
133
+ ```
134
+
135
+ #### `default(defaultValue)`
136
+
137
+ Sets a default value for the schema.
138
+
139
+ ```typescript
140
+ const defaultSchema = stringSchema.default('default value');
141
+ ```
142
+
143
+ ### Extending Schemas
144
+
145
+ You can extend the schema system with custom logic.
146
+
147
+ ```typescript
148
+ import { extend } from '@esmj/schema';
149
+
150
+ extend((schema, validation, options) => {
151
+ schema.customMethod = () => {
152
+ // Custom logic
153
+ };
154
+
155
+ return schema;
156
+ });
157
+ ```
158
+
159
+ ## License
160
+
161
+ MIT
162
+
package/biome.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "files": {
3
+ "include": ["src/**/*.mjs", "src/**/*.ts", "utils/**/*.mjs"],
4
+ "ignore": [".history/**/*"]
5
+ },
6
+ "formatter": {
7
+ "enabled": true,
8
+ "formatWithErrors": true,
9
+ "indentStyle": "space",
10
+ "indentWidth": 2,
11
+ "lineEnding": "lf",
12
+ "lineWidth": 80,
13
+ "attributePosition": "auto"
14
+ },
15
+ "organizeImports": { "enabled": true },
16
+ "linter": {
17
+ "enabled": true,
18
+ "rules": {
19
+ "recommended": true,
20
+ "complexity": {
21
+ "noForEach": "off",
22
+ "noBannedTypes": "off"
23
+ },
24
+ "style": {
25
+ "noParameterAssign": "off"
26
+ }
27
+ }
28
+ },
29
+ "javascript": {
30
+ "formatter": {
31
+ "jsxQuoteStyle": "double",
32
+ "quoteProperties": "asNeeded",
33
+ "trailingCommas": "all",
34
+ "semicolons": "always",
35
+ "arrowParentheses": "always",
36
+ "bracketSpacing": true,
37
+ "bracketSameLine": false,
38
+ "quoteStyle": "single",
39
+ "attributePosition": "auto"
40
+ }
41
+ },
42
+ "overrides": [
43
+ {
44
+ "include": ["*.json"],
45
+ "formatter": {
46
+ "indentWidth": 2
47
+ }
48
+ }
49
+ ]
50
+ }
@@ -0,0 +1,26 @@
1
+ interface SchemaInterface<Input, Output> {
2
+ parse(value: Input | Partial<Input> | unknown): Output;
3
+ safeParse(value: Input | Partial<Input> | unknown): {
4
+ success: true;
5
+ data: Output;
6
+ } | {
7
+ success: false;
8
+ error: Error;
9
+ };
10
+ optional(): SchemaInterface<Input, Partial<Output> | undefined>;
11
+ nullable(): SchemaInterface<Input, Output | null>;
12
+ nullish(): SchemaInterface<Input, Output | undefined | null>;
13
+ default(defaultValue: Partial<Input> | (() => Partial<Input>) | Partial<Output>): SchemaInterface<Input, Output>;
14
+ }
15
+ type SchemaType = SchemaInterface<string, string> | SchemaInterface<string, string | undefined> | SchemaInterface<string, string | null> | SchemaInterface<string, string | undefined | null> | SchemaInterface<object, object> | SchemaInterface<object, object | undefined> | SchemaInterface<object, object | null> | SchemaInterface<object, object | undefined | null> | SchemaInterface<number, number> | SchemaInterface<number, number | undefined> | SchemaInterface<number, number | null> | SchemaInterface<number, number | undefined | null> | SchemaInterface<boolean, boolean> | SchemaInterface<boolean, boolean | undefined> | SchemaInterface<boolean, boolean | null> | SchemaInterface<boolean, boolean | undefined | null> | SchemaInterface<Array<unknown>, Array<unknown>> | SchemaInterface<Array<unknown>, Array<unknown> | undefined> | SchemaInterface<Array<unknown>, Array<unknown> | null> | SchemaInterface<Array<unknown>, Array<unknown> | undefined | null>;
16
+ declare const s: {
17
+ object<T extends Record<string, SchemaType>>(definition: { [Property in keyof T]: T[Property]; }): SchemaInterface<{ [Property in keyof T]: T[Property]; }, { [Property in keyof T]: ReturnType<T[Property]["parse"]>; }>;
18
+ string(): SchemaInterface<string, string>;
19
+ number(): SchemaInterface<number, number>;
20
+ boolean(): SchemaInterface<boolean, boolean>;
21
+ array<T extends SchemaType>(definition: T): SchemaInterface<Array<T>, Array<ReturnType<T["parse"]>>>;
22
+ any(): any;
23
+ };
24
+ declare function extend(callback: Function): void;
25
+
26
+ export { type SchemaInterface, type SchemaType, extend, s };
@@ -0,0 +1,26 @@
1
+ interface SchemaInterface<Input, Output> {
2
+ parse(value: Input | Partial<Input> | unknown): Output;
3
+ safeParse(value: Input | Partial<Input> | unknown): {
4
+ success: true;
5
+ data: Output;
6
+ } | {
7
+ success: false;
8
+ error: Error;
9
+ };
10
+ optional(): SchemaInterface<Input, Partial<Output> | undefined>;
11
+ nullable(): SchemaInterface<Input, Output | null>;
12
+ nullish(): SchemaInterface<Input, Output | undefined | null>;
13
+ default(defaultValue: Partial<Input> | (() => Partial<Input>) | Partial<Output>): SchemaInterface<Input, Output>;
14
+ }
15
+ type SchemaType = SchemaInterface<string, string> | SchemaInterface<string, string | undefined> | SchemaInterface<string, string | null> | SchemaInterface<string, string | undefined | null> | SchemaInterface<object, object> | SchemaInterface<object, object | undefined> | SchemaInterface<object, object | null> | SchemaInterface<object, object | undefined | null> | SchemaInterface<number, number> | SchemaInterface<number, number | undefined> | SchemaInterface<number, number | null> | SchemaInterface<number, number | undefined | null> | SchemaInterface<boolean, boolean> | SchemaInterface<boolean, boolean | undefined> | SchemaInterface<boolean, boolean | null> | SchemaInterface<boolean, boolean | undefined | null> | SchemaInterface<Array<unknown>, Array<unknown>> | SchemaInterface<Array<unknown>, Array<unknown> | undefined> | SchemaInterface<Array<unknown>, Array<unknown> | null> | SchemaInterface<Array<unknown>, Array<unknown> | undefined | null>;
16
+ declare const s: {
17
+ object<T extends Record<string, SchemaType>>(definition: { [Property in keyof T]: T[Property]; }): SchemaInterface<{ [Property in keyof T]: T[Property]; }, { [Property in keyof T]: ReturnType<T[Property]["parse"]>; }>;
18
+ string(): SchemaInterface<string, string>;
19
+ number(): SchemaInterface<number, number>;
20
+ boolean(): SchemaInterface<boolean, boolean>;
21
+ array<T extends SchemaType>(definition: T): SchemaInterface<Array<T>, Array<ReturnType<T["parse"]>>>;
22
+ any(): any;
23
+ };
24
+ declare function extend(callback: Function): void;
25
+
26
+ export { type SchemaInterface, type SchemaType, extend, s };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ 'use strict';var l={object(t){let c=s(u=>typeof u=="object"&&u!==null&&!Array.isArray(u),{type:"object"});return i(c,"parse",(u,...o)=>{let e=u(...o);return t&&typeof e=="object"?Object.keys(t).reduce((n,r)=>{if(typeof t[r]?.parse=="function")try{n[r]=t[r].parse(e[r]);}catch(p){throw r=p.cause?.key?`${r}.${p.cause.key}`:r,new Error(`Error parsing key "${r}": ${p.message}`,{cause:{key:r}})}return n},{}):e}),c},string(){return s(a=>typeof a=="string",{type:"string"})},number(){return s(a=>typeof a=="number",{type:"number"})},boolean(){return s(a=>a===true||a===false,{type:"boolean"})},array(t){let c=s(u=>Array.isArray(u),{type:"array"});return i(c,"parse",(u,o)=>(o=u(o),t&&Array.isArray(o)?o.map((e,n)=>{try{return t.parse(e)}catch(r){let p=r.cause?.key?`${n}.${r.cause.key}`:n;throw new Error(`Error parsing index "${n}": ${r.message}`,{cause:{key:p}})}}):o)),c},any(){return s(()=>true)}};function y(t){return a=>`The value "${a}" must be type of ${t} but is type of "${typeof a}".`}function i(t,a,c){let u=t[a];t[a]=(...o)=>c(u,...o);}function s(t,{type:a="any"}={}){let c=y(a),u={message:c,type:a},o={parse(e){if(!t(e))throw new Error(c(e));return e},safeParse(e){try{return {success:!0,data:this.parse(e)}}catch(n){return {success:false,error:n}}},optional(){return i(this,"parse",(e,n)=>{try{return e(n)}catch{return}}),this},nullable(){return i(this,"parse",(e,n)=>{try{return e(n)}catch{return null}}),this},nullish(){return i(this,"parse",(e,n)=>{try{return e(n)}catch{return n==null?n:null}}),this},default(e){return i(this,"parse",(n,r)=>(r===void 0&&(r=e,r=typeof e=="function"?e():e),r=n(r),r)),this}};return f.reduce((e,n)=>n(e,t,u)??e,o)}var f=[];function h(t){f.push(t);}exports.extend=h;exports.s=l;
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ var l={object(t){let c=s(u=>typeof u=="object"&&u!==null&&!Array.isArray(u),{type:"object"});return i(c,"parse",(u,...o)=>{let e=u(...o);return t&&typeof e=="object"?Object.keys(t).reduce((n,r)=>{if(typeof t[r]?.parse=="function")try{n[r]=t[r].parse(e[r]);}catch(p){throw r=p.cause?.key?`${r}.${p.cause.key}`:r,new Error(`Error parsing key "${r}": ${p.message}`,{cause:{key:r}})}return n},{}):e}),c},string(){return s(a=>typeof a=="string",{type:"string"})},number(){return s(a=>typeof a=="number",{type:"number"})},boolean(){return s(a=>a===true||a===false,{type:"boolean"})},array(t){let c=s(u=>Array.isArray(u),{type:"array"});return i(c,"parse",(u,o)=>(o=u(o),t&&Array.isArray(o)?o.map((e,n)=>{try{return t.parse(e)}catch(r){let p=r.cause?.key?`${n}.${r.cause.key}`:n;throw new Error(`Error parsing index "${n}": ${r.message}`,{cause:{key:p}})}}):o)),c},any(){return s(()=>true)}};function y(t){return a=>`The value "${a}" must be type of ${t} but is type of "${typeof a}".`}function i(t,a,c){let u=t[a];t[a]=(...o)=>c(u,...o);}function s(t,{type:a="any"}={}){let c=y(a),u={message:c,type:a},o={parse(e){if(!t(e))throw new Error(c(e));return e},safeParse(e){try{return {success:!0,data:this.parse(e)}}catch(n){return {success:false,error:n}}},optional(){return i(this,"parse",(e,n)=>{try{return e(n)}catch{return}}),this},nullable(){return i(this,"parse",(e,n)=>{try{return e(n)}catch{return null}}),this},nullish(){return i(this,"parse",(e,n)=>{try{return e(n)}catch{return n==null?n:null}}),this},default(e){return i(this,"parse",(n,r)=>(r===void 0&&(r=e,r=typeof e=="function"?e():e),r=n(r),r)),this}};return f.reduce((e,n)=>n(e,t,u)??e,o)}var f=[];function h(t){f.push(t);}export{h as extend,l as s};
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@esmj/schema",
3
+ "version": "0.0.2",
4
+ "description": "Tiny extendable package for schema validation.",
5
+ "keywords": [
6
+ "schema",
7
+ "validation",
8
+ "type",
9
+ "inference",
10
+ "zod"
11
+ ],
12
+ "main": "dist/index",
13
+ "module": "dist/index",
14
+ "exports": {
15
+ ".": {
16
+ "import": "./dist/index.mjs",
17
+ "require": "./dist/index.js"
18
+ }
19
+ },
20
+ "sideEffects": false,
21
+ "typings": "dist/index.d.ts",
22
+ "scripts": {
23
+ "lint": "biome check --no-errors-on-unmatched",
24
+ "lint:fix": "npm run lint -- --fix --unsafe",
25
+ "dev": "node_modules/.bin/tsup --dts --watch --onSuccess 'node ./dist/index.mjs'",
26
+ "test": "node --test --experimental-strip-types",
27
+ "test:watch": "npm run test -- --watchAll",
28
+ "preversion": "npm test && npm run lint && npm run build",
29
+ "version": "npm run changelog && git add CHANGELOG.md",
30
+ "postversion": "git push && git push --tags",
31
+ "commit": "node_modules/.bin/git-cz",
32
+ "changelog": "node_modules/.bin/conventional-changelog -p angular -i CHANGELOG.md -s -r 1",
33
+ "build": "node_modules/.bin/tsup --dts",
34
+ "prepare": "husky install"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/mjancarik/esmj-schema.git"
39
+ },
40
+ "author": "Miroslav Jancarik",
41
+ "license": "MIT",
42
+ "bugs": {
43
+ "url": "https://github.com/mjancarik/esmj-schema/issues"
44
+ },
45
+ "lint-staged": {
46
+ "**/*.{ts,js,mjs}": "npm run lint"
47
+ },
48
+ "commitlint": {
49
+ "extends": [
50
+ "@commitlint/config-conventional"
51
+ ]
52
+ },
53
+ "config": {
54
+ "commitizen": {
55
+ "path": "git-cz"
56
+ }
57
+ },
58
+ "publishConfig": {
59
+ "registry": "https://registry.npmjs.org/",
60
+ "access": "public"
61
+ },
62
+ "homepage": "https://github.com/mjancarik/esmj-schema#readme",
63
+ "devDependencies": {
64
+ "@biomejs/biome": "1.9.4",
65
+ "@commitlint/cli": "^19.7.1",
66
+ "@commitlint/config-conventional": "^19.7.1",
67
+ "@typescript-eslint/eslint-plugin": "^8.24.0",
68
+ "@typescript-eslint/parser": "^8.24.0",
69
+ "commitizen": "^4.3.1",
70
+ "conventional-changelog-cli": "^5.0.0",
71
+ "cz-conventional-changelog": "^3.3.0",
72
+ "git-cz": "^4.9.0",
73
+ "husky": "^9.1.7",
74
+ "lint-staged": "^15.4.3",
75
+ "prettier": "^3.5.0",
76
+ "tsup": "^8.3.6"
77
+ }
78
+ }