validup 0.2.2 → 0.4.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/dist/index.mjs CHANGED
@@ -1,474 +1,1585 @@
1
- import { distinctArray } from 'smob';
2
- import { arrayToPath, expandPath, pathToArray, getPathValue, setPathValue } from 'pathtrace';
3
-
4
- function buildErrorMessageForAttribute(key) {
5
- return `Property ${String(key)} is invalid`;
6
- }
7
- function buildErrorMessageForAttributes(input) {
8
- let names;
9
- if (Array.isArray(input)) {
10
- names = distinctArray(input);
11
- } else {
12
- names = Object.keys(input);
13
- }
14
- if (names.length === 0) {
15
- return 'Properties are invalid';
16
- }
17
- if (names.length > 1) {
18
- return `Properties ${names.join(', ')} are invalid.`;
19
- }
20
- return buildErrorMessageForAttribute(names[0]);
21
- }
22
-
23
- /*
24
- * Copyright (c) 2024.
25
- * Author Peter Placzek (tada5hi)
26
- * For the full copyright and license information,
27
- * view the LICENSE file that was distributed with this source code.
28
- */ var GroupKey = /*#__PURE__*/ function(GroupKey) {
29
- GroupKey["WILDCARD"] = "*";
30
- return GroupKey;
31
- }({});
32
- var OptionalValue = /*#__PURE__*/ function(OptionalValue) {
33
- /**
34
- * value: undefined
35
- */ OptionalValue["UNDEFINED"] = "undefined";
36
- /**
37
- * value: null & undefined
38
- */ OptionalValue["NULL"] = "null";
39
- /**
40
- * value: empty string, false, 0
41
- */ OptionalValue["FALSY"] = "falsy";
42
- return OptionalValue;
43
- }({});
44
-
45
- /**
46
- * Check if input value (type of) satisfies optional value type constraint.
47
- *
48
- * @param value
49
- * @param optionalValue
50
- */ function isOptionalValue(value, optionalValue) {
51
- const optionValueNormalized = optionalValue || OptionalValue.UNDEFINED;
52
- if (optionValueNormalized === OptionalValue.NULL) {
53
- return value === null || typeof value === 'undefined';
54
- }
55
- if (optionValueNormalized === OptionalValue.UNDEFINED) {
56
- return typeof value === 'undefined';
57
- }
58
- return !value;
59
- }
60
-
61
- /**
62
- * Stringify path array to string.
63
- *
64
- * @param input
65
- */ function stringifyPath(input) {
66
- return arrayToPath(input);
67
- }
68
-
69
- class ValidupError extends Error {
70
- constructor(issues = []){
71
- const paths = issues.map((issue)=>stringifyPath(issue.path));
72
- super(buildErrorMessageForAttributes(paths));
73
- this.issues = issues;
74
- }
75
- }
76
-
77
- /*
78
- * Copyright (c) 2024.
79
- * Author Peter Placzek (tada5hi)
80
- * For the full copyright and license information,
81
- * view the LICENSE file that was distributed with this source code.
82
- */ // eslint-disable-next-line @typescript-eslint/ban-types
1
+ import { BaseError, interpolate, interpolate as interpolate$1 } from "@ebec/core";
2
+ import { distinctArray } from "smob";
3
+ import { arrayToPath, expandPath, getPathValue, pathToArray, setPathValue } from "pathtrace";
4
+ //#region src/utils/has-own-property.ts
83
5
  function hasOwnProperty(obj, prop) {
84
- return Object.prototype.hasOwnProperty.call(obj, prop);
6
+ return Object.prototype.hasOwnProperty.call(obj, prop);
85
7
  }
86
-
87
- /*
88
- * Copyright (c) 2024.
89
- * Author Peter Placzek (tada5hi)
90
- * For the full copyright and license information,
91
- * view the LICENSE file that was distributed with this source code.
92
- */ function isObject(input) {
93
- return !!input && typeof input === 'object' && !Array.isArray(input);
8
+ //#endregion
9
+ //#region src/utils/object.ts
10
+ function isObject(input) {
11
+ return !!input && typeof input === "object" && !Array.isArray(input);
94
12
  }
95
-
13
+ //#endregion
14
+ //#region src/container/check.ts
15
+ function isContainer(input) {
16
+ return isObject(input) && typeof input.run === "function" && typeof input.safeRun === "function";
17
+ }
18
+ //#endregion
19
+ //#region src/error/base.ts
20
+ var ValidupError = class extends BaseError {
21
+ issues;
22
+ constructor(issues = []) {
23
+ const paths = issues.map((issue) => stringifyPath(issue.path));
24
+ super({ message: buildErrorMessageForAttributes(paths) });
25
+ this.issues = issues;
26
+ }
27
+ toJSON() {
28
+ return {
29
+ ...super.toJSON(),
30
+ issues: this.issues
31
+ };
32
+ }
33
+ };
34
+ //#endregion
35
+ //#region src/issue/check.ts
96
36
  function isIssuePath(input) {
97
- if (!Array.isArray(input)) {
98
- return false;
99
- }
100
- return input.every((el)=>typeof el === 'string' || typeof el === 'number' || typeof el === 'symbol');
37
+ if (!Array.isArray(input)) return false;
38
+ return input.every((el) => typeof el === "string" || typeof el === "number" || typeof el === "symbol");
101
39
  }
102
40
  function isBaseIssue(input) {
103
- if (!isObject(input)) {
104
- return false;
105
- }
106
- if (typeof input.message !== 'string') {
107
- return false;
108
- }
109
- if (!isIssuePath(input.path)) {
110
- return false;
111
- }
112
- return typeof input.meta === 'undefined' || isObject(input.meta);
41
+ if (!isObject(input)) return false;
42
+ if (typeof input.message !== "string") return false;
43
+ if (!isIssuePath(input.path)) return false;
44
+ return typeof input.meta === "undefined" || isObject(input.meta);
113
45
  }
114
46
  function isIssueItem(input) {
115
- if (!isBaseIssue(input)) {
116
- return false;
117
- }
118
- if (input.type !== 'item') {
119
- return false;
120
- }
121
- return typeof input.code === 'string';
47
+ if (!isBaseIssue(input)) return false;
48
+ if (input.type !== "item") return false;
49
+ return typeof input.code === "string";
122
50
  }
123
51
  function isIssueGroup(input) {
124
- if (!isBaseIssue(input)) {
125
- return false;
126
- }
127
- if (input.type !== 'group') {
128
- return false;
129
- }
130
- return Array.isArray(input.issues) && input.issues.every((issue)=>isIssueItem(issue) || isIssueGroup(issue));
52
+ if (!isBaseIssue(input)) return false;
53
+ if (input.type !== "group") return false;
54
+ return Array.isArray(input.issues) && input.issues.every((issue) => isIssueItem(issue) || isIssueGroup(issue));
131
55
  }
132
56
  function isIssue(input) {
133
- return isIssueGroup(input) || isIssueItem(input);
57
+ return isIssueGroup(input) || isIssueItem(input);
134
58
  }
135
-
136
- /*
137
- * Copyright (c) 2026.
138
- * Author Peter Placzek (tada5hi)
139
- * For the full copyright and license information,
140
- * view the LICENSE file that was distributed with this source code.
141
- */ var IssueCode = /*#__PURE__*/ function(IssueCode) {
142
- IssueCode["VALUE_INVALID"] = "value_invalid";
143
- IssueCode["ONE_OF_FAILED"] = "one_of_failed";
144
- return IssueCode;
145
- }({});
146
-
59
+ //#endregion
60
+ //#region src/issue/constants.ts
61
+ /**
62
+ * Vocabulary of well-known issue codes. Adapter packages map foreign
63
+ * validator codes onto these so consumer-side translation catalogs
64
+ * (e.g. `@ilingo/validup`) can ship one localized message per code
65
+ * instead of falling back to a generic "invalid value" fallback.
66
+ *
67
+ * Tracks the common ground between vuelidate, zod, joi, and yup. The
68
+ * core lifts from vuelidate's catalog (snake_cased to match validup's
69
+ * convention); modern format codes (`PATTERN`, `UUID`, `DATE`,
70
+ * `JSON`, `BASE64`, `STRONG_PASSWORD`, …) cover ground vuelidate
71
+ * predates. Every format code names the format positively (`UUID`,
72
+ * `EMAIL`, `URL`, …) rather than the failure mode (`NOT_UUID`,
73
+ * `INVALID_EMAIL`) so the registry reads consistently.
74
+ *
75
+ * Ad-hoc / project-specific codes still work — `IssueItem.code` is
76
+ * widened to `IssueCode | (string & {})`, so `defineIssueItem({ code:
77
+ * 'email_taken', ... })` is valid. If you want a typed const for your
78
+ * own codes, define one alongside this one:
79
+ *
80
+ * ```ts
81
+ * import { IssueCode } from 'validup';
82
+ *
83
+ * export const AppCode = {
84
+ * ...IssueCode,
85
+ * EMAIL_TAKEN: 'email_taken',
86
+ * } as const;
87
+ * ```
88
+ *
89
+ * Each entry's JSDoc documents the structured `data` adapters should
90
+ * attach when constructing the issue — templates can rely on those
91
+ * placeholders being present (`{{min}}`, `{{max}}`, `{{other}}`, etc.).
92
+ */
93
+ const IssueCode = {
94
+ /** Generic fallback when no more-specific code applies. `data`: — */
95
+ VALUE_INVALID: "value_invalid",
96
+ /** Every branch of a `oneOf` container failed. `data`: — */
97
+ ONE_OF_FAILED: "one_of_failed",
98
+ /** Value is missing, `undefined`, `null`, or empty per the validator's semantics. `data`: — */
99
+ REQUIRED: "required",
100
+ /** Value contains characters outside the alphabetical set. `data`: — */
101
+ ALPHA: "alpha",
102
+ /** Value contains characters outside the alphanumeric set. `data`: — */
103
+ ALPHA_NUM: "alpha_num",
104
+ /** Value is not a number. `data`: — */
105
+ NUMERIC: "numeric",
106
+ /** Value is not an integer. `data`: — */
107
+ INTEGER: "integer",
108
+ /** Value is not a decimal number. `data`: — */
109
+ DECIMAL: "decimal",
110
+ /** Value is shorter than the configured minimum. `data`: `{ min: number }` */
111
+ MIN_LENGTH: "min_length",
112
+ /** Value is longer than the configured maximum. `data`: `{ max: number }` */
113
+ MAX_LENGTH: "max_length",
114
+ /** Numeric value is below the configured minimum. `data`: `{ min: number }` */
115
+ MIN_VALUE: "min_value",
116
+ /** Numeric value is above the configured maximum. `data`: `{ max: number }` */
117
+ MAX_VALUE: "max_value",
118
+ /** Numeric value falls outside the configured `[min, max]` range. `data`: `{ min: number, max: number }` */
119
+ BETWEEN: "between",
120
+ /** Value is not a valid email address. `data`: — */
121
+ EMAIL: "email",
122
+ /** Value is not a valid URL. `data`: — */
123
+ URL: "url",
124
+ /** Value is not a valid IP address. `data`: — */
125
+ IP_ADDRESS: "ip_address",
126
+ /** Value is not a valid MAC address. `data`: — */
127
+ MAC_ADDRESS: "mac_address",
128
+ /** Value is not a valid UUID. `data`: — */
129
+ UUID: "uuid",
130
+ /** Value is not a valid date / cannot be parsed as a date. `data`: — */
131
+ DATE: "date",
132
+ /**
133
+ * Value does not match the expected regex pattern. `data`:
134
+ * `{ pattern: string }` — source of the regex without flags so
135
+ * catalogs can quote it in human-readable form.
136
+ */
137
+ PATTERN: "pattern",
138
+ /** Value is not valid JSON. `data`: — */
139
+ JSON: "json",
140
+ /** Value is not valid base64. `data`: — */
141
+ BASE64: "base64",
142
+ /**
143
+ * Value does not meet the configured strong-password rules. `data`:
144
+ * `{ minLength?: number, minLowercase?: number, minUppercase?: number,
145
+ * minNumbers?: number, minSymbols?: number }` — only the keys the
146
+ * adapter chose to surface; missing keys mean "the default for that
147
+ * setting wasn't configured."
148
+ */
149
+ STRONG_PASSWORD: "strong_password",
150
+ /**
151
+ * Value must equal another named field's value (sibling-field assertion,
152
+ * e.g. password-confirm). `data`: `{ other: string }` — the name of
153
+ * the field being compared against.
154
+ */
155
+ SAME_AS: "same_as"
156
+ };
157
+ //#endregion
158
+ //#region src/issue/define.ts
159
+ /**
160
+ * Build an `IssueItem`. TS uses the supplied `code` to pick the right
161
+ * `data` requirement at the call site — passing `MIN_LENGTH` without
162
+ * `data: { min }` is a compile error; passing `STRONG_PASSWORD` with
163
+ * `data: { pointsPerUnique: 5 }` is a compile error.
164
+ *
165
+ * `code` may be omitted (defaults to `IssueCode.VALUE_INVALID` — bare,
166
+ * no data).
167
+ */
147
168
  function defineIssueItem(data) {
148
- return {
149
- type: 'item',
150
- ...data,
151
- code: IssueCode.VALUE_INVALID || data.code
152
- };
169
+ return {
170
+ type: "item",
171
+ ...data,
172
+ code: data.code || IssueCode.VALUE_INVALID
173
+ };
153
174
  }
154
175
  function defineIssueGroup(data) {
155
- return {
156
- type: 'group',
157
- ...data
158
- };
176
+ return {
177
+ type: "group",
178
+ ...data
179
+ };
159
180
  }
160
-
181
+ //#endregion
182
+ //#region src/issue/flatten.ts
183
+ function flattenIssueItems(issues) {
184
+ const output = [];
185
+ for (const issue of issues) if (isIssueItem(issue)) output.push(issue);
186
+ else output.push(...flattenIssueItems(issue.issues));
187
+ return output;
188
+ }
189
+ function flattenIssueGroups(issues) {
190
+ const output = [];
191
+ for (const issue of issues) if (isIssueGroup(issue)) {
192
+ output.push(issue);
193
+ output.push(...flattenIssueGroups(issue.issues));
194
+ }
195
+ return output;
196
+ }
197
+ //#endregion
198
+ //#region src/issue/format.ts
199
+ /**
200
+ * Render an issue's user-facing message.
201
+ *
202
+ * Resolution order:
203
+ * 1. If `templates[code]` exists, return `interpolate(template, issue.data)`.
204
+ * 2. Else return `issue.message` (the default English rendering set at
205
+ * construction time).
206
+ * 3. Else return `fallback`.
207
+ */
208
+ function formatIssue(issue, templates, fallback = "") {
209
+ if (templates && issue.code) {
210
+ const template = templates[issue.code];
211
+ if (typeof template === "string") return interpolate$1(template, issue.data || {});
212
+ }
213
+ if (typeof issue.message === "string" && issue.message.length > 0) return issue.message;
214
+ return fallback;
215
+ }
216
+ //#endregion
217
+ //#region src/error/check.ts
161
218
  function isError(input) {
162
- if (!isObject(input)) {
163
- return false;
164
- }
165
- return typeof input.message === 'string';
219
+ if (input instanceof Error) return true;
220
+ if (!isObject(input)) return false;
221
+ return typeof input.message === "string" && typeof input.name === "string";
166
222
  }
167
223
  function isValidupError(error) {
168
- if (!isError(error)) {
169
- return false;
170
- }
171
- if (error instanceof ValidupError) {
172
- return true;
173
- }
174
- if (!hasOwnProperty(error, 'issues')) {
175
- return false;
176
- }
177
- return Array.isArray(error.issues) && error.issues.every((issue)=>isIssue(issue));
224
+ if (!isError(error)) return false;
225
+ if (error instanceof ValidupError) return true;
226
+ if (!hasOwnProperty(error, "issues")) return false;
227
+ return Array.isArray(error.issues) && error.issues.every((issue) => isIssue(issue));
178
228
  }
179
-
180
- function isContainer(input) {
181
- return isObject(input) && typeof input.run === 'function' && typeof input.safeRun === 'function';
229
+ //#endregion
230
+ //#region src/helpers/error-to-issues.ts
231
+ /**
232
+ * The "given an unknown throw, produce `Issue[]`" cascade shared by
233
+ * the validator-orchestrating helpers. The branching is identical
234
+ * at each site — `ValidupError` fans out, `Error` becomes one item,
235
+ * anything else gets a defensive stringify — so it lives here.
236
+ *
237
+ * - `ValidupError` → returns a fresh array containing each of its
238
+ * `issues` verbatim (callers can map/prefix after).
239
+ * - `Error` → returns one `IssueItem` carrying the message + supplied
240
+ * code/path.
241
+ * - Anything else (string, plain object, `null`, …) → returns one
242
+ * defensively-stringified `IssueItem` so the aggregate is never
243
+ * silently missing a contributing failure.
244
+ *
245
+ * Callers layer their own per-site concerns on top of the returned
246
+ * issues: path prefixing, optional stamping, per-branch index
247
+ * stamping, etc.
248
+ */
249
+ function errorToIssues(error, options = {}) {
250
+ const code = options.code ?? IssueCode.VALUE_INVALID;
251
+ const path = options.path ?? [];
252
+ if (isValidupError(error)) return [...error.issues];
253
+ if (isError(error)) return [defineIssueItem({
254
+ path,
255
+ code,
256
+ message: error.message
257
+ })];
258
+ return [defineIssueItem({
259
+ path,
260
+ code,
261
+ message: typeof error === "string" && error.length > 0 ? error : `Non-Error throw: ${String(error)}`
262
+ })];
182
263
  }
183
-
184
- class Container {
185
- mount(...args) {
186
- if (args.length < 1) {
187
- throw new SyntaxError('The mount method requires at least one argument');
188
- }
189
- let path;
190
- let data;
191
- let dataIsContainer = false;
192
- let options = {};
193
- for(let i = 0; i < args.length; i++){
194
- const arg = args[i];
195
- if (typeof arg === 'string') {
196
- path = arg;
197
- continue;
198
- }
199
- if (typeof arg === 'function') {
200
- data = arg;
201
- continue;
202
- }
203
- if (isContainer(arg)) {
204
- data = arg;
205
- dataIsContainer = true;
206
- continue;
207
- }
208
- if (isObject(arg)) {
209
- options = args[i];
210
- }
211
- }
212
- if (!dataIsContainer && (typeof path === 'undefined' || path.length === 0)) {
213
- throw new SyntaxError('Only a container can be mounted without a key.');
214
- }
215
- if (typeof data === 'undefined') {
216
- throw new SyntaxError('No container/validator could be extracted from the fn arguments.');
217
- }
218
- if (isContainer(data)) {
219
- this.items.push({
220
- options,
221
- data,
222
- path,
223
- type: 'container'
224
- });
225
- return;
226
- }
227
- this.items.push({
228
- options,
229
- data,
230
- path,
231
- type: 'validator'
232
- });
233
- }
234
- // ----------------------------------------------
235
- /**
236
- * @throws ValidupError
237
- *
238
- * @param data
239
- * @param options
240
- */ async run(data = {}, options = {}) {
241
- let pathsToInclude;
242
- if (options.pathsToInclude) {
243
- pathsToInclude = options.pathsToInclude;
244
- } else if (this.options.pathsToInclude) {
245
- pathsToInclude = this.options.pathsToInclude;
246
- }
247
- let pathsToExclude;
248
- if (options.pathsToExclude) {
249
- pathsToExclude = options.pathsToExclude;
250
- } else if (this.options.pathsToInclude) {
251
- pathsToExclude = this.options.pathsToExclude;
252
- }
253
- const output = {};
254
- const issues = [];
255
- let itemCount = 0;
256
- let errorCount = 0;
257
- for(let i = 0; i < this.items.length; i++){
258
- const item = this.items[i];
259
- if (!this.isItemGroupIncluded(item, options.group)) {
260
- continue;
261
- }
262
- let pathCount = 0;
263
- let pathFailed = false;
264
- let keys;
265
- if (item.path) {
266
- keys = expandPath(data, item.path);
267
- } else {
268
- keys = [
269
- ''
270
- ];
271
- }
272
- for(let j = 0; j < keys.length; j++){
273
- const key = keys[j];
274
- const keyParts = key ? pathToArray(key) : [];
275
- const pathRelative = keyParts.at(-1);
276
- const pathAbsolute = [
277
- ...options.path ? options.path : [],
278
- ...keyParts
279
- ];
280
- let value;
281
- if (key.length > 0) {
282
- value = hasOwnProperty(output, key) ? output[key] : getPathValue(data, key);
283
- } else {
284
- value = data;
285
- }
286
- if (typeof pathsToInclude !== 'undefined' && pathsToInclude.indexOf(key) === -1) {
287
- continue;
288
- }
289
- if (typeof pathsToExclude !== 'undefined' && pathsToExclude.indexOf(key) !== -1) {
290
- continue;
291
- }
292
- try {
293
- if (item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
294
- if (item.options.optionalInclude) {
295
- output[key] = value;
296
- }
297
- } else if (item.type === 'container') {
298
- const tmp = await item.data.run(isObject(value) ? value : {}, {
299
- group: options.group,
300
- flat: true,
301
- path: pathAbsolute,
302
- pathsToInclude: options.pathsToInclude
303
- });
304
- const tmpKeys = Object.keys(tmp);
305
- for(let k = 0; k < tmpKeys.length; k++){
306
- output[this.mergePaths(key, tmpKeys[k])] = tmp[tmpKeys[k]];
307
- }
308
- } else if (item.type === 'validator') {
309
- output[key] = await item.data({
310
- key,
311
- path: pathAbsolute,
312
- value,
313
- data,
314
- group: options.group
315
- });
316
- }
317
- } catch (e) {
318
- const childIssues = [];
319
- if (isValidupError(e)) {
320
- for(let i = 0; i < e.issues.length; i++){
321
- const issue = e.issues[i];
322
- childIssues.push({
323
- ...issue,
324
- path: [
325
- ...keyParts,
326
- ...issue.path || []
327
- ]
328
- });
329
- }
330
- } else if (isError(e)) {
331
- childIssues.push(defineIssueItem({
332
- path: keyParts,
333
- message: e.message
334
- }));
335
- }
336
- if (pathRelative) {
337
- if (item.type === 'container' || childIssues.length > 1) {
338
- const group = defineIssueGroup({
339
- message: buildErrorMessageForAttribute(pathRelative),
340
- path: keyParts,
341
- issues: childIssues
342
- });
343
- issues.push(group);
344
- } else {
345
- issues.push(...childIssues);
346
- }
347
- } else {
348
- issues.push(...childIssues);
349
- }
350
- pathFailed = true;
351
- }
352
- pathCount++;
353
- }
354
- if (pathCount > 0) {
355
- itemCount++;
356
- if (pathFailed) {
357
- errorCount++;
358
- }
359
- }
360
- }
361
- if (this.options.oneOf) {
362
- if (errorCount === itemCount) {
363
- const group = defineIssueGroup({
364
- code: IssueCode.ONE_OF_FAILED,
365
- message: 'None of the branches succeeded',
366
- issues,
367
- path: options.path ? options.path : []
368
- });
369
- throw new ValidupError([
370
- group
371
- ]);
372
- }
373
- } else if (errorCount > 0) {
374
- throw new ValidupError(issues);
375
- }
376
- if (options.defaults) {
377
- const defaultKeys = Object.keys(options.defaults);
378
- for(let i = 0; i < defaultKeys.length; i++){
379
- if (!hasOwnProperty(output, defaultKeys[i]) || typeof output[defaultKeys[i]] === 'undefined') {
380
- output[defaultKeys[i]] = options.defaults[defaultKeys[i]];
381
- }
382
- }
383
- }
384
- if (options.flat) {
385
- return output;
386
- }
387
- const temp = {};
388
- const keys = Object.keys(output);
389
- for(let i = 0; i < keys.length; i++){
390
- setPathValue(temp, keys[i], output[keys[i]]);
391
- }
392
- return temp;
393
- }
394
- async safeRun(input = {}, options = {}) {
395
- try {
396
- const data = await this.run(input, options);
397
- return {
398
- success: true,
399
- data
400
- };
401
- } catch (e) {
402
- if (isValidupError(e)) {
403
- return {
404
- success: false,
405
- error: e
406
- };
407
- }
408
- if (isError(e)) {
409
- return {
410
- success: false,
411
- error: new ValidupError([
412
- defineIssueItem({
413
- path: [],
414
- message: e.message
415
- })
416
- ])
417
- };
418
- }
419
- return {
420
- success: false,
421
- error: new ValidupError()
422
- };
423
- }
424
- }
425
- isItemGroupIncluded(item, group) {
426
- if (group === GroupKey.WILDCARD) {
427
- return true;
428
- }
429
- if (item.options.group) {
430
- if (Array.isArray(item.options.group)) {
431
- if (item.options.group.indexOf(GroupKey.WILDCARD) !== -1) {
432
- return true;
433
- }
434
- if (group && item.options.group.indexOf(group) !== -1) {
435
- return true;
436
- }
437
- } else {
438
- if (item.options.group === GroupKey.WILDCARD) {
439
- return true;
440
- }
441
- if (item.options.group === group) {
442
- return true;
443
- }
444
- }
445
- return false;
446
- }
447
- return true;
448
- }
449
- mergePaths(...args) {
450
- let output = '';
451
- for(let i = 0; i < args.length; i++){
452
- const arg = args[i];
453
- if (!arg || arg.length === 0) {
454
- continue;
455
- }
456
- if (arg.at(0) === '.') {
457
- output += arg;
458
- } else {
459
- output += output.length > 0 ? `.${arg}` : arg;
460
- }
461
- }
462
- return output;
463
- }
464
- initialize() {}
465
- // ----------------------------------------------
466
- constructor(options = {}){
467
- this.options = options;
468
- this.items = [];
469
- this.initialize();
470
- }
264
+ //#endregion
265
+ //#region src/helpers/one-of-failed.ts
266
+ /**
267
+ * Build the `IssueGroup` that wraps an every-branch-failed aggregate
268
+ * — used by `composeAnyOf` (validator-level oneOf) AND
269
+ * `Container.finalizeOutput` (container-level `oneOf` option). Sharing
270
+ * the shape keeps the `IssueCode.ONE_OF_FAILED` contract symmetric so
271
+ * consumers / i18n catalogs only need one format for both modes.
272
+ */
273
+ function buildOneOfFailedGroup(branchIssues, options = {}) {
274
+ return defineIssueGroup({
275
+ code: IssueCode.ONE_OF_FAILED,
276
+ message: options.message ?? "None of the branches succeeded",
277
+ path: options.path ?? [],
278
+ issues: branchIssues
279
+ });
280
+ }
281
+ //#endregion
282
+ //#region src/helpers/compose.ts
283
+ /**
284
+ * Compose multiple validators into a single `Validator`.
285
+ *
286
+ * Default (`oneOf: false`) — validators run in order; each stage's
287
+ * return value feeds the next as `ctx.value`. A stage that returns
288
+ * `undefined` is treated as a pass-through (upstream value continues
289
+ * down the chain), so pure checks that don't re-emit `ctx.value`
290
+ * compose cleanly with transformers. `bail: true` (default) stops at
291
+ * the first failure; `bail: false` collects every failure into a
292
+ * single `ValidupError`.
293
+ *
294
+ * `oneOf: true` — branches run as alternatives in registration order;
295
+ * the first branch to succeed wins and subsequent branches are not
296
+ * invoked. When every branch fails, the composed validator throws a
297
+ * `ValidupError` whose first issue is an `IssueGroup` with
298
+ * `code: IssueCode.ONE_OF_FAILED` carrying every branch's failures.
299
+ *
300
+ * Elements can be bare `Validator<C>` functions OR fully-built
301
+ * `IContainer<T, C>` instances — the dispatcher detects which and
302
+ * either calls the function with the threaded `ctx` or invokes the
303
+ * container's `run(value, { group, context, signal, path })` with
304
+ * the threaded value as input. Containers participate with the same
305
+ * transform-or-throw contract; their output replaces the threaded
306
+ * value in the all-strategy chain, and a successful container wins
307
+ * the branch in `oneOf` mode.
308
+ *
309
+ * @example
310
+ * // Fail-fast (default) — sanitize then validate
311
+ * container.mount('email', compose([
312
+ * trim(),
313
+ * isEmail(),
314
+ * isLength({ max: 254 }),
315
+ * ]));
316
+ *
317
+ * // Collect-all — surface every broken rule for a richer error UI
318
+ * container.mount('password', compose([
319
+ * isLength({ min: 8 }),
320
+ * isAlphanumeric(),
321
+ * matches(/[0-9]/),
322
+ * ], { bail: false }));
323
+ *
324
+ * // Any-of — accept either an email or a phone number on the same field
325
+ * container.mount('contact', compose([
326
+ * isEmail(),
327
+ * isMobilePhone(),
328
+ * ], { oneOf: true }));
329
+ *
330
+ * // Any-of with a container branch — accept a contact string OR a
331
+ * // nested address object validated by its own container.
332
+ * container.mount('contact', composeOneOf([
333
+ * isEmail(),
334
+ * isMobilePhone(),
335
+ * addressContainer,
336
+ * ]));
337
+ *
338
+ * Throws that aren't `ValidupError` / `Error` (raw strings, plain
339
+ * objects, null) are synthesized into a single `IssueItem` so the
340
+ * aggregate is never silently missing a contributing failure — mirrors
341
+ * `Container.recordMountError`'s defensive behavior.
342
+ */
343
+ function compose(elements, options = {}) {
344
+ if (options.oneOf === true) return composeAnyOf(elements);
345
+ const bail = options.bail ?? true;
346
+ return async (ctx) => {
347
+ const issues = [];
348
+ let { value } = ctx;
349
+ for (const element of elements) try {
350
+ const result = await invokeComposeElement(element, {
351
+ ...ctx,
352
+ value
353
+ });
354
+ if (typeof result !== "undefined") value = result;
355
+ } catch (e) {
356
+ if (bail) throw e;
357
+ for (const issue of errorToIssues(e)) issues.push(issue);
358
+ }
359
+ if (issues.length > 0) throw new ValidupError(issues);
360
+ return value;
361
+ };
471
362
  }
363
+ /**
364
+ * Sugar for `compose(elements, { oneOf: true })`. Reads more
365
+ * naturally at the call site when the alternative semantic is the
366
+ * intent, mirrors `Container`'s own `oneOf` option.
367
+ */
368
+ function composeOneOf(elements) {
369
+ return compose(elements, { oneOf: true });
370
+ }
371
+ /**
372
+ * The `oneOf` execution path. Carved out so `compose`'s body stays
373
+ * focused on the all-strategy chain and so the abort / per-branch
374
+ * issue plumbing has somewhere to live without nesting.
375
+ *
376
+ * Each branch sees the original `ctx.value` (no threading across
377
+ * alternatives). The first defined return wins; an `undefined` return
378
+ * from a successful branch falls back to `ctx.value` so the
379
+ * pass-through rule stays symmetric with the all-strategy path.
380
+ *
381
+ * Aborts are re-raised verbatim from inside the try (matches Container
382
+ * behavior): a cancelled run isn't a validation outcome to wrap.
383
+ */
384
+ function composeAnyOf(elements) {
385
+ return async (ctx) => {
386
+ const branchIssues = [];
387
+ for (const [index, element] of elements.entries()) {
388
+ ctx.signal?.throwIfAborted();
389
+ try {
390
+ const result = await invokeComposeElement(element, { ...ctx });
391
+ return typeof result === "undefined" ? ctx.value : result;
392
+ } catch (e) {
393
+ if (ctx.signal?.aborted) throw e;
394
+ const wrapped = wrapBranchIssues(e, index);
395
+ for (const issue of wrapped) branchIssues.push(issue);
396
+ }
397
+ }
398
+ throw new ValidupError([buildOneOfFailedGroup(branchIssues)]);
399
+ };
400
+ }
401
+ /**
402
+ * Dispatch one compose element against the current `ctx`. Containers
403
+ * receive `ctx.value` as their input (normalised to `{}` for non-object
404
+ * values, mirroring how the `Container.run` loop handles a nested
405
+ * container mounted against a non-object value); validators receive
406
+ * `ctx` itself.
407
+ *
408
+ * Forwarded to the child container's `run`:
409
+ *
410
+ * - `group`, `context`, `signal` — the threaded run-level options
411
+ * surfaced on `ctx`. Letting the child see `ctx.signal` matters for
412
+ * aborting in-flight child validation when the outer run is
413
+ * cancelled.
414
+ * - `path: ctx.path` — used by the child's mounts to compute their
415
+ * own `ctx.path`, so a validator inside the child sees the
416
+ * absolute path it sits at (`['foo', 'street']`, not just
417
+ * `['street']`). Issue *paths* in the final thrown error don't
418
+ * depend on this forwarding — the outer Container's
419
+ * `prefixIssuePath` step rebuilds them from each level's own
420
+ * `keyParts` — but validators that inspect `ctx.path` (for
421
+ * logging, custom error formatting, etc.) would see a misleading
422
+ * relative path without it.
423
+ * - `cache: ctx.cache` — the outer Container surfaces its run-level
424
+ * `IResultCache` on `ctx`, so threading it here keeps a
425
+ * container-as-branch participating in the same per-mount cache
426
+ * the outer container is using. Without this forward, mounts
427
+ * inside a compose-branch container would silently bypass the
428
+ * cache, breaking the cache contract for the
429
+ * `composeOneOf([…, childContainer])` shape.
430
+ *
431
+ * Other run-level options (`pathsToInclude`, `pathsToExclude`,
432
+ * `defaults`, `parallel`) are intentionally NOT forwarded — they're
433
+ * normally narrowed per-mount by the parent's run loop
434
+ * (`resolvePathFilter`, `resolveDefaults`), and compose doesn't have
435
+ * the parent mount key it would need to compute the equivalent
436
+ * narrowing. A `composeOneOf` branch that's a container therefore
437
+ * runs all of its mounts regardless of the outer's include/exclude
438
+ * filter; if you need that level of inheritance, mount the container
439
+ * directly with `container.mount(...)` instead of routing it through
440
+ * compose.
441
+ */
442
+ async function invokeComposeElement(element, ctx) {
443
+ if (isContainer(element)) return element.run(isObject(ctx.value) ? ctx.value : {}, {
444
+ path: ctx.path,
445
+ group: ctx.group,
446
+ context: ctx.context,
447
+ signal: ctx.signal,
448
+ cache: ctx.cache
449
+ });
450
+ return element(ctx);
451
+ }
452
+ /**
453
+ * Normalize one branch's failure into `Issue[]` ready to merge into
454
+ * the outer `ONE_OF_FAILED` group. Each issue is tagged with
455
+ * `data: { branch: index }` so a tree-walking consumer can report
456
+ * "branch N failed because ..." without needing to reconstruct
457
+ * registration order.
458
+ *
459
+ * Delegates the unknown-throw → `Issue[]` fold to the shared
460
+ * `errorToIssues` cascade; only the per-branch stamping is local
461
+ * concern. Spread issues are shallow-cloned before stamping so the
462
+ * `ValidupError` instance's `issues` array on the caller side isn't
463
+ * mutated when a consumer reads `.data.branch` later.
464
+ */
465
+ function wrapBranchIssues(error, index) {
466
+ const stamp = (issue) => {
467
+ issue.data = {
468
+ ...issue.data ?? {},
469
+ branch: index
470
+ };
471
+ return issue;
472
+ };
473
+ return errorToIssues(error).map((issue) => stamp({ ...issue }));
474
+ }
475
+ //#endregion
476
+ //#region src/helpers/create-error.ts
477
+ /**
478
+ * Build a `ValidupError` carrying a single `IssueItem` with the supplied
479
+ * code / message / data. Sugar for the common one-issue failure
480
+ * construction used by adapters and hand-rolled validators.
481
+ *
482
+ * The caller throws — keeping the `throw` keyword at the call site
483
+ * makes the failure path obvious in the validator function body:
484
+ *
485
+ * ```ts
486
+ * if (!validator.isEmail(s)) {
487
+ * throw createValidupError(ctx.value, IssueCode.EMAIL, 'Invalid email');
488
+ * }
489
+ *
490
+ * if (!isInRange(s)) {
491
+ * throw createValidupError(ctx.value, IssueCode.MIN_VALUE, msg, { min: 18 });
492
+ * }
493
+ * ```
494
+ *
495
+ * The `code` you pass selects the `data` requirement at compile time:
496
+ * parameterized codes (`MIN_LENGTH`, `STRONG_PASSWORD`, …) require their
497
+ * typed payload; bare codes (`EMAIL`, `REQUIRED`, …) take no data; any
498
+ * other string falls through to an open `Record<string, unknown>` data
499
+ * argument.
500
+ *
501
+ * For multi-issue failures (e.g. inside {@link compose} with `{ bail: false }`),
502
+ * build a `ValidupError` directly with
503
+ * `new ValidupError([defineIssueItem(...), …])`.
504
+ */
505
+ function createValidupError(received, code, message, ...rest) {
506
+ const data = rest[0];
507
+ return new ValidupError([defineIssueItem({
508
+ path: [],
509
+ message,
510
+ code,
511
+ data,
512
+ received
513
+ })]);
514
+ }
515
+ //#endregion
516
+ //#region src/helpers/defaults.ts
517
+ /**
518
+ * Slice a parent `defaults` map down to entries that target paths inside a
519
+ * single nested container mount, with the mount-key prefix stripped so the
520
+ * child sees them as local keys. Exact-key matches (the default targets the
521
+ * mount root itself) are skipped — the parent's post-loop fill handles those
522
+ * once the child has returned, since the child is run with `flat: true` and
523
+ * cannot address its own root.
524
+ */
525
+ function resolveDefaults(defaults, key) {
526
+ if (typeof defaults === "undefined") return;
527
+ if (key.length === 0) return defaults;
528
+ const output = {};
529
+ let matched = false;
530
+ const keys = Object.keys(defaults);
531
+ for (const k of keys) if (k.startsWith(`${key}.`)) {
532
+ output[k.slice(key.length + 1)] = defaults[k];
533
+ matched = true;
534
+ }
535
+ return matched ? output : void 0;
536
+ }
537
+ //#endregion
538
+ //#region src/helpers/error.ts
539
+ function buildErrorMessageForAttribute(key) {
540
+ return `Property ${String(key)} is invalid`;
541
+ }
542
+ function buildErrorMessageForAttributes(input) {
543
+ let names;
544
+ if (Array.isArray(input)) names = distinctArray(input);
545
+ else names = Object.keys(input);
546
+ if (names.length === 0) return "Properties are invalid";
547
+ if (names.length > 1) return `Properties ${names.join(", ")} are invalid.`;
548
+ return buildErrorMessageForAttribute(names[0]);
549
+ }
550
+ //#endregion
551
+ //#region src/constants.ts
552
+ let GroupKey = /* @__PURE__ */ function(GroupKey) {
553
+ GroupKey["WILDCARD"] = "*";
554
+ return GroupKey;
555
+ }({});
556
+ let OptionalValue = /* @__PURE__ */ function(OptionalValue) {
557
+ /**
558
+ * Treats only `undefined` as optional. Default.
559
+ */
560
+ OptionalValue["UNDEFINED"] = "undefined";
561
+ /**
562
+ * Treats `null` and `undefined` as optional.
563
+ */
564
+ OptionalValue["NULL"] = "null";
565
+ /**
566
+ * Treats any JS falsy value as optional — `undefined`, `null`, `false`,
567
+ * `0`, `''`, `NaN`.
568
+ *
569
+ * **Warning**: this includes `0` and `''`. For quantity / numeric fields
570
+ * where `0` is a meaningful value, prefer the predicate form
571
+ * `optional: (value) => boolean` so you keep control over what counts as
572
+ * missing (e.g. `optional: (v) => v === '' || v === undefined` drops the
573
+ * empty string but keeps `0`).
574
+ */
575
+ OptionalValue["FALSY"] = "falsy";
576
+ return OptionalValue;
577
+ }({});
578
+ //#endregion
579
+ //#region src/helpers/optional-value.ts
580
+ /**
581
+ * Check if input value (type of) satisfies optional value type constraint.
582
+ *
583
+ * @param value
584
+ * @param optionalValue
585
+ */
586
+ function isOptionalValue(value, optionalValue) {
587
+ const optionValueNormalized = optionalValue || "undefined";
588
+ if (optionValueNormalized === "null") return value === null || typeof value === "undefined";
589
+ if (optionValueNormalized === "undefined") return typeof value === "undefined";
590
+ return !value;
591
+ }
592
+ //#endregion
593
+ //#region src/helpers/path-filter.ts
594
+ /**
595
+ * Resolve `pathsToInclude` / `pathsToExclude` against a single mounted item's
596
+ * (already-expanded) local `key`. Returns whether to skip the item, plus the
597
+ * filter sub-lists to forward into a child container — with the parent prefix
598
+ * stripped so the child can match purely against its own local keys.
599
+ *
600
+ * Semantics:
601
+ * - Un-keyed container mount (`key === ''`) shares the parent's namespace, so
602
+ * filters are forwarded verbatim.
603
+ * - Exact match in `pathsToInclude` / `pathsToExclude` matches the whole mount.
604
+ * - Prefix match (`<key>.…`) only descends into container mounts; leaf
605
+ * validators with deeper-target filters fall through (skipped for include,
606
+ * kept for exclude).
607
+ */
608
+ function resolvePathFilter(pathsToInclude, pathsToExclude, key, isContainer) {
609
+ if (key.length === 0) return {
610
+ skip: false,
611
+ pathsToInclude,
612
+ pathsToExclude
613
+ };
614
+ let includeForward;
615
+ if (typeof pathsToInclude !== "undefined") {
616
+ let exact = false;
617
+ const stripped = [];
618
+ for (const path of pathsToInclude) if (path === key) exact = true;
619
+ else if (isContainer && path.startsWith(`${key}.`)) stripped.push(path.slice(key.length + 1));
620
+ if (exact) includeForward = void 0;
621
+ else if (stripped.length > 0) includeForward = stripped;
622
+ else return {
623
+ skip: true,
624
+ pathsToInclude: void 0,
625
+ pathsToExclude: void 0
626
+ };
627
+ }
628
+ let excludeForward;
629
+ if (typeof pathsToExclude !== "undefined") {
630
+ const stripped = [];
631
+ for (const path of pathsToExclude) {
632
+ if (path === key) return {
633
+ skip: true,
634
+ pathsToInclude: void 0,
635
+ pathsToExclude: void 0
636
+ };
637
+ if (isContainer && path.startsWith(`${key}.`)) stripped.push(path.slice(key.length + 1));
638
+ }
639
+ if (stripped.length > 0) excludeForward = stripped;
640
+ }
641
+ return {
642
+ skip: false,
643
+ pathsToInclude: includeForward,
644
+ pathsToExclude: excludeForward
645
+ };
646
+ }
647
+ //#endregion
648
+ //#region src/helpers/path-stringify.ts
649
+ /**
650
+ * Stringify path array to string.
651
+ *
652
+ * @param input
653
+ */
654
+ function stringifyPath(input) {
655
+ return arrayToPath(input);
656
+ }
657
+ //#endregion
658
+ //#region src/validator/check.ts
659
+ /**
660
+ * Duck-typed guard for {@link ValidatorDescriptor}. Used by `mount()` to
661
+ * distinguish a descriptor from a bare `Validator` function and from a
662
+ * nested `IContainer` (which is also an object but carries `run` /
663
+ * `safeRun` methods — the descriptor has a `run` function but no
664
+ * `safeRun`).
665
+ *
666
+ * Duck-typed (not `instanceof`) so descriptors built from a different
667
+ * copy of the package — adapters bundling their own `validup` dependency,
668
+ * pnpm workspaces with multiple installs — still round-trip cleanly.
669
+ */
670
+ function isValidatorDescriptor(input) {
671
+ if (!isObject(input)) return false;
672
+ return typeof input.run === "function" && typeof input.safeRun !== "function";
673
+ }
674
+ //#endregion
675
+ //#region src/validator/define.ts
676
+ /**
677
+ * Factory for a {@link ValidatorDescriptor}. Mirrors the
678
+ * `defineIssueItem` / `defineIssueGroup` shape used elsewhere in the
679
+ * library so authored validators get a stable, typed construction site.
680
+ *
681
+ * @example
682
+ * const validateEmailUnique = defineValidator({
683
+ * sideEffect: true,
684
+ * run: async (ctx) => {
685
+ * const taken = await api.isEmailTaken(ctx.value as string);
686
+ * if (taken) throw new Error('Email is already taken');
687
+ * return ctx.value;
688
+ * },
689
+ * });
690
+ */
691
+ function defineValidator(descriptor) {
692
+ return descriptor;
693
+ }
694
+ //#endregion
695
+ //#region src/container/run-sync-violation.ts
696
+ /**
697
+ * Thrown by `Container.runSync` when a validator returns a Promise or a
698
+ * nested container does not implement `runSync`. Marked separately from
699
+ * generic `Error` so the per-mount catch can re-throw it instead of folding
700
+ * it into the issue list (otherwise users would get "Property X is invalid"
701
+ * instead of the structural diagnostic).
702
+ *
703
+ * Internal — not exported from the package barrel.
704
+ */
705
+ var RunSyncViolationError = class extends Error {
706
+ name = "RunSyncViolationError";
707
+ };
708
+ /**
709
+ * Duck-typed check — robust against `instanceof` mismatches when a duplicate
710
+ * copy of the package exists in the dependency tree, or when the throw
711
+ * crosses a realm boundary. Mirrors the `isValidupError` pattern.
712
+ */
713
+ function isRunSyncViolation(e) {
714
+ if (e instanceof RunSyncViolationError) return true;
715
+ return typeof e === "object" && e !== null && e.name === "RunSyncViolationError";
716
+ }
717
+ //#endregion
718
+ //#region src/container/module.ts
719
+ var Container = class {
720
+ options;
721
+ items;
722
+ constructor(options = {}) {
723
+ this.options = options;
724
+ this.items = [];
725
+ this.initialize();
726
+ }
727
+ mount(...args) {
728
+ if (args.length < 1) throw new SyntaxError("The mount method requires at least one argument");
729
+ if (args.length > 3) throw new SyntaxError(`mount() accepts at most 3 arguments, got ${args.length}`);
730
+ let path;
731
+ let pathSeen = false;
732
+ let data;
733
+ let dataSeen = false;
734
+ let dataKind;
735
+ let options = {};
736
+ let optionsSeen = false;
737
+ for (const arg of args) {
738
+ if (typeof arg === "string") {
739
+ if (pathSeen) throw new SyntaxError("mount() received multiple string arguments — only one path is supported.");
740
+ pathSeen = true;
741
+ path = arg;
742
+ continue;
743
+ }
744
+ if (typeof arg === "function") {
745
+ if (dataSeen) throw new SyntaxError("mount() received multiple validator/container arguments.");
746
+ dataSeen = true;
747
+ data = arg;
748
+ dataKind = "validator";
749
+ continue;
750
+ }
751
+ if (isContainer(arg)) {
752
+ if (dataSeen) throw new SyntaxError("mount() received multiple validator/container arguments.");
753
+ dataSeen = true;
754
+ data = arg;
755
+ dataKind = "container";
756
+ continue;
757
+ }
758
+ if (isValidatorDescriptor(arg)) {
759
+ if (dataSeen) throw new SyntaxError("mount() received multiple validator/container arguments.");
760
+ dataSeen = true;
761
+ data = arg;
762
+ dataKind = "descriptor";
763
+ continue;
764
+ }
765
+ if (isObject(arg)) {
766
+ if (optionsSeen) throw new SyntaxError("mount() received multiple options objects.");
767
+ optionsSeen = true;
768
+ options = arg;
769
+ }
770
+ }
771
+ if (dataKind !== "container" && (typeof path === "undefined" || path.length === 0)) throw new SyntaxError("Only a container can be mounted without a key.");
772
+ if (typeof data === "undefined" || typeof dataKind === "undefined") throw new SyntaxError("No container/validator could be extracted from the fn arguments.");
773
+ if (dataKind === "container") {
774
+ this.items.push({
775
+ options,
776
+ data,
777
+ path,
778
+ type: "container"
779
+ });
780
+ return;
781
+ }
782
+ if (dataKind === "descriptor") {
783
+ const descriptor = data;
784
+ this.items.push({
785
+ options,
786
+ data: descriptor.run,
787
+ path,
788
+ type: "validator",
789
+ sideEffect: descriptor.sideEffect
790
+ });
791
+ return;
792
+ }
793
+ this.items.push({
794
+ options,
795
+ data,
796
+ path,
797
+ type: "validator"
798
+ });
799
+ }
800
+ /**
801
+ * Run the container against `data`. Default execution mode — async,
802
+ * sequential, throws `ValidupError` on validation failure.
803
+ *
804
+ * Variants for the other execution modes:
805
+ * - `run(data, { parallel: true })` — async, sequential→concurrent. Each
806
+ * mount captures `value` from `data` before any sibling runs, so chained
807
+ * sanitize-then-validate patterns are not supported.
808
+ * - {@link Container.safeRun} — same as `run` but returns a discriminated
809
+ * `Result<T>` instead of throwing on validation failure (still rethrows
810
+ * on abort).
811
+ * - {@link Container.runSync} / {@link Container.safeRunSync} — synchronous
812
+ * variants for graphs where every validator (and every nested container's
813
+ * `runSync`) is synchronous.
814
+ *
815
+ * Aborts surface verbatim — the abort is detected via `signal.throwIfAborted()`
816
+ * between mounts (which throws `signal.reason`), and any error raised by a
817
+ * mid-flight validator during an aborted run is re-thrown as-is rather than
818
+ * folded into the issue tree. Callers can therefore distinguish "validation
819
+ * failed" from "operation cancelled," but should not assume the thrown value
820
+ * is always `signal.reason` — a validator that throws its own error before
821
+ * the next abort check produces that error instead.
822
+ *
823
+ * @throws ValidupError on validation failure.
824
+ * @throws signal.reason when the abort check fires between mounts.
825
+ * @throws (mid-flight validator error) when a validator throws during an
826
+ * already-aborted run — re-raised as-is rather than wrapped.
827
+ */
828
+ async run(data = {}, options = {}) {
829
+ if (options.parallel) return this.runParallel(data, options);
830
+ const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);
831
+ const output = {};
832
+ const issues = [];
833
+ let itemCount = 0;
834
+ let errorCount = 0;
835
+ for (let i = 0; i < this.items.length; i++) {
836
+ options.signal?.throwIfAborted();
837
+ const item = this.items[i];
838
+ if (!this.isItemGroupIncluded(item, options.group)) continue;
839
+ let pathCount = 0;
840
+ let pathFailed = false;
841
+ const branchStart = issues.length;
842
+ const keys = item.path ? expandPath(data, item.path) : [""];
843
+ for (const key of keys) {
844
+ const keyParts = key ? pathToArray(key) : [];
845
+ const pathRelative = keyParts.at(-1);
846
+ const pathAbsolute = [...options.path ? options.path : [], ...keyParts];
847
+ let value;
848
+ if (key.length > 0) value = hasOwnProperty(output, key) ? output[key] : getPathValue(data, key);
849
+ else value = data;
850
+ const filter = resolvePathFilter(pathsToInclude, pathsToExclude, key, item.type === "container");
851
+ if (filter.skip) continue;
852
+ try {
853
+ if (typeof item.options.optional === "function" ? item.options.optional(value) : item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
854
+ if (item.options.optionalInclude) output[key] = value;
855
+ } else if (item.type === "container") {
856
+ const tmp = await item.data.run(isObject(value) ? value : {}, {
857
+ group: options.group,
858
+ flat: true,
859
+ path: pathAbsolute,
860
+ pathsToInclude: filter.pathsToInclude,
861
+ pathsToExclude: filter.pathsToExclude,
862
+ defaults: resolveDefaults(options.defaults, key),
863
+ context: options.context,
864
+ signal: options.signal,
865
+ cache: options.cache
866
+ });
867
+ const tmpKeys = Object.keys(tmp);
868
+ for (const tmpKey of tmpKeys) output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];
869
+ } else if (item.type === "validator") {
870
+ const snapshot = {
871
+ value,
872
+ context: options.context,
873
+ group: options.group
874
+ };
875
+ const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);
876
+ if (cached) if (cached.ok) output[key] = cached.value;
877
+ else throw cached.error;
878
+ else try {
879
+ const result = await item.data({
880
+ key,
881
+ path: pathAbsolute,
882
+ value,
883
+ data,
884
+ group: options.group,
885
+ context: options.context,
886
+ signal: options.signal,
887
+ cache: options.cache
888
+ });
889
+ output[key] = result;
890
+ this.writeCachedOutcome(item, key, snapshot, {
891
+ ok: true,
892
+ value: result
893
+ }, options.cache, options.signal);
894
+ } catch (e) {
895
+ this.writeCachedOutcome(item, key, snapshot, {
896
+ ok: false,
897
+ error: e
898
+ }, options.cache, options.signal);
899
+ throw e;
900
+ }
901
+ }
902
+ } catch (e) {
903
+ this.collectExecutionFailure({
904
+ error: e,
905
+ item,
906
+ value,
907
+ keyParts,
908
+ pathRelative,
909
+ issues,
910
+ signal: options.signal
911
+ });
912
+ pathFailed = true;
913
+ }
914
+ pathCount++;
915
+ }
916
+ if (pathCount > 0) {
917
+ itemCount++;
918
+ if (pathFailed) {
919
+ errorCount++;
920
+ this.wrapBranchForOneOf(issues, branchStart, item, i);
921
+ }
922
+ }
923
+ }
924
+ return this.finalizeOutput(output, options, issues, errorCount, itemCount);
925
+ }
926
+ /**
927
+ * Parallel-execution variant of `run()`. All mounts kick off their
928
+ * promises eagerly and the results are merged after `Promise.allSettled`.
929
+ * See `ContainerRunOptions.parallel` for the trade-off note.
930
+ */
931
+ async runParallel(data, options) {
932
+ const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);
933
+ const output = {};
934
+ const issues = [];
935
+ const itemGroups = [];
936
+ for (let i = 0; i < this.items.length; i++) {
937
+ options.signal?.throwIfAborted();
938
+ const item = this.items[i];
939
+ if (!this.isItemGroupIncluded(item, options.group)) continue;
940
+ const tasks = [];
941
+ let syncPathCount = 0;
942
+ const keys = item.path ? expandPath(data, item.path) : [""];
943
+ for (const key of keys) {
944
+ const keyParts = key ? pathToArray(key) : [];
945
+ const pathRelative = keyParts.at(-1);
946
+ const pathAbsolute = [...options.path ? options.path : [], ...keyParts];
947
+ let value;
948
+ if (key.length > 0) value = getPathValue(data, key);
949
+ else value = data;
950
+ const filter = resolvePathFilter(pathsToInclude, pathsToExclude, key, item.type === "container");
951
+ if (filter.skip) continue;
952
+ if (typeof item.options.optional === "function" ? item.options.optional(value) : item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
953
+ if (item.options.optionalInclude) output[key] = value;
954
+ syncPathCount++;
955
+ continue;
956
+ }
957
+ let promise;
958
+ if (item.type === "container") promise = item.data.run(isObject(value) ? value : {}, {
959
+ group: options.group,
960
+ flat: true,
961
+ path: pathAbsolute,
962
+ pathsToInclude: filter.pathsToInclude,
963
+ pathsToExclude: filter.pathsToExclude,
964
+ defaults: resolveDefaults(options.defaults, key),
965
+ context: options.context,
966
+ signal: options.signal,
967
+ parallel: true,
968
+ cache: options.cache
969
+ });
970
+ else {
971
+ const snapshot = {
972
+ value,
973
+ context: options.context,
974
+ group: options.group
975
+ };
976
+ const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);
977
+ if (cached) promise = cached.ok ? Promise.resolve(cached.value) : Promise.reject(cached.error);
978
+ else {
979
+ const itemData = item.data;
980
+ const captureItem = item;
981
+ const captureKey = key;
982
+ const captureSnapshot = snapshot;
983
+ promise = (async () => {
984
+ try {
985
+ const result = await itemData({
986
+ key,
987
+ path: pathAbsolute,
988
+ value,
989
+ data,
990
+ group: options.group,
991
+ context: options.context,
992
+ signal: options.signal,
993
+ cache: options.cache
994
+ });
995
+ this.writeCachedOutcome(captureItem, captureKey, captureSnapshot, {
996
+ ok: true,
997
+ value: result
998
+ }, options.cache, options.signal);
999
+ return result;
1000
+ } catch (e) {
1001
+ this.writeCachedOutcome(captureItem, captureKey, captureSnapshot, {
1002
+ ok: false,
1003
+ error: e
1004
+ }, options.cache, options.signal);
1005
+ throw e;
1006
+ }
1007
+ })();
1008
+ }
1009
+ }
1010
+ tasks.push({
1011
+ key,
1012
+ keyParts,
1013
+ pathRelative,
1014
+ value,
1015
+ promise,
1016
+ kind: item.type
1017
+ });
1018
+ }
1019
+ if (tasks.length > 0 || syncPathCount > 0) itemGroups.push({
1020
+ item,
1021
+ mountIndex: i,
1022
+ tasks,
1023
+ syncPathCount
1024
+ });
1025
+ }
1026
+ const settledByGroup = await Promise.all(itemGroups.map((group) => Promise.allSettled(group.tasks.map((t) => t.promise))));
1027
+ options.signal?.throwIfAborted();
1028
+ let itemCount = 0;
1029
+ let errorCount = 0;
1030
+ for (const [i, { item, mountIndex, tasks, syncPathCount }] of itemGroups.entries()) {
1031
+ const settled = settledByGroup[i];
1032
+ let pathFailed = false;
1033
+ const branchStart = issues.length;
1034
+ for (const [j, task] of tasks.entries()) {
1035
+ const result = settled[j];
1036
+ if (result.status === "fulfilled") if (task.kind === "container") {
1037
+ const tmp = result.value;
1038
+ const tmpKeys = Object.keys(tmp);
1039
+ for (const tmpKey of tmpKeys) output[this.mergePaths(task.key, tmpKey)] = tmp[tmpKey];
1040
+ } else output[task.key] = result.value;
1041
+ else {
1042
+ this.collectExecutionFailure({
1043
+ error: result.reason,
1044
+ item,
1045
+ value: task.value,
1046
+ keyParts: task.keyParts,
1047
+ pathRelative: task.pathRelative,
1048
+ issues,
1049
+ signal: options.signal
1050
+ });
1051
+ pathFailed = true;
1052
+ }
1053
+ }
1054
+ if (tasks.length + syncPathCount > 0) {
1055
+ itemCount++;
1056
+ if (pathFailed) {
1057
+ errorCount++;
1058
+ this.wrapBranchForOneOf(issues, branchStart, item, mountIndex);
1059
+ }
1060
+ }
1061
+ }
1062
+ options.signal?.throwIfAborted();
1063
+ return this.finalizeOutput(output, options, issues, errorCount, itemCount);
1064
+ }
1065
+ async safeRun(input = {}, options = {}) {
1066
+ try {
1067
+ return {
1068
+ success: true,
1069
+ data: await this.run(input, options)
1070
+ };
1071
+ } catch (e) {
1072
+ return this.wrapSafeRunError(e, options);
1073
+ }
1074
+ }
1075
+ /**
1076
+ * Synchronous variant of {@link Container.run}. Use it for purely
1077
+ * synchronous validator graphs where the microtask overhead of `await`
1078
+ * per mount matters (e.g. driving a reactive UI without a `pending`
1079
+ * flicker on every keystroke).
1080
+ *
1081
+ * Each mounted validator's return value MUST NOT be a thenable, and every
1082
+ * nested container MUST implement `runSync`. Either violation throws
1083
+ * `RunSyncViolationError` (structural — distinct from validation
1084
+ * failures), so the diagnostic is surfaced verbatim rather than wrapped
1085
+ * into a `ValidupError`. The companion {@link Container.safeRunSync}
1086
+ * still rethrows these for the same reason.
1087
+ *
1088
+ * No `parallel` variant — synchronous graphs don't benefit from
1089
+ * concurrency, and `Promise.allSettled` is async by definition.
1090
+ *
1091
+ * Aborts surface the same way as {@link Container.run}: the
1092
+ * `signal.throwIfAborted()` check between mounts throws `signal.reason`,
1093
+ * and a mid-flight validator throw during an already-aborted run is
1094
+ * re-raised verbatim. Don't assume the thrown value is always
1095
+ * `signal.reason`.
1096
+ *
1097
+ * @throws ValidupError on validation failure.
1098
+ * @throws RunSyncViolationError when a validator returns a Promise or a
1099
+ * nested container does not implement `runSync`.
1100
+ * @throws signal.reason when the abort check fires between mounts.
1101
+ * @throws (mid-flight validator error) when a validator throws during an
1102
+ * already-aborted run.
1103
+ */
1104
+ runSync(data = {}, options = {}) {
1105
+ const { pathsToInclude, pathsToExclude } = this.resolveContainerFilters(options);
1106
+ const output = {};
1107
+ const issues = [];
1108
+ let itemCount = 0;
1109
+ let errorCount = 0;
1110
+ for (let i = 0; i < this.items.length; i++) {
1111
+ options.signal?.throwIfAborted();
1112
+ const item = this.items[i];
1113
+ if (!this.isItemGroupIncluded(item, options.group)) continue;
1114
+ let pathCount = 0;
1115
+ let pathFailed = false;
1116
+ const branchStart = issues.length;
1117
+ const keys = item.path ? expandPath(data, item.path) : [""];
1118
+ for (const key of keys) {
1119
+ const keyParts = key ? pathToArray(key) : [];
1120
+ const pathRelative = keyParts.at(-1);
1121
+ const pathAbsolute = [...options.path ? options.path : [], ...keyParts];
1122
+ let value;
1123
+ if (key.length > 0) value = hasOwnProperty(output, key) ? output[key] : getPathValue(data, key);
1124
+ else value = data;
1125
+ const filter = resolvePathFilter(pathsToInclude, pathsToExclude, key, item.type === "container");
1126
+ if (filter.skip) continue;
1127
+ try {
1128
+ if (typeof item.options.optional === "function" ? item.options.optional(value) : item.options.optional && isOptionalValue(value, item.options.optionalValue)) {
1129
+ if (item.options.optionalInclude) output[key] = value;
1130
+ } else if (item.type === "container") {
1131
+ const childRunSync = item.data.runSync;
1132
+ if (typeof childRunSync !== "function") throw new RunSyncViolationError(`runSync: nested container at "${key || "<root>"}" does not implement runSync`);
1133
+ const tmp = childRunSync.call(item.data, isObject(value) ? value : {}, {
1134
+ group: options.group,
1135
+ flat: true,
1136
+ path: pathAbsolute,
1137
+ pathsToInclude: filter.pathsToInclude,
1138
+ pathsToExclude: filter.pathsToExclude,
1139
+ defaults: resolveDefaults(options.defaults, key),
1140
+ context: options.context,
1141
+ signal: options.signal,
1142
+ cache: options.cache
1143
+ });
1144
+ const tmpKeys = Object.keys(tmp);
1145
+ for (const tmpKey of tmpKeys) output[this.mergePaths(key, tmpKey)] = tmp[tmpKey];
1146
+ } else if (item.type === "validator") {
1147
+ const snapshot = {
1148
+ value,
1149
+ context: options.context,
1150
+ group: options.group
1151
+ };
1152
+ const cached = this.resolveCachedOutcome(item, key, snapshot, options.cache);
1153
+ if (cached) if (cached.ok) output[key] = cached.value;
1154
+ else throw cached.error;
1155
+ else try {
1156
+ const result = item.data({
1157
+ key,
1158
+ path: pathAbsolute,
1159
+ value,
1160
+ data,
1161
+ group: options.group,
1162
+ context: options.context,
1163
+ signal: options.signal,
1164
+ cache: options.cache
1165
+ });
1166
+ if (result !== null && typeof result === "object" && typeof result.then === "function") throw new RunSyncViolationError(`runSync: validator at "${key || "<root>"}" returned a Promise`);
1167
+ output[key] = result;
1168
+ this.writeCachedOutcome(item, key, snapshot, {
1169
+ ok: true,
1170
+ value: result
1171
+ }, options.cache, options.signal);
1172
+ } catch (e) {
1173
+ if (!isRunSyncViolation(e)) this.writeCachedOutcome(item, key, snapshot, {
1174
+ ok: false,
1175
+ error: e
1176
+ }, options.cache, options.signal);
1177
+ throw e;
1178
+ }
1179
+ }
1180
+ } catch (e) {
1181
+ this.collectExecutionFailure({
1182
+ error: e,
1183
+ item,
1184
+ value,
1185
+ keyParts,
1186
+ pathRelative,
1187
+ issues,
1188
+ signal: options.signal
1189
+ });
1190
+ pathFailed = true;
1191
+ }
1192
+ pathCount++;
1193
+ }
1194
+ if (pathCount > 0) {
1195
+ itemCount++;
1196
+ if (pathFailed) {
1197
+ errorCount++;
1198
+ this.wrapBranchForOneOf(issues, branchStart, item, i);
1199
+ }
1200
+ }
1201
+ }
1202
+ return this.finalizeOutput(output, options, issues, errorCount, itemCount);
1203
+ }
1204
+ safeRunSync(input = {}, options = {}) {
1205
+ try {
1206
+ return {
1207
+ success: true,
1208
+ data: this.runSync(input, options)
1209
+ };
1210
+ } catch (e) {
1211
+ return this.wrapSafeRunError(e, options);
1212
+ }
1213
+ }
1214
+ /**
1215
+ * Lookup helper for the per-mount result cache.
1216
+ *
1217
+ * Returns `undefined` (forcing a real run) for any of:
1218
+ * - No `cache` supplied — caller didn't opt in.
1219
+ * - Mount isn't a validator — container mounts run their own
1220
+ * inner loop, which consults the cache for their own mounts.
1221
+ * - Validator declared `sideEffect: true` — its result depends on
1222
+ * inputs the snapshot doesn't capture (sibling fields, network,
1223
+ * global state), so caching would be unsound.
1224
+ * - No prior entry stored for this `(mount, key)` pair.
1225
+ * - Stored snapshot's `value` / `context` / `group` don't all match
1226
+ * the current invocation by `Object.is`.
1227
+ */
1228
+ resolveCachedOutcome(item, key, snapshot, cache) {
1229
+ if (!cache || item.type !== "validator" || item.sideEffect === true) return;
1230
+ const entry = cache.get(item, key);
1231
+ if (!entry) return;
1232
+ if (Object.is(entry.snapshot.value, snapshot.value) && Object.is(entry.snapshot.context, snapshot.context) && Object.is(entry.snapshot.group, snapshot.group)) return entry.outcome;
1233
+ }
1234
+ /**
1235
+ * Store the outcome of a fresh validator invocation. No-ops in the
1236
+ * same cases `resolveCachedOutcome` returns `undefined` for, plus:
1237
+ *
1238
+ * - `signal.aborted` — the throw was caused by cancellation, not by
1239
+ * a validation outcome we want to remember. Caching the abort
1240
+ * would mean future replays surface "AbortError" as a fake
1241
+ * validation issue every time the same snapshot is seen, even
1242
+ * in fully-completed runs.
1243
+ *
1244
+ * `RunSyncViolationError`s are filtered out at the call site
1245
+ * (`runSync` only) because they're structural — the validator
1246
+ * graph is wrong, not the input.
1247
+ */
1248
+ writeCachedOutcome(item, key, snapshot, outcome, cache, signal) {
1249
+ if (!cache || item.type !== "validator" || item.sideEffect === true || signal?.aborted) return;
1250
+ cache.set(item, key, {
1251
+ snapshot,
1252
+ outcome
1253
+ });
1254
+ }
1255
+ resolveContainerFilters(options) {
1256
+ let pathsToInclude;
1257
+ if (options.pathsToInclude) pathsToInclude = options.pathsToInclude;
1258
+ else if (this.options.pathsToInclude) pathsToInclude = this.options.pathsToInclude;
1259
+ let pathsToExclude;
1260
+ if (options.pathsToExclude) pathsToExclude = options.pathsToExclude;
1261
+ else if (this.options.pathsToExclude) pathsToExclude = this.options.pathsToExclude;
1262
+ return {
1263
+ pathsToInclude,
1264
+ pathsToExclude
1265
+ };
1266
+ }
1267
+ /**
1268
+ * Prepend `keyParts` to a child issue's `path` and — when the child is
1269
+ * an `IssueGroup` — recurse into its nested issues so every leaf carries
1270
+ * the parent prefix. Without recursion, a child container that already
1271
+ * wrapped its own multi-issue mount in a group (or a `oneOf` child) would
1272
+ * surface inner items with paths missing the parent segment, breaking
1273
+ * downstream consumers that rely on `flattenIssueItems` for per-field
1274
+ * lookup (e.g. `@validup/vue`).
1275
+ */
1276
+ prefixIssuePath(issue, keyParts) {
1277
+ const prefixed = {
1278
+ ...issue,
1279
+ path: [...keyParts, ...issue.path || []]
1280
+ };
1281
+ if (prefixed.type === "group") prefixed.issues = prefixed.issues.map((nested) => this.prefixIssuePath(nested, keyParts));
1282
+ return prefixed;
1283
+ }
1284
+ /**
1285
+ * Translate a throw raised by one execution step (one validator or
1286
+ * nested-container invocation, from the surrounding `run` loop) into
1287
+ * accumulated issues and push them onto `context.issues`. Re-throws when
1288
+ * the run was aborted (signal-aware validators) so abort errors are not
1289
+ * mangled into validation issues.
1290
+ *
1291
+ * "Mount" is the *setup-time* verb (`container.mount(...)`); what failed
1292
+ * here is the *execution* of an already-mounted unit — hence the name.
1293
+ *
1294
+ * The context object captures everything the error path needs to know
1295
+ * about the failing step: the thrown value (`error`), the mount
1296
+ * descriptor (`item`), the current input (`value` — kept around so we
1297
+ * can re-evaluate predicate-optional declarations at error time), the
1298
+ * expanded path (`keyParts` — used to prepend to nested `ValidupError`
1299
+ * issues) and the trailing segment (`pathRelative` — used when wrapping
1300
+ * multi-issue or container emissions into an `IssueGroup`). The
1301
+ * destination accumulator (`issues`) and the abort `signal` round out
1302
+ * what's needed to handle the failure.
1303
+ *
1304
+ * @modifies context.issues — appends one or more entries per call.
1305
+ */
1306
+ collectExecutionFailure(context) {
1307
+ const { error, item, value, keyParts, pathRelative, issues, signal } = context;
1308
+ if (signal?.aborted) throw error;
1309
+ if (isRunSyncViolation(error)) throw error;
1310
+ const isOptionalMount = typeof item.options.optional === "function" ? Boolean(item.options.optional(value)) : item.options.optional === true;
1311
+ const markOptional = (issue) => {
1312
+ if (!isOptionalMount) return issue;
1313
+ issue.meta = {
1314
+ ...issue.meta ?? {},
1315
+ optional: true
1316
+ };
1317
+ return issue;
1318
+ };
1319
+ const markOptionalDeep = (issue) => {
1320
+ if (!isOptionalMount) return issue;
1321
+ markOptional(issue);
1322
+ if (issue.type === "group") issue.issues = issue.issues.map((nested) => markOptionalDeep(nested));
1323
+ return issue;
1324
+ };
1325
+ const childIssues = [];
1326
+ if (isValidupError(error)) for (let i = 0; i < error.issues.length; i++) {
1327
+ const prefixed = this.prefixIssuePath(error.issues[i], keyParts);
1328
+ childIssues.push(item.type === "validator" ? markOptionalDeep(prefixed) : prefixed);
1329
+ }
1330
+ else if (isError(error)) childIssues.push(markOptional(defineIssueItem({
1331
+ path: keyParts,
1332
+ message: error.message
1333
+ })));
1334
+ else childIssues.push(markOptional(defineIssueItem({
1335
+ path: keyParts,
1336
+ message: typeof error === "string" && error.length > 0 ? error : `Non-Error throw: ${String(error)}`
1337
+ })));
1338
+ if (pathRelative) if (item.type === "container" || childIssues.length > 1) issues.push(markOptional(defineIssueGroup({
1339
+ message: buildErrorMessageForAttribute(String(pathRelative)),
1340
+ data: { name: String(pathRelative) },
1341
+ path: keyParts,
1342
+ issues: childIssues
1343
+ })));
1344
+ else issues.push(...childIssues);
1345
+ else issues.push(...childIssues);
1346
+ }
1347
+ /**
1348
+ * For `oneOf` containers, wrap the issues produced by a single branch
1349
+ * (slice from `branchStart` to the end of `issues`) into one sub-group
1350
+ * so per-branch identity is preserved in the final aggregate. Non-oneOf
1351
+ * containers leave the issue list untouched — they don't need branch
1352
+ * partitioning.
1353
+ *
1354
+ * The wrapping group's `path` is `[]` (the branch wraps everything
1355
+ * inside it; per-leaf paths are unchanged); `data.branch` is the
1356
+ * mount index; and `data.name` (when set) is the mount path so
1357
+ * consumers can label "branch X failed" without recomputing the
1358
+ * registration order.
1359
+ */
1360
+ wrapBranchForOneOf(issues, branchStart, item, branchIndex) {
1361
+ if (!this.options.oneOf) return;
1362
+ const branchIssues = issues.splice(branchStart);
1363
+ const data = { branch: branchIndex };
1364
+ if (item.path) data.name = item.path;
1365
+ issues.push(defineIssueGroup({
1366
+ message: item.path ? `Branch "${item.path}" failed` : `Branch ${branchIndex} failed`,
1367
+ data,
1368
+ path: [],
1369
+ issues: branchIssues
1370
+ }));
1371
+ }
1372
+ /**
1373
+ * Apply post-loop semantics: oneOf aggregation, error throw, defaults
1374
+ * fill, and flat-vs-nested output expansion.
1375
+ */
1376
+ finalizeOutput(output, options, issues, errorCount, itemCount) {
1377
+ if (this.options.oneOf) {
1378
+ if (itemCount > 0 && errorCount === itemCount) throw new ValidupError([buildOneOfFailedGroup(issues, { path: options.path ? options.path : [] })]);
1379
+ } else if (errorCount > 0) throw new ValidupError(issues);
1380
+ if (options.defaults) {
1381
+ const defaultKeys = Object.keys(options.defaults);
1382
+ for (const defaultKey of defaultKeys) if (!hasOwnProperty(output, defaultKey) || typeof output[defaultKey] === "undefined") output[defaultKey] = options.defaults[defaultKey];
1383
+ }
1384
+ if (options.flat) return output;
1385
+ const temp = {};
1386
+ const keys = Object.keys(output);
1387
+ for (const key of keys) setPathValue(temp, key, output[key]);
1388
+ return temp;
1389
+ }
1390
+ wrapSafeRunError(e, options) {
1391
+ if (options.signal?.aborted) throw e;
1392
+ if (isRunSyncViolation(e)) throw e;
1393
+ if (isValidupError(e)) return {
1394
+ success: false,
1395
+ error: e
1396
+ };
1397
+ if (isError(e)) return {
1398
+ success: false,
1399
+ error: new ValidupError([defineIssueItem({
1400
+ path: [],
1401
+ message: e.message
1402
+ })])
1403
+ };
1404
+ return {
1405
+ success: false,
1406
+ error: new ValidupError([defineIssueItem({
1407
+ path: [],
1408
+ message: typeof e === "string" && e.length > 0 ? e : `Non-Error throw: ${String(e)}`
1409
+ })])
1410
+ };
1411
+ }
1412
+ isItemGroupIncluded(item, group) {
1413
+ if (group === "*") return true;
1414
+ if (item.options.group) {
1415
+ if (Array.isArray(item.options.group)) {
1416
+ if (item.options.group.includes("*")) return true;
1417
+ if (group && item.options.group.includes(group)) return true;
1418
+ } else {
1419
+ if (item.options.group === "*") return true;
1420
+ if (item.options.group === group) return true;
1421
+ }
1422
+ return false;
1423
+ }
1424
+ return true;
1425
+ }
1426
+ /**
1427
+ * Join flat-output keys with `.` separators, preserving any pre-existing
1428
+ * leading dot on the right-hand side. Note: keys containing a *literal*
1429
+ * dot collide with the dotted-path syntax used for nested-output
1430
+ * expansion (see `setPathValue` in `pathtrace`) and will produce
1431
+ * ambiguous output when re-expanded — avoid mounting/returning such keys.
1432
+ */
1433
+ mergePaths(...args) {
1434
+ let output = "";
1435
+ for (const arg of args) {
1436
+ if (!arg || arg.length === 0) continue;
1437
+ if (arg.at(0) === ".") output += arg;
1438
+ else output += output.length > 0 ? `.${arg}` : arg;
1439
+ }
1440
+ return output;
1441
+ }
1442
+ initialize() {}
1443
+ };
1444
+ //#endregion
1445
+ //#region src/builder/module.ts
1446
+ function isBuilder(value) {
1447
+ return typeof value === "object" && value !== null && typeof value.build === "function" && typeof value.mount === "function";
1448
+ }
1449
+ var Builder = class Builder {
1450
+ options;
1451
+ steps;
1452
+ constructor(options, steps) {
1453
+ this.options = options;
1454
+ this.steps = steps;
1455
+ }
1456
+ mount(key, ...rest) {
1457
+ let options = {};
1458
+ let target;
1459
+ if (rest.length === 1) target = rest[0];
1460
+ else {
1461
+ options = rest[0];
1462
+ target = rest[1];
1463
+ }
1464
+ let step;
1465
+ if (isBuilder(target)) step = {
1466
+ kind: "nest",
1467
+ key,
1468
+ child: target.build(),
1469
+ options
1470
+ };
1471
+ else if (isContainer(target)) step = {
1472
+ kind: "nest",
1473
+ key,
1474
+ child: target,
1475
+ options
1476
+ };
1477
+ else step = {
1478
+ kind: "validator",
1479
+ key,
1480
+ validator: target,
1481
+ options
1482
+ };
1483
+ return new Builder(this.options, [...this.steps, step]);
1484
+ }
1485
+ oneOf() {
1486
+ return new Builder({
1487
+ ...this.options,
1488
+ oneOf: true
1489
+ }, this.steps);
1490
+ }
1491
+ pathsToInclude(...paths) {
1492
+ return new Builder({
1493
+ ...this.options,
1494
+ pathsToInclude: [...this.options.pathsToInclude ?? [], ...paths]
1495
+ }, this.steps);
1496
+ }
1497
+ pathsToExclude(...paths) {
1498
+ return new Builder({
1499
+ ...this.options,
1500
+ pathsToExclude: [...this.options.pathsToExclude ?? [], ...paths]
1501
+ }, this.steps);
1502
+ }
1503
+ build() {
1504
+ const container = new Container(this.options);
1505
+ for (const step of this.steps) if (step.kind === "nest") container.mount(step.key, step.options, step.child);
1506
+ else container.mount(step.key, step.options, step.validator);
1507
+ return container;
1508
+ }
1509
+ };
1510
+ /**
1511
+ * Entry point for the compile-time-typed schema builder. The accumulator
1512
+ * starts at `{}` and grows as `.mount(...)` calls are chained;
1513
+ * `.build()` returns a `Container<T, C>` whose `run()` reflects the
1514
+ * accumulated shape.
1515
+ *
1516
+ * Pass the context type as the generic parameter to flow it through nested
1517
+ * builders and validator factories: `defineSchema<MyContext>()`.
1518
+ */
1519
+ function defineSchema() {
1520
+ return new Builder({}, []);
1521
+ }
1522
+ //#endregion
1523
+ //#region src/cache/check.ts
1524
+ /**
1525
+ * Duck-typed guard for {@link IResultCache}. Avoids `instanceof`
1526
+ * checks so caches constructed from a different copy of the package
1527
+ * (workspaces with duplicated `validup` installs, adapter bundles)
1528
+ * still round-trip cleanly.
1529
+ */
1530
+ function isResultCache(input) {
1531
+ if (!isObject(input)) return false;
1532
+ return typeof input.get === "function" && typeof input.set === "function" && typeof input.delete === "function" && typeof input.clear === "function";
1533
+ }
1534
+ //#endregion
1535
+ //#region src/cache/module.ts
1536
+ /**
1537
+ * Default in-memory {@link IResultCache} implementation.
1538
+ *
1539
+ * Backed by a two-level `Map`:
1540
+ * - outer key — Mount reference (opaque object)
1541
+ * - inner key — expanded path (string)
1542
+ *
1543
+ * `Map` is used for both levels (rather than a `WeakMap` on the outer)
1544
+ * so `clear()` is supported. Cache entries become unreachable when the
1545
+ * owning composable / caller drops its reference to the
1546
+ * `ResultCache` instance; in the typical `@validup/vue` flow that
1547
+ * happens on `onScopeDispose`, which lines up with component unmount.
1548
+ *
1549
+ * Snapshot equality (the "is this still valid?" check) is the run
1550
+ * loop's job — see `container/module.ts`. This class is dumb storage.
1551
+ */
1552
+ var ResultCache = class {
1553
+ store;
1554
+ constructor() {
1555
+ this.store = /* @__PURE__ */ new Map();
1556
+ }
1557
+ get(mount, key) {
1558
+ return this.store.get(mount)?.get(key);
1559
+ }
1560
+ set(mount, key, entry) {
1561
+ let inner = this.store.get(mount);
1562
+ if (!inner) {
1563
+ inner = /* @__PURE__ */ new Map();
1564
+ this.store.set(mount, inner);
1565
+ }
1566
+ inner.set(key, entry);
1567
+ }
1568
+ delete(mount, key) {
1569
+ if (typeof key === "undefined") {
1570
+ this.store.delete(mount);
1571
+ return;
1572
+ }
1573
+ const inner = this.store.get(mount);
1574
+ if (!inner) return;
1575
+ inner.delete(key);
1576
+ if (inner.size === 0) this.store.delete(mount);
1577
+ }
1578
+ clear() {
1579
+ this.store.clear();
1580
+ }
1581
+ };
1582
+ //#endregion
1583
+ export { Builder, Container, GroupKey, IssueCode, OptionalValue, ResultCache, ValidupError, buildErrorMessageForAttribute, buildErrorMessageForAttributes, buildOneOfFailedGroup, compose, composeOneOf, createValidupError, defineIssueGroup, defineIssueItem, defineSchema, defineValidator, errorToIssues, flattenIssueGroups, flattenIssueItems, formatIssue, hasOwnProperty, interpolate, isContainer, isError, isIssue, isIssueGroup, isIssueItem, isObject, isOptionalValue, isResultCache, isValidatorDescriptor, isValidupError, resolveDefaults, resolvePathFilter, stringifyPath };
472
1584
 
473
- export { Container, GroupKey, IssueCode, OptionalValue, ValidupError, buildErrorMessageForAttribute, buildErrorMessageForAttributes, defineIssueGroup, defineIssueItem, hasOwnProperty, isContainer, isError, isIssue, isIssueGroup, isIssueItem, isObject, isOptionalValue, isValidupError, stringifyPath };
474
- //# sourceMappingURL=index.mjs.map
1585
+ //# sourceMappingURL=index.mjs.map