validup 0.1.9 → 0.2.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
@@ -88,11 +88,11 @@ console.log(output);
88
88
 
89
89
  ### Errors
90
90
 
91
- During the execution of a [validator](#validator), a ValidupValidatorError or ValidupNestedError can be thrown.
92
- A ValidupNestedError bundles multiple ValidupValidationErrors.
91
+ During the execution of a [validator](#validator), a ValidupError can be thrown.
92
+ An error can contain multiple issues.
93
93
 
94
- When the execution of a Container fails, the container will always throw a ValidupNestedError.
95
- Unknown errors will be converted to a ValidupValidatorError.
94
+ When the execution of a Container fails, the container will always throw a ValidupError.
95
+ Unknown errors will be converted.
96
96
 
97
97
  ### Mounting
98
98
 
@@ -149,23 +149,23 @@ type ValidatorContext = {
149
149
  /**
150
150
  * The expanded mount path in the current container.
151
151
  */
152
- path: string,
153
- /**
154
- * The unexpanded mount path in the current container.
155
- */
156
- pathRaw: string,
152
+ key: string,
153
+
157
154
  /**
158
155
  * The global mount path of the parent container.
159
156
  */
160
- pathAbsolute: string,
157
+ path: PropertyKey[],
158
+
161
159
  /**
162
160
  * The actual value, which should be validated.
163
161
  */
164
162
  value: unknown,
163
+
165
164
  /**
166
165
  * The input data of the current container.
167
166
  */
168
167
  data: Record<string, any>,
168
+
169
169
  /**
170
170
  * The group name for which the validator is executed.
171
171
  */
@@ -0,0 +1,2 @@
1
+ import type { IContainer } from './types';
2
+ export declare function isContainer(input: unknown): input is IContainer;
@@ -0,0 +1,3 @@
1
+ export * from './check';
2
+ export * from './module';
3
+ export * from './types';
@@ -0,0 +1,21 @@
1
+ import type { Path } from 'pathtrace';
2
+ import type { Validator } from '../types';
3
+ import type { ContainerOptions, ContainerRunOptions, IContainer, Mount, MountOptions } from './types';
4
+ export declare class Container<T extends Record<string, any> = Record<string, any>> implements IContainer {
5
+ protected options: ContainerOptions<T>;
6
+ protected items: Mount[];
7
+ constructor(options?: ContainerOptions<T>);
8
+ mount(container: IContainer): void;
9
+ mount(options: MountOptions, container: IContainer): void;
10
+ mount(key: Path<T> | (string & {}), data: IContainer | Validator): void;
11
+ mount(key: Path<T> | (string & {}), options: MountOptions, data: IContainer | Validator): void;
12
+ /**
13
+ * @throws ValidupError
14
+ * @param data
15
+ * @param options
16
+ */
17
+ run(data?: Record<string, any>, options?: ContainerRunOptions<T>): Promise<T>;
18
+ private isItemGroupIncluded;
19
+ private mergePaths;
20
+ protected initialize(): void;
21
+ }
@@ -0,0 +1,101 @@
1
+ import type { Path } from 'pathtrace';
2
+ import type { OptionalValue } from '../constants';
3
+ import type { ObjectLiteral, Validator } from '../types';
4
+ export type ContainerOptions<T> = {
5
+ /**
6
+ * Only one of the mounted container/validators must succeed.
7
+ */
8
+ oneOf?: boolean;
9
+ /**
10
+ * Limit mounted paths on execution.
11
+ * By default, all mounted containers/validators will
12
+ * be considered for execution.
13
+ */
14
+ pathsToInclude?: Path<T>[];
15
+ /**
16
+ * Exclude mounted paths on execution.
17
+ * By default, all mounted containers/validators will
18
+ * be considered for execution.
19
+ */
20
+ pathsToExclude?: Path<T>[];
21
+ };
22
+ export type ContainerRunOptions<T extends Record<string, any> = Record<string, any>> = {
23
+ /**
24
+ * Default values for the container output.
25
+ */
26
+ defaults?: {
27
+ [Key in Path<T>]: any;
28
+ };
29
+ /**
30
+ * Group to execute.
31
+ */
32
+ group?: string;
33
+ /**
34
+ * Output flat object?
35
+ */
36
+ flat?: boolean;
37
+ /**
38
+ * Passed path from the parent container.
39
+ */
40
+ path?: PropertyKey[];
41
+ /**
42
+ * Limit mounted paths on execution.
43
+ * By default, all mounted containers/validators will
44
+ * be considered for execution.
45
+ */
46
+ pathsToInclude?: Path<T>[];
47
+ /**
48
+ * Exclude mounted paths on execution.
49
+ * By default, all mounted containers/validators will
50
+ * be considered for execution.
51
+ */
52
+ pathsToExclude?: Path<T>[];
53
+ };
54
+ export type MountOptions = {
55
+ /**
56
+ * Group(s) to execute.
57
+ */
58
+ group?: string | string[];
59
+ /**
60
+ * Specify if an optional value is also acceptable for the mount key.
61
+ * An optional value won't be passed to the underlying container/validator.
62
+ *
63
+ * default: false
64
+ */
65
+ optional?: boolean;
66
+ /**
67
+ * Which values are considered optional.
68
+ * An optional value won't be passed to the underlying container/validator.
69
+ *
70
+ * default: 'undefined'
71
+ */
72
+ optionalValue?: `${OptionalValue}`;
73
+ /**
74
+ * Include optional value as property in output.
75
+ *
76
+ * default: false
77
+ */
78
+ optionalInclude?: boolean;
79
+ };
80
+ export interface IContainer<T extends ObjectLiteral = ObjectLiteral> {
81
+ /**
82
+ * Execute container with given input.
83
+ *
84
+ * @param data
85
+ * @param options
86
+ */
87
+ run(data?: Record<string, any>, options?: ContainerRunOptions<T>): Promise<T>;
88
+ }
89
+ export type BaseMount = {
90
+ options: MountOptions;
91
+ path?: string;
92
+ };
93
+ export type ContainerMount = BaseMount & {
94
+ type: 'container';
95
+ data: IContainer;
96
+ };
97
+ export type ValidatorMount = BaseMount & {
98
+ type: 'validator';
99
+ data: Validator;
100
+ };
101
+ export type Mount = ContainerMount | ValidatorMount;
@@ -1,2 +1,5 @@
1
+ import type { Issue } from '../issue';
1
2
  export declare class ValidupError extends Error {
3
+ readonly issues: Issue[];
4
+ constructor(issues?: Issue[]);
2
5
  }
@@ -1,3 +1 @@
1
- export * from './validator';
2
1
  export * from './base';
3
- export * from './nested';
@@ -1,2 +1,2 @@
1
- export declare function buildErrorMessageForAttribute(key: string | number): string;
2
- export declare function buildErrorMessageForAttributes(input: (number | string)[] | Record<string, any>): string;
1
+ export declare function buildErrorMessageForAttribute(key: PropertyKey): string;
2
+ export declare function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>): string;
package/dist/index.cjs CHANGED
@@ -4,7 +4,7 @@ var smob = require('smob');
4
4
  var pathtrace = require('pathtrace');
5
5
 
6
6
  function buildErrorMessageForAttribute(key) {
7
- return `The attribute ${String(key)} is invalid.`;
7
+ return `Property ${String(key)} is invalid`;
8
8
  }
9
9
  function buildErrorMessageForAttributes(input) {
10
10
  let names;
@@ -14,10 +14,10 @@ function buildErrorMessageForAttributes(input) {
14
14
  names = Object.keys(input);
15
15
  }
16
16
  if (names.length === 0) {
17
- return 'An unexpected error occurred.';
17
+ return 'Properties are invalid';
18
18
  }
19
19
  if (names.length > 1) {
20
- return `The attributes ${names.join(', ')} are invalid.`;
20
+ return `Properties ${names.join(', ')} are invalid.`;
21
21
  }
22
22
  return buildErrorMessageForAttribute(names[0]);
23
23
  }
@@ -66,27 +66,40 @@ var OptionalValue = /*#__PURE__*/ function(OptionalValue) {
66
66
  * For the full copyright and license information,
67
67
  * view the LICENSE file that was distributed with this source code.
68
68
  */ class ValidupError extends Error {
69
- }
70
-
71
- class ValidupValidatorError extends ValidupError {
72
- constructor(options){
73
- super(options.message);
74
- this.path = options.path;
75
- this.pathAbsolute = options.pathAbsolute ?? options.path;
76
- this.code = options.code;
77
- this.received = options.received;
78
- this.expected = options.expected;
69
+ constructor(issues = []){
70
+ super(JSON.stringify(issues, (_, value)=>{
71
+ if (typeof value === 'bigint') {
72
+ return value.toString();
73
+ }
74
+ return value;
75
+ }, 2));
76
+ this.issues = issues;
79
77
  }
80
78
  }
81
79
 
82
- class ValidupNestedError extends ValidupError {
83
- addChild(child) {
84
- this.children.push(child);
85
- }
86
- constructor(options = {}){
87
- super(options.message || 'One or many attributes may be invalid.');
88
- this.children = options.children || [];
89
- }
80
+ /*
81
+ * Copyright (c) 2026.
82
+ * Author Peter Placzek (tada5hi)
83
+ * For the full copyright and license information,
84
+ * view the LICENSE file that was distributed with this source code.
85
+ */ var IssueCode = /*#__PURE__*/ function(IssueCode) {
86
+ IssueCode["VALUE_INVALID"] = "value_invalid";
87
+ IssueCode["ONE_OF_FAILED"] = "one_of_failed";
88
+ return IssueCode;
89
+ }({});
90
+
91
+ function defineIssueItem(data) {
92
+ return {
93
+ type: 'item',
94
+ ...data,
95
+ code: IssueCode.VALUE_INVALID || data.code
96
+ };
97
+ }
98
+ function defineIssueGroup(data) {
99
+ return {
100
+ type: 'group',
101
+ ...data
102
+ };
90
103
  }
91
104
 
92
105
  /*
@@ -108,6 +121,10 @@ function hasOwnProperty(obj, prop) {
108
121
  return !!input && typeof input === 'object' && !Array.isArray(input);
109
122
  }
110
123
 
124
+ function isContainer(input) {
125
+ return isObject(input) && typeof input.run === 'function';
126
+ }
127
+
111
128
  class Container {
112
129
  mount(...args) {
113
130
  if (args.length < 1) {
@@ -118,20 +135,21 @@ class Container {
118
135
  let dataIsContainer = false;
119
136
  let options = {};
120
137
  for(let i = 0; i < args.length; i++){
121
- if (typeof args[i] === 'string') {
122
- path = args[i];
138
+ const arg = args[i];
139
+ if (typeof arg === 'string') {
140
+ path = arg;
123
141
  continue;
124
142
  }
125
- if (typeof args[i] === 'function') {
126
- data = args[i];
143
+ if (typeof arg === 'function') {
144
+ data = arg;
127
145
  continue;
128
146
  }
129
- if (args[i] instanceof Container) {
130
- data = args[i];
147
+ if (isContainer(arg)) {
148
+ data = arg;
131
149
  dataIsContainer = true;
132
150
  continue;
133
151
  }
134
- if (isObject(args[i])) {
152
+ if (isObject(arg)) {
135
153
  options = args[i];
136
154
  }
137
155
  }
@@ -141,17 +159,28 @@ class Container {
141
159
  if (typeof data === 'undefined') {
142
160
  throw new SyntaxError('No container/validator could be extracted from the fn arguments.');
143
161
  }
162
+ if (isContainer(data)) {
163
+ this.items.push({
164
+ options,
165
+ data,
166
+ path,
167
+ type: 'container'
168
+ });
169
+ return;
170
+ }
144
171
  this.items.push({
145
- ...options,
172
+ options,
146
173
  data,
147
- path
174
+ path,
175
+ type: 'validator'
148
176
  });
149
177
  }
150
178
  // ----------------------------------------------
151
- async run(data = {}, options = {}) {
152
- const output = {};
153
- const errors = [];
154
- const errorKeys = [];
179
+ /**
180
+ * @throws ValidupError
181
+ * @param data
182
+ * @param options
183
+ */ async run(data = {}, options = {}) {
155
184
  let pathsToInclude;
156
185
  if (options.pathsToInclude) {
157
186
  pathsToInclude = options.pathsToInclude;
@@ -164,44 +193,51 @@ class Container {
164
193
  } else if (this.options.pathsToInclude) {
165
194
  pathsToExclude = this.options.pathsToExclude;
166
195
  }
196
+ const output = {};
197
+ const issues = [];
167
198
  let itemCount = 0;
199
+ let errorCount = 0;
168
200
  for(let i = 0; i < this.items.length; i++){
169
201
  const item = this.items[i];
170
202
  if (!this.isItemGroupIncluded(item, options.group)) {
171
203
  continue;
172
204
  }
173
- let pathsCount = 0;
174
- let paths;
205
+ let pathCount = 0;
206
+ let pathFailed = false;
207
+ let keys;
175
208
  if (item.path) {
176
- paths = pathtrace.expandPath(data, item.path);
209
+ keys = pathtrace.expandPath(data, item.path);
177
210
  } else {
178
- paths = [
211
+ keys = [
179
212
  ''
180
213
  ];
181
214
  }
182
- for(let j = 0; j < paths.length; j++){
183
- const path = paths[j];
184
- const pathAbsolute = this.mergePaths(options.path, paths[j]);
215
+ for(let j = 0; j < keys.length; j++){
216
+ const key = keys[j];
217
+ const keyParts = key ? pathtrace.pathToArray(key) : [];
218
+ const pathRelative = keyParts.at(-1);
219
+ const pathAbsolute = [
220
+ ...options.path ? options.path : [],
221
+ ...keyParts
222
+ ];
185
223
  let value;
186
- if (hasOwnProperty(output, path)) {
187
- value = output[path];
188
- } else if (path.length > 0) {
189
- value = pathtrace.getPathValue(data, path);
224
+ if (key.length > 0) {
225
+ value = hasOwnProperty(output, key) ? output[key] : pathtrace.getPathValue(data, key);
190
226
  } else {
191
227
  value = data;
192
228
  }
193
- if (typeof pathsToInclude !== 'undefined' && pathsToInclude.indexOf(path) === -1) {
229
+ if (typeof pathsToInclude !== 'undefined' && pathsToInclude.indexOf(key) === -1) {
194
230
  continue;
195
231
  }
196
- if (typeof pathsToExclude !== 'undefined' && pathsToExclude.indexOf(path) !== -1) {
232
+ if (typeof pathsToExclude !== 'undefined' && pathsToExclude.indexOf(key) !== -1) {
197
233
  continue;
198
234
  }
199
235
  try {
200
- if (item.optional && isOptionalValue(value, item.optionalValue)) {
201
- if (item.optionalInclude) {
202
- output[path] = value;
236
+ if (item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
237
+ if (item.options.optionalInclude) {
238
+ output[key] = value;
203
239
  }
204
- } else if (item.data instanceof Container) {
240
+ } else if (item.type === 'container') {
205
241
  const tmp = await item.data.run(isObject(value) ? value : {}, {
206
242
  group: options.group,
207
243
  flat: true,
@@ -210,61 +246,75 @@ class Container {
210
246
  });
211
247
  const tmpKeys = Object.keys(tmp);
212
248
  for(let k = 0; k < tmpKeys.length; k++){
213
- output[this.mergePaths(path, tmpKeys[k])] = tmp[tmpKeys[k]];
249
+ output[this.mergePaths(key, tmpKeys[k])] = tmp[tmpKeys[k]];
214
250
  }
215
- } else {
216
- output[path] = await item.data({
217
- path,
218
- pathRaw: item.path ?? '',
219
- pathAbsolute,
251
+ } else if (item.type === 'validator') {
252
+ output[key] = await item.data({
253
+ key,
254
+ path: pathAbsolute,
220
255
  value,
221
256
  data,
222
257
  group: options.group
223
258
  });
224
259
  }
225
260
  } catch (e) {
226
- if (e instanceof ValidupValidatorError) {
227
- errors.push(e);
228
- errorKeys.push(pathAbsolute);
229
- } else if (e instanceof ValidupNestedError) {
230
- errors.push(...e.children);
231
- if (pathAbsolute.length > 0) {
232
- errorKeys.push(pathAbsolute);
261
+ const childIssues = [];
262
+ if (e instanceof ValidupError) {
263
+ for(let i = 0; i < e.issues.length; i++){
264
+ const issue = e.issues[i];
265
+ childIssues.push({
266
+ ...issue,
267
+ path: [
268
+ ...keyParts,
269
+ ...issue.path || []
270
+ ]
271
+ });
272
+ }
273
+ } else if (e instanceof Error) {
274
+ childIssues.push(defineIssueItem({
275
+ path: keyParts,
276
+ message: e.message
277
+ }));
278
+ }
279
+ if (pathRelative) {
280
+ if (item.type === 'container' || childIssues.length > 1) {
281
+ const group = defineIssueGroup({
282
+ message: buildErrorMessageForAttribute(pathRelative),
283
+ path: keyParts,
284
+ issues: childIssues
285
+ });
286
+ issues.push(group);
233
287
  } else {
234
- errorKeys.push(...e.children.map((child)=>child.pathAbsolute));
288
+ issues.push(...childIssues);
235
289
  }
236
290
  } else {
237
- const error = new ValidupValidatorError({
238
- path,
239
- pathAbsolute,
240
- received: value
241
- });
242
- if (e instanceof Error) {
243
- error.cause = e;
244
- error.message = e.message;
245
- }
246
- errors.push(error);
247
- errorKeys.push(pathAbsolute);
291
+ issues.push(...childIssues);
248
292
  }
293
+ pathFailed = true;
249
294
  }
250
- pathsCount++;
295
+ pathCount++;
251
296
  }
252
- if (pathsCount > 0) {
297
+ if (pathCount > 0) {
253
298
  itemCount++;
299
+ if (pathFailed) {
300
+ errorCount++;
301
+ }
254
302
  }
255
303
  }
256
304
  if (this.options.oneOf) {
257
- if (errors.length === itemCount) {
258
- throw new ValidupNestedError({
259
- message: buildErrorMessageForAttributes(errorKeys),
260
- children: errors
305
+ if (errorCount === itemCount) {
306
+ const group = defineIssueGroup({
307
+ code: IssueCode.ONE_OF_FAILED,
308
+ message: 'None of the branches succeeded',
309
+ issues,
310
+ path: options.path ? options.path : []
261
311
  });
312
+ throw new ValidupError([
313
+ group
314
+ ]);
262
315
  }
263
- } else if (errors.length > 0) {
264
- throw new ValidupNestedError({
265
- message: buildErrorMessageForAttributes(errorKeys),
266
- children: errors
267
- });
316
+ } else if (errorCount > 0) {
317
+ throw new ValidupError(issues);
268
318
  }
269
319
  if (options.defaults) {
270
320
  const defaultKeys = Object.keys(options.defaults);
@@ -288,19 +338,19 @@ class Container {
288
338
  if (group === GroupKey.WILDCARD) {
289
339
  return true;
290
340
  }
291
- if (item.group) {
292
- if (Array.isArray(item.group)) {
293
- if (item.group.indexOf(GroupKey.WILDCARD) !== -1) {
341
+ if (item.options.group) {
342
+ if (Array.isArray(item.options.group)) {
343
+ if (item.options.group.indexOf(GroupKey.WILDCARD) !== -1) {
294
344
  return true;
295
345
  }
296
- if (group && item.group.indexOf(group) !== -1) {
346
+ if (group && item.options.group.indexOf(group) !== -1) {
297
347
  return true;
298
348
  }
299
349
  } else {
300
- if (item.group === GroupKey.WILDCARD) {
350
+ if (item.options.group === GroupKey.WILDCARD) {
301
351
  return true;
302
352
  }
303
- if (item.group === group) {
353
+ if (item.options.group === group) {
304
354
  return true;
305
355
  }
306
356
  }
@@ -334,13 +384,15 @@ class Container {
334
384
 
335
385
  exports.Container = Container;
336
386
  exports.GroupKey = GroupKey;
387
+ exports.IssueCode = IssueCode;
337
388
  exports.OptionalValue = OptionalValue;
338
389
  exports.ValidupError = ValidupError;
339
- exports.ValidupNestedError = ValidupNestedError;
340
- exports.ValidupValidatorError = ValidupValidatorError;
341
390
  exports.buildErrorMessageForAttribute = buildErrorMessageForAttribute;
342
391
  exports.buildErrorMessageForAttributes = buildErrorMessageForAttributes;
392
+ exports.defineIssueGroup = defineIssueGroup;
393
+ exports.defineIssueItem = defineIssueItem;
343
394
  exports.hasOwnProperty = hasOwnProperty;
395
+ exports.isContainer = isContainer;
344
396
  exports.isObject = isObject;
345
397
  exports.isOptionalValue = isOptionalValue;
346
398
  //# sourceMappingURL=index.cjs.map