@manassandhu/mint 0.0.0-stage → 0.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.
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Mint - Number Schema
3
+ */
4
+
5
+ import { Schema } from "../core/Schema.js";
6
+
7
+ export class NumberSchema extends Schema {
8
+ constructor(checks = []) {
9
+ super({ type: "number" });
10
+ this.checks = [...checks];
11
+ }
12
+
13
+ _addCheck(check) {
14
+ return new NumberSchema([...this.checks, check]);
15
+ }
16
+
17
+ _parse(context, value) {
18
+ if (typeof value !== "number" || Number.isNaN(value)) {
19
+ context.addIssue({
20
+ code: "invalid_type",
21
+ expected: "number",
22
+ received: getType(value),
23
+ message: `Expected number, received ${getType(value)}`,
24
+ });
25
+
26
+ return value;
27
+ }
28
+
29
+ for (const check of this.checks) {
30
+ if (!check.validate(value)) {
31
+ context.addIssue({
32
+ code: check.code,
33
+ message: check.message,
34
+ ...check.metadata,
35
+ });
36
+ }
37
+ }
38
+
39
+ return value;
40
+ }
41
+
42
+ min(value, message) {
43
+ return this._addCheck({
44
+ code: "too_small",
45
+ validate: (input) => input >= value,
46
+ message: message ?? `Number must be greater than or equal to ${value}`,
47
+ metadata: {
48
+ minimum: value,
49
+ inclusive: true,
50
+ type: "number",
51
+ },
52
+ });
53
+ }
54
+
55
+ max(value, message) {
56
+ return this._addCheck({
57
+ code: "too_big",
58
+ validate: (input) => input <= value,
59
+ message: message ?? `Number must be less than or equal to ${value}`,
60
+ metadata: {
61
+ maximum: value,
62
+ inclusive: true,
63
+ type: "number",
64
+ },
65
+ });
66
+ }
67
+
68
+ gt(value, message) {
69
+ return this._addCheck({
70
+ code: "too_small",
71
+ validate: (input) => input > value,
72
+ message: message ?? `Number must be greater than ${value}`,
73
+ metadata: {
74
+ minimum: value,
75
+ inclusive: false,
76
+ type: "number",
77
+ },
78
+ });
79
+ }
80
+
81
+ gte(value, message) {
82
+ return this.min(value, message);
83
+ }
84
+
85
+ lt(value, message) {
86
+ return this._addCheck({
87
+ code: "too_big",
88
+ validate: (input) => input < value,
89
+ message: message ?? `Number must be less than ${value}`,
90
+ metadata: {
91
+ maximum: value,
92
+ inclusive: false,
93
+ type: "number",
94
+ },
95
+ });
96
+ }
97
+
98
+ lte(value, message) {
99
+ return this.max(value, message);
100
+ }
101
+
102
+ int(message) {
103
+ return this._addCheck({
104
+ code: "invalid_type",
105
+ validate: Number.isInteger,
106
+ message: message ?? "Expected integer",
107
+ metadata: {
108
+ expected: "integer",
109
+ received: "float",
110
+ },
111
+ });
112
+ }
113
+
114
+ positive(message) {
115
+ return this.gt(0, message);
116
+ }
117
+
118
+ negative(message) {
119
+ return this.lt(0, message);
120
+ }
121
+
122
+ nonnegative(message) {
123
+ return this.gte(0, message);
124
+ }
125
+
126
+ nonpositive(message) {
127
+ return this.lte(0, message);
128
+ }
129
+
130
+ finite(message) {
131
+ return this._addCheck({
132
+ code: "not_finite",
133
+ validate: Number.isFinite,
134
+ message: message ?? "Number must be finite",
135
+ });
136
+ }
137
+
138
+ safe(message) {
139
+ return this._addCheck({
140
+ code: "unsafe_number",
141
+ validate: Number.isSafeInteger,
142
+ message: message ?? "Number must be a safe integer",
143
+ });
144
+ }
145
+
146
+ multipleOf(value, message) {
147
+ if (value === 0) {
148
+ throw new Error("multipleOf() divisor cannot be zero.");
149
+ }
150
+
151
+ return this._addCheck({
152
+ code: "not_multiple_of",
153
+ validate: (input) => {
154
+ const quotient = input / value;
155
+ return Math.abs(quotient - Math.round(quotient)) < 1e-10;
156
+ },
157
+ message: message ?? `Number must be a multiple of ${value}`,
158
+ metadata: {
159
+ multipleOf: value,
160
+ },
161
+ });
162
+ }
163
+ }
164
+
165
+ function getType(value) {
166
+ if (value === null) return "null";
167
+ if (Array.isArray(value)) return "array";
168
+ return typeof value;
169
+ }
@@ -0,0 +1,336 @@
1
+ /**
2
+ * Mint - Object Schema
3
+ *
4
+ * Validates objects using a defined schema shape.
5
+ * Supports:
6
+ * - Nested validation
7
+ * - Strip unknown keys (default)
8
+ * - Strict unknown-key rejection
9
+ * - Passthrough unknown keys
10
+ * - Pick / omit / extend / merge
11
+ * - Partial / required
12
+ * - Async validation
13
+ */
14
+
15
+ import { Schema } from "../core/Schema.js";
16
+ import { isPlainObject, hasOwn } from "../utils/objectUtils.js";
17
+
18
+ export class ObjectSchema extends Schema {
19
+ constructor(shape, unknownKeys = "strip") {
20
+ validateShape(shape);
21
+ validateUnknownKeysMode(unknownKeys);
22
+
23
+ const frozenShape = Object.freeze({ ...shape });
24
+
25
+ super({
26
+ type: "object",
27
+ shape: frozenShape,
28
+ unknownKeys,
29
+ });
30
+
31
+ this.shape = frozenShape;
32
+ this.unknownKeys = unknownKeys;
33
+ }
34
+
35
+ _parse(context, value) {
36
+ if (!isPlainObject(value)) {
37
+ context.addIssue({
38
+ code: "invalid_type",
39
+ expected: "object",
40
+ received: getType(value),
41
+ message: `Expected object, received ${getType(value)}`,
42
+ });
43
+
44
+ return value;
45
+ }
46
+
47
+ const output = {};
48
+
49
+ // Validate known schema properties.
50
+ for (const key of Object.keys(this.shape)) {
51
+ const schema = this.shape[key];
52
+ const exists = hasOwn(value, key);
53
+ const inputValue = exists ? value[key] : undefined;
54
+
55
+ const childContext = context.child(key, inputValue);
56
+
57
+ const parsedValue = schema._parse(childContext, inputValue);
58
+
59
+ if (isPromise(parsedValue)) {
60
+ throw new Error(
61
+ "Asynchronous object validation requires async parsing.",
62
+ );
63
+ }
64
+
65
+ // Preserve explicitly present undefined values.
66
+ // Omit absent optional properties.
67
+ if (exists || parsedValue !== undefined) {
68
+ output[key] = parsedValue;
69
+ }
70
+ }
71
+
72
+ this._processUnknownKeys(context, value, output);
73
+
74
+ return output;
75
+ }
76
+
77
+ async _parseAsync(context, value) {
78
+ if (!isPlainObject(value)) {
79
+ context.addIssue({
80
+ code: "invalid_type",
81
+ expected: "object",
82
+ received: getType(value),
83
+ message: `Expected object, received ${getType(value)}`,
84
+ });
85
+
86
+ return value;
87
+ }
88
+
89
+ const output = {};
90
+
91
+ // Validate known schema properties asynchronously.
92
+ // Sequential parsing preserves deterministic issue ordering.
93
+ for (const key of Object.keys(this.shape)) {
94
+ const schema = this.shape[key];
95
+ const exists = hasOwn(value, key);
96
+ const inputValue = exists ? value[key] : undefined;
97
+
98
+ const childContext = context.child(key, inputValue);
99
+
100
+ const parsedValue = await schema._parseAsync(childContext, inputValue);
101
+
102
+ // Preserve explicitly present undefined values.
103
+ // Omit absent optional properties.
104
+ if (exists || parsedValue !== undefined) {
105
+ output[key] = parsedValue;
106
+ }
107
+ }
108
+
109
+ this._processUnknownKeys(context, value, output);
110
+
111
+ return output;
112
+ }
113
+
114
+ _processUnknownKeys(context, value, output) {
115
+ const unknownKeys = Object.keys(value).filter(
116
+ (key) => !hasOwn(this.shape, key),
117
+ );
118
+
119
+ if (this.unknownKeys === "strict") {
120
+ for (const key of unknownKeys) {
121
+ context.child(key, value[key]).addIssue({
122
+ code: "unrecognized_key",
123
+ message: `Unrecognized key: "${key}"`,
124
+ key,
125
+ });
126
+ }
127
+ } else if (this.unknownKeys === "passthrough") {
128
+ for (const key of unknownKeys) {
129
+ output[key] = value[key];
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Reject all unknown object keys.
136
+ */
137
+ strict() {
138
+ return new ObjectSchema(this.shape, "strict");
139
+ }
140
+
141
+ /**
142
+ * Allow unknown keys and preserve them.
143
+ */
144
+ passthrough() {
145
+ return new ObjectSchema(this.shape, "passthrough");
146
+ }
147
+
148
+ /**
149
+ * Strip unknown keys.
150
+ */
151
+ strip() {
152
+ return new ObjectSchema(this.shape, "strip");
153
+ }
154
+
155
+ /**
156
+ * Add or replace fields.
157
+ */
158
+ extend(additionalShape) {
159
+ validateShape(additionalShape);
160
+
161
+ return new ObjectSchema(
162
+ {
163
+ ...this.shape,
164
+ ...additionalShape,
165
+ },
166
+ this.unknownKeys,
167
+ );
168
+ }
169
+
170
+ /**
171
+ * Alias for extend().
172
+ */
173
+ safeExtend(additionalShape) {
174
+ return this.extend(additionalShape);
175
+ }
176
+
177
+ /**
178
+ * Select specified properties.
179
+ */
180
+ pick(keys) {
181
+ const selectedShape = {};
182
+
183
+ for (const key of normalizeKeys(keys)) {
184
+ if (hasOwn(this.shape, key)) {
185
+ selectedShape[key] = this.shape[key];
186
+ }
187
+ }
188
+
189
+ return new ObjectSchema(selectedShape, this.unknownKeys);
190
+ }
191
+
192
+ /**
193
+ * Exclude specified properties.
194
+ */
195
+ omit(keys) {
196
+ const excluded = new Set(normalizeKeys(keys));
197
+ const newShape = {};
198
+
199
+ for (const key of Object.keys(this.shape)) {
200
+ if (!excluded.has(key)) {
201
+ newShape[key] = this.shape[key];
202
+ }
203
+ }
204
+
205
+ return new ObjectSchema(newShape, this.unknownKeys);
206
+ }
207
+
208
+ /**
209
+ * Make every field optional.
210
+ */
211
+ partial(keys) {
212
+ const selected =
213
+ keys === undefined ? Object.keys(this.shape) : normalizeKeys(keys);
214
+
215
+ const selectedSet = new Set(selected);
216
+ const newShape = {};
217
+
218
+ for (const key of Object.keys(this.shape)) {
219
+ newShape[key] = selectedSet.has(key)
220
+ ? this.shape[key].optional()
221
+ : this.shape[key];
222
+ }
223
+
224
+ return new ObjectSchema(newShape, this.unknownKeys);
225
+ }
226
+
227
+ /**
228
+ * Make every field required.
229
+ */
230
+ required(keys) {
231
+ const selected =
232
+ keys === undefined ? Object.keys(this.shape) : normalizeKeys(keys);
233
+
234
+ const selectedSet = new Set(selected);
235
+ const newShape = {};
236
+
237
+ for (const key of Object.keys(this.shape)) {
238
+ newShape[key] = selectedSet.has(key)
239
+ ? unwrapOptional(this.shape[key])
240
+ : this.shape[key];
241
+ }
242
+
243
+ return new ObjectSchema(newShape, this.unknownKeys);
244
+ }
245
+
246
+ /**
247
+ * Merge another ObjectSchema into this one.
248
+ * The other schema's fields overwrite matching keys.
249
+ */
250
+ merge(other) {
251
+ if (!(other instanceof ObjectSchema)) {
252
+ throw new TypeError("merge() expects another ObjectSchema.");
253
+ }
254
+
255
+ return new ObjectSchema(
256
+ {
257
+ ...this.shape,
258
+ ...other.shape,
259
+ },
260
+ other.unknownKeys,
261
+ );
262
+ }
263
+
264
+ /**
265
+ * Returns the shape definition.
266
+ */
267
+ getShape() {
268
+ return { ...this.shape };
269
+ }
270
+
271
+ /**
272
+ * Returns keys defined by this schema.
273
+ */
274
+ get keys() {
275
+ return Object.keys(this.shape);
276
+ }
277
+ }
278
+
279
+ function validateShape(shape) {
280
+ if (shape === null || typeof shape !== "object" || Array.isArray(shape)) {
281
+ throw new TypeError("ObjectSchema shape must be an object.");
282
+ }
283
+
284
+ for (const [key, schema] of Object.entries(shape)) {
285
+ if (!schema || typeof schema._parse !== "function") {
286
+ throw new TypeError(`Invalid schema for object key "${key}".`);
287
+ }
288
+ }
289
+ }
290
+
291
+ function validateUnknownKeysMode(mode) {
292
+ const validModes = ["strip", "strict", "passthrough"];
293
+
294
+ if (!validModes.includes(mode)) {
295
+ throw new TypeError(`Invalid unknown-key mode "${mode}".`);
296
+ }
297
+ }
298
+
299
+ function normalizeKeys(keys) {
300
+ if (Array.isArray(keys)) {
301
+ return keys;
302
+ }
303
+
304
+ if (keys && typeof keys === "object") {
305
+ return Object.keys(keys).filter((key) => keys[key]);
306
+ }
307
+
308
+ throw new TypeError("Expected an array of keys or key-selection object.");
309
+ }
310
+
311
+ function unwrapOptional(schema) {
312
+ if (schema.type === "optional") {
313
+ return schema.schema;
314
+ }
315
+
316
+ if (schema.type === "default") {
317
+ return schema.schema;
318
+ }
319
+
320
+ return schema;
321
+ }
322
+
323
+ function getType(value) {
324
+ if (value === null) return "null";
325
+ if (Array.isArray(value)) return "array";
326
+
327
+ return typeof value;
328
+ }
329
+
330
+ function isPromise(value) {
331
+ return (
332
+ value !== null &&
333
+ (typeof value === "object" || typeof value === "function") &&
334
+ typeof value.then === "function"
335
+ );
336
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Mint - Promise Schema
3
+ *
4
+ * Validates Promise-like values and their resolved data.
5
+ */
6
+
7
+ import { Schema } from "../core/Schema.js";
8
+
9
+ export class PromiseSchema extends Schema {
10
+ constructor(valueSchema) {
11
+ validateSchema(valueSchema);
12
+
13
+ super({
14
+ type: "promise",
15
+ valueSchema,
16
+ });
17
+
18
+ this.valueSchema = valueSchema;
19
+ }
20
+
21
+ _parse(context, value) {
22
+ if (!isPromise(value)) {
23
+ context.addIssue({
24
+ code: "invalid_type",
25
+ expected: "promise",
26
+ received: getType(value),
27
+ message: `Expected Promise, received ${getType(value)}`,
28
+ });
29
+
30
+ return value;
31
+ }
32
+
33
+ return value.then((resolvedValue) => {
34
+ const childContext = context.child("resolved", resolvedValue);
35
+
36
+ return this.valueSchema._parse(childContext, resolvedValue);
37
+ });
38
+ }
39
+
40
+ async _parseAsync(context, value) {
41
+ if (!isPromise(value)) {
42
+ context.addIssue({
43
+ code: "invalid_type",
44
+ expected: "promise",
45
+ received: getType(value),
46
+ message: `Expected Promise, received ${getType(value)}`,
47
+ });
48
+
49
+ return value;
50
+ }
51
+
52
+ const resolvedValue = await value;
53
+
54
+ const childContext = context.child("resolved", resolvedValue);
55
+
56
+ return this.valueSchema._parseAsync(childContext, resolvedValue);
57
+ }
58
+ }
59
+
60
+ function validateSchema(schema) {
61
+ if (!schema || typeof schema._parse !== "function") {
62
+ throw new TypeError("PromiseSchema requires a valid value schema.");
63
+ }
64
+ }
65
+
66
+ function isPromise(value) {
67
+ return (
68
+ value !== null &&
69
+ (typeof value === "object" || typeof value === "function") &&
70
+ typeof value.then === "function"
71
+ );
72
+ }
73
+
74
+ function getType(value) {
75
+ if (value === null) return "null";
76
+
77
+ if (isPromise(value)) return "promise";
78
+
79
+ if (Array.isArray(value)) return "array";
80
+
81
+ return typeof value;
82
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Mint - Record Schema
3
+ *
4
+ * Validates objects with consistent value schemas.
5
+ * Optionally validates keys using a key schema.
6
+ */
7
+
8
+ import { Schema } from "../core/Schema.js";
9
+ import { isPlainObject } from "../utils/objectUtils.js";
10
+
11
+ export class RecordSchema extends Schema {
12
+ constructor(valueSchema, keySchema = null) {
13
+ validateSchema(valueSchema);
14
+
15
+ if (keySchema !== null) {
16
+ validateSchema(keySchema);
17
+ }
18
+
19
+ super({
20
+ type: "record",
21
+ valueSchema,
22
+ keySchema,
23
+ });
24
+
25
+ this.valueSchema = valueSchema;
26
+ this.keySchema = keySchema;
27
+ }
28
+
29
+ _parse(context, value) {
30
+ if (!isPlainObject(value)) {
31
+ context.addIssue({
32
+ code: "invalid_type",
33
+ expected: "object",
34
+ received: getType(value),
35
+ message: `Expected object, received ${getType(value)}`,
36
+ });
37
+
38
+ return value;
39
+ }
40
+
41
+ const output = {};
42
+
43
+ for (const key of Object.keys(value)) {
44
+ const childContext = context.child(key, value[key]);
45
+
46
+ // Validate key if a key schema was supplied.
47
+ if (this.keySchema) {
48
+ const parsedKey = this.keySchema._parse(childContext, key);
49
+
50
+ if (isPromise(parsedKey)) {
51
+ throw new Error(
52
+ "Asynchronous record key validation requires async parsing.",
53
+ );
54
+ }
55
+
56
+ if (childContext.hasIssues) {
57
+ continue;
58
+ }
59
+ }
60
+
61
+ const parsedValue = this.valueSchema._parse(childContext, value[key]);
62
+
63
+ if (isPromise(parsedValue)) {
64
+ throw new Error(
65
+ "Asynchronous record validation requires async parsing.",
66
+ );
67
+ }
68
+
69
+ output[key] = parsedValue;
70
+ }
71
+
72
+ return output;
73
+ }
74
+
75
+ async _parseAsync(context, value) {
76
+ if (!isPlainObject(value)) {
77
+ context.addIssue({
78
+ code: "invalid_type",
79
+ expected: "object",
80
+ received: getType(value),
81
+ message: `Expected object, received ${getType(value)}`,
82
+ });
83
+
84
+ return value;
85
+ }
86
+
87
+ const output = {};
88
+
89
+ for (const key of Object.keys(value)) {
90
+ const childContext = context.child(key, value[key]);
91
+
92
+ // Validate key if a key schema was supplied.
93
+ if (this.keySchema) {
94
+ await this.keySchema._parseAsync(childContext, key);
95
+
96
+ if (childContext.hasIssues) {
97
+ continue;
98
+ }
99
+ }
100
+
101
+ const parsedValue = await this.valueSchema._parseAsync(
102
+ childContext,
103
+ value[key],
104
+ );
105
+
106
+ output[key] = parsedValue;
107
+ }
108
+
109
+ return output;
110
+ }
111
+ }
112
+
113
+ function validateSchema(schema) {
114
+ if (!schema || typeof schema._parse !== "function") {
115
+ throw new TypeError("Record key and value must be valid schemas.");
116
+ }
117
+ }
118
+
119
+ function getType(value) {
120
+ if (value === null) return "null";
121
+ if (Array.isArray(value)) return "array";
122
+
123
+ return typeof value;
124
+ }
125
+
126
+ function isPromise(value) {
127
+ return (
128
+ value !== null &&
129
+ (typeof value === "object" || typeof value === "function") &&
130
+ typeof value.then === "function"
131
+ );
132
+ }