@orkestrel/contract 0.0.3 → 0.0.5

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.
@@ -26,6 +26,26 @@ var JSON_SCHEMA_TYPES = Object.freeze([
26
26
  "integer",
27
27
  "string"
28
28
  ]);
29
+ /**
30
+ * The maximum number of {@link Fault} entries a single `explain` report ever
31
+ * returns, frozen.
32
+ *
33
+ * @remarks
34
+ * Bounds the report against adversarial input (a giant array, a wide record) —
35
+ * `compileReporter` collects faults in stable pre-order and stops once this cap
36
+ * is reached, so the report size (and the work to build it) stays finite and
37
+ * deterministic regardless of the input's size.
38
+ */
39
+ var FAULT_LIMIT = 64;
40
+ /**
41
+ * The maximum character length of a {@link preview}-rendered string, frozen.
42
+ *
43
+ * @remarks
44
+ * A previewed string longer than this is clipped with a trailing `…` so a
45
+ * {@link Fault}'s `received` field never embeds an unbounded amount of
46
+ * untrusted text.
47
+ */
48
+ var PREVIEW_LIMIT = 64;
29
49
  //#endregion
30
50
  //#region src/core/validators.ts
31
51
  /** Determine whether a value is `null`.
@@ -62,7 +82,14 @@ function isUndefined(value) {
62
82
  function isDefined(value) {
63
83
  return value !== null && value !== void 0;
64
84
  }
65
- /** Determine whether a value is a string. */
85
+ /** Determine whether a value is a string.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * isString('hi') // true
90
+ * isString(42) // false
91
+ * ```
92
+ */
66
93
  function isString(value) {
67
94
  return typeof value === "string";
68
95
  }
@@ -71,11 +98,26 @@ function isString(value) {
71
98
  *
72
99
  * @remarks
73
100
  * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * isNumber(42) // true
105
+ * isNumber(Number.NaN) // true — NaN is still a number
106
+ * isNumber('42') // false
107
+ * ```
74
108
  */
75
109
  function isNumber(value) {
76
110
  return typeof value === "number";
77
111
  }
78
- /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`). */
112
+ /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * isFiniteNumber(42) // true
117
+ * isFiniteNumber(Number.NaN) // false
118
+ * isFiniteNumber(Infinity) // false
119
+ * ```
120
+ */
79
121
  function isFiniteNumber(value) {
80
122
  return typeof value === "number" && Number.isFinite(value);
81
123
  }
@@ -192,6 +234,35 @@ function isNullableNumber(value) {
192
234
  function isNullableBoolean(value) {
193
235
  return value === null || isBoolean(value);
194
236
  }
237
+ /**
238
+ * Determine whether a value is an instance of a constructor, contained against
239
+ * a throwing `instanceof` check.
240
+ *
241
+ * @remarks
242
+ * The low-level total helper every `instanceof`-based guard in this file (and
243
+ * the `instanceOf` combinator) routes through. A bare `value instanceof X` is
244
+ * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
245
+ * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
246
+ * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
247
+ * wraps the check in {@link attempt} (see ./helpers.js) so any such throw
248
+ * yields `false` instead of escaping.
249
+ *
250
+ * @param value - The value to test
251
+ * @param ctor - The constructor to test against
252
+ * @returns `true` when `value instanceof ctor`, `false` on a non-match or a
253
+ * contained throw
254
+ *
255
+ * @example
256
+ * ```ts
257
+ * isInstance(new Date(), Date) // true
258
+ * isInstance({}, Date) // false
259
+ * ```
260
+ */
261
+ function isInstance(value, ctor) {
262
+ const target = ctor;
263
+ const outcome = attempt(() => isFunction(target) && value instanceof target);
264
+ return outcome.success && outcome.value;
265
+ }
195
266
  /** Determine whether a value is a `Date`.
196
267
  *
197
268
  * @example
@@ -201,7 +272,7 @@ function isNullableBoolean(value) {
201
272
  * ```
202
273
  */
203
274
  function isDate(value) {
204
- return value instanceof Date;
275
+ return isInstance(value, Date);
205
276
  }
206
277
  /** Determine whether a value is a `RegExp`.
207
278
  *
@@ -212,7 +283,7 @@ function isDate(value) {
212
283
  * ```
213
284
  */
214
285
  function isRegExp(value) {
215
- return value instanceof RegExp;
286
+ return isInstance(value, RegExp);
216
287
  }
217
288
  /** Determine whether a value is an `Error`.
218
289
  *
@@ -223,7 +294,7 @@ function isRegExp(value) {
223
294
  * ```
224
295
  */
225
296
  function isError(value) {
226
- return value instanceof Error;
297
+ return isInstance(value, Error);
227
298
  }
228
299
  /** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).
229
300
  *
@@ -234,7 +305,7 @@ function isError(value) {
234
305
  * ```
235
306
  */
236
307
  function isPromise(value) {
237
- return value instanceof Promise;
308
+ return isInstance(value, Promise);
238
309
  }
239
310
  /**
240
311
  * Determine whether a value is promise-like — an object exposing callable
@@ -270,7 +341,7 @@ function isPromiseLike(value) {
270
341
  * ```
271
342
  */
272
343
  function isArrayBuffer(value) {
273
- return value instanceof ArrayBuffer;
344
+ return isInstance(value, ArrayBuffer);
274
345
  }
275
346
  /**
276
347
  * Determine whether a value is a `SharedArrayBuffer`.
@@ -286,7 +357,7 @@ function isArrayBuffer(value) {
286
357
  * ```
287
358
  */
288
359
  function isSharedArrayBuffer(value) {
289
- return typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer;
360
+ return typeof SharedArrayBuffer !== "undefined" && isInstance(value, SharedArrayBuffer);
290
361
  }
291
362
  /**
292
363
  * Determine whether a value implements the iterable protocol (`Symbol.iterator`).
@@ -355,6 +426,14 @@ function isObject(value) {
355
426
  * instance's runs through the class's own prototype. The whole body runs
356
427
  * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
357
428
  * `getPrototypeOf` trap cannot escape as a thrown error.
429
+ *
430
+ * @example
431
+ * ```ts
432
+ * isRecord({ a: 1 }) // true
433
+ * isRecord(Object.create(null)) // true
434
+ * isRecord([]) // false
435
+ * isRecord(new Date()) // false
436
+ * ```
358
437
  */
359
438
  function isRecord(value) {
360
439
  const outcome = attempt(() => {
@@ -373,7 +452,7 @@ function isRecord(value) {
373
452
  * ```
374
453
  */
375
454
  function isMap(value) {
376
- return value instanceof Map;
455
+ return isInstance(value, Map);
377
456
  }
378
457
  /** Determine whether a value is a `Set`.
379
458
  *
@@ -384,7 +463,7 @@ function isMap(value) {
384
463
  * ```
385
464
  */
386
465
  function isSet(value) {
387
- return value instanceof Set;
466
+ return isInstance(value, Set);
388
467
  }
389
468
  /** Determine whether a value is a `WeakMap`.
390
469
  *
@@ -395,7 +474,7 @@ function isSet(value) {
395
474
  * ```
396
475
  */
397
476
  function isWeakMap(value) {
398
- return value instanceof WeakMap;
477
+ return isInstance(value, WeakMap);
399
478
  }
400
479
  /** Determine whether a value is a `WeakSet`.
401
480
  *
@@ -406,7 +485,7 @@ function isWeakMap(value) {
406
485
  * ```
407
486
  */
408
487
  function isWeakSet(value) {
409
- return value instanceof WeakSet;
488
+ return isInstance(value, WeakSet);
410
489
  }
411
490
  /** Determine whether a value is an array.
412
491
  *
@@ -428,7 +507,7 @@ function isArray(value) {
428
507
  * ```
429
508
  */
430
509
  function isDataView(value) {
431
- return value instanceof DataView;
510
+ return isInstance(value, DataView);
432
511
  }
433
512
  /** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).
434
513
  *
@@ -450,7 +529,7 @@ function isArrayBufferView(value) {
450
529
  * ```
451
530
  */
452
531
  function isInt8Array(value) {
453
- return value instanceof Int8Array;
532
+ return isInstance(value, Int8Array);
454
533
  }
455
534
  /** Determine whether a value is a `Uint8Array`.
456
535
  *
@@ -461,7 +540,7 @@ function isInt8Array(value) {
461
540
  * ```
462
541
  */
463
542
  function isUint8Array(value) {
464
- return value instanceof Uint8Array;
543
+ return isInstance(value, Uint8Array);
465
544
  }
466
545
  /** Determine whether a value is a `Uint8ClampedArray`.
467
546
  *
@@ -472,7 +551,7 @@ function isUint8Array(value) {
472
551
  * ```
473
552
  */
474
553
  function isUint8ClampedArray(value) {
475
- return value instanceof Uint8ClampedArray;
554
+ return isInstance(value, Uint8ClampedArray);
476
555
  }
477
556
  /** Determine whether a value is an `Int16Array`.
478
557
  *
@@ -483,7 +562,7 @@ function isUint8ClampedArray(value) {
483
562
  * ```
484
563
  */
485
564
  function isInt16Array(value) {
486
- return value instanceof Int16Array;
565
+ return isInstance(value, Int16Array);
487
566
  }
488
567
  /** Determine whether a value is a `Uint16Array`.
489
568
  *
@@ -494,7 +573,7 @@ function isInt16Array(value) {
494
573
  * ```
495
574
  */
496
575
  function isUint16Array(value) {
497
- return value instanceof Uint16Array;
576
+ return isInstance(value, Uint16Array);
498
577
  }
499
578
  /** Determine whether a value is an `Int32Array`.
500
579
  *
@@ -505,7 +584,7 @@ function isUint16Array(value) {
505
584
  * ```
506
585
  */
507
586
  function isInt32Array(value) {
508
- return value instanceof Int32Array;
587
+ return isInstance(value, Int32Array);
509
588
  }
510
589
  /** Determine whether a value is a `Uint32Array`.
511
590
  *
@@ -516,7 +595,7 @@ function isInt32Array(value) {
516
595
  * ```
517
596
  */
518
597
  function isUint32Array(value) {
519
- return value instanceof Uint32Array;
598
+ return isInstance(value, Uint32Array);
520
599
  }
521
600
  /** Determine whether a value is a `Float32Array`.
522
601
  *
@@ -527,7 +606,7 @@ function isUint32Array(value) {
527
606
  * ```
528
607
  */
529
608
  function isFloat32Array(value) {
530
- return value instanceof Float32Array;
609
+ return isInstance(value, Float32Array);
531
610
  }
532
611
  /** Determine whether a value is a `Float64Array`.
533
612
  *
@@ -538,7 +617,7 @@ function isFloat32Array(value) {
538
617
  * ```
539
618
  */
540
619
  function isFloat64Array(value) {
541
- return value instanceof Float64Array;
620
+ return isInstance(value, Float64Array);
542
621
  }
543
622
  /**
544
623
  * Determine whether a value is a `BigInt64Array`.
@@ -554,7 +633,7 @@ function isFloat64Array(value) {
554
633
  * ```
555
634
  */
556
635
  function isBigInt64Array(value) {
557
- return typeof BigInt64Array !== "undefined" && value instanceof BigInt64Array;
636
+ return typeof BigInt64Array !== "undefined" && isInstance(value, BigInt64Array);
558
637
  }
559
638
  /**
560
639
  * Determine whether a value is a `BigUint64Array`.
@@ -570,7 +649,7 @@ function isBigInt64Array(value) {
570
649
  * ```
571
650
  */
572
651
  function isBigUint64Array(value) {
573
- return typeof BigUint64Array !== "undefined" && value instanceof BigUint64Array;
652
+ return typeof BigUint64Array !== "undefined" && isInstance(value, BigUint64Array);
574
653
  }
575
654
  /** Determine whether a value is the empty string `''`.
576
655
  *
@@ -604,7 +683,8 @@ function isEmptyArray(value) {
604
683
  */
605
684
  function isEmptyObject(value) {
606
685
  if (!isRecord(value)) return false;
607
- return Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0;
686
+ const outcome = attempt(() => Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0);
687
+ return outcome.success && outcome.value;
608
688
  }
609
689
  /** Determine whether a value is an empty `Map`.
610
690
  *
@@ -615,7 +695,7 @@ function isEmptyObject(value) {
615
695
  * ```
616
696
  */
617
697
  function isEmptyMap(value) {
618
- return value instanceof Map && value.size === 0;
698
+ return isMap(value) && value.size === 0;
619
699
  }
620
700
  /** Determine whether a value is an empty `Set`.
621
701
  *
@@ -626,7 +706,7 @@ function isEmptyMap(value) {
626
706
  * ```
627
707
  */
628
708
  function isEmptySet(value) {
629
- return value instanceof Set && value.size === 0;
709
+ return isSet(value) && value.size === 0;
630
710
  }
631
711
  /** Determine whether a value is a non-empty string (at least one character).
632
712
  *
@@ -660,7 +740,8 @@ function isNonEmptyArray(value) {
660
740
  */
661
741
  function isNonEmptyObject(value) {
662
742
  if (!isRecord(value)) return false;
663
- return Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0;
743
+ const outcome = attempt(() => Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0);
744
+ return outcome.success && outcome.value;
664
745
  }
665
746
  /** Determine whether a value is a non-empty `Map` (at least one entry).
666
747
  *
@@ -671,7 +752,7 @@ function isNonEmptyObject(value) {
671
752
  * ```
672
753
  */
673
754
  function isNonEmptyMap(value) {
674
- return value instanceof Map && value.size > 0;
755
+ return isMap(value) && value.size > 0;
675
756
  }
676
757
  /** Determine whether a value is a non-empty `Set` (at least one element).
677
758
  *
@@ -682,7 +763,7 @@ function isNonEmptyMap(value) {
682
763
  * ```
683
764
  */
684
765
  function isNonEmptySet(value) {
685
- return value instanceof Set && value.size > 0;
766
+ return isSet(value) && value.size > 0;
686
767
  }
687
768
  /** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).
688
769
  *
@@ -1018,6 +1099,79 @@ function enumerableSymbolCount(value) {
1018
1099
  function schemaToParameters(schema) {
1019
1100
  return isRecord(schema) ? schema : void 0;
1020
1101
  }
1102
+ /**
1103
+ * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s
1104
+ * `received` field.
1105
+ *
1106
+ * @remarks
1107
+ * A primitive renders as its literal: a string is `JSON.stringify`-escaped and
1108
+ * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when
1109
+ * clipped); a number / boolean / bigint / symbol renders via `String`; `null`
1110
+ * and `undefined` render as their own name. Everything else — a plain object,
1111
+ * an array, a function, a class instance, a `Map` — is NEVER traversed or
1112
+ * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),
1113
+ * so a hostile or enormous structure can never blow up the preview.
1114
+ *
1115
+ * @param value - The value to preview
1116
+ * @returns A short descriptive string, always safe to embed in a diagnostic
1117
+ *
1118
+ * @example
1119
+ * ```ts
1120
+ * preview('hi') // '"hi"'
1121
+ * preview(42) // '42'
1122
+ * preview(null) // 'null'
1123
+ * preview({ a: 1 }) // 'object'
1124
+ * preview([1, 2, 3]) // 'object'
1125
+ * ```
1126
+ */
1127
+ function preview(value) {
1128
+ if (value === null) return "null";
1129
+ if (value === void 0) return "undefined";
1130
+ if (isString(value)) {
1131
+ const text = JSON.stringify(value);
1132
+ return text.length > 64 ? `${text.slice(0, 64)}…` : text;
1133
+ }
1134
+ if (isNumber(value) || isBoolean(value)) return String(value);
1135
+ if (isBigInt(value)) return `${value}n`;
1136
+ if (isSymbol(value)) return value.toString();
1137
+ return typeof value;
1138
+ }
1139
+ /**
1140
+ * Project a {@link ContractShape} to the {@link FaultKind} it describes.
1141
+ *
1142
+ * @remarks
1143
+ * A structural mapping used by {@link compileReporter} to fill a `Fault`'s
1144
+ * `expected` field: most shapes map to their own `type` (`numberShape` maps to
1145
+ * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
1146
+ * `nullableShape` project through to their inner shape's kind, and `rawShape`
1147
+ * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
1148
+ *
1149
+ * @param shape - The shape to project
1150
+ * @returns The shape's {@link FaultKind}
1151
+ *
1152
+ * @example
1153
+ * ```ts
1154
+ * shapeToKind(stringShape()) // 'string'
1155
+ * shapeToKind(integerShape()) // 'integer'
1156
+ * shapeToKind(optionalShape(nullShape())) // 'null'
1157
+ * ```
1158
+ */
1159
+ function shapeToKind(shape) {
1160
+ switch (shape.type) {
1161
+ case "string": return "string";
1162
+ case "number": return shape.integer === true ? "integer" : "number";
1163
+ case "boolean": return "boolean";
1164
+ case "null": return "null";
1165
+ case "literal": return "literal";
1166
+ case "array": return "array";
1167
+ case "object": return "object";
1168
+ case "union": return "union";
1169
+ case "json": return "json";
1170
+ case "optional": return shapeToKind(shape.inner);
1171
+ case "nullable": return shapeToKind(shape.inner);
1172
+ case "raw": return "json";
1173
+ }
1174
+ }
1021
1175
  //#endregion
1022
1176
  //#region src/core/combinators.ts
1023
1177
  function arrayOf(elementGuard) {
@@ -1070,7 +1224,7 @@ function literalOf(...literals) {
1070
1224
  * ```
1071
1225
  */
1072
1226
  function instanceOf(ctor) {
1073
- return (value) => isConstructor(ctor) && isObject(value) && value instanceof ctor;
1227
+ return (value) => isConstructor(ctor) && isObject(value) && isInstance(value, ctor);
1074
1228
  }
1075
1229
  /**
1076
1230
  * Build a guard from a native `enum` or any object whose values are strings or
@@ -1985,7 +2139,11 @@ function compileGuard(shape) {
1985
2139
  return outcome.success && outcome.value;
1986
2140
  };
1987
2141
  }
1988
- case "union": return unionOf(...shape.variants.map((variant) => compileGuard(variant)));
2142
+ case "union": {
2143
+ const guards = shape.variants.map((variant) => compileGuard(variant));
2144
+ if (shape.mode === "oneOf") return (value) => guards.filter((guard) => guard(value)).length === 1;
2145
+ return unionOf(...guards);
2146
+ }
1989
2147
  case "optional": return orOf(isUndefined, compileGuard(shape.inner));
1990
2148
  case "nullable": return nullableOf(compileGuard(shape.inner));
1991
2149
  case "raw": return (_value) => true;
@@ -2092,6 +2250,11 @@ function compileParser(shape) {
2092
2250
  parse: compileParser(variant),
2093
2251
  guard: compileGuard(variant)
2094
2252
  }));
2253
+ if (shape.mode === "oneOf") return (value) => {
2254
+ const matches = variants.filter((variant) => variant.guard(value));
2255
+ const [only] = matches;
2256
+ return matches.length === 1 && only !== void 0 ? only.parse(value) : void 0;
2257
+ };
2095
2258
  return (value) => {
2096
2259
  for (const variant of variants) if (variant.guard(value)) return value;
2097
2260
  for (const variant of variants) {
@@ -2186,6 +2349,260 @@ function compileGenerator(shape, random = seededRandom(Date.now())) {
2186
2349
  case "raw": throw new Error("compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way");
2187
2350
  }
2188
2351
  }
2352
+ /**
2353
+ * Compile a {@link ContractShape} into a structured fault report for a value —
2354
+ * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.
2355
+ *
2356
+ * @remarks
2357
+ * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards
2358
+ * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /
2359
+ * `isJSONValue` / …), so the soundness invariant
2360
+ * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`
2361
+ * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a
2362
+ * coercible value like `'42'` against a `numberShape` reports no fault, the
2363
+ * same leniency `parse` grants, even though the strict guard would reject it).
2364
+ *
2365
+ * Faults are collected in stable pre-order (declared key/index order); every
2366
+ * call — object, array, and union alike, including a union's `oneOf` "no
2367
+ * match" / "no consensus" summary fault prepended to its closest variant's
2368
+ * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the
2369
+ * bound holds at every level of nesting, not just the outermost container, on
2370
+ * adversarial input (a huge array, a wide record, a wide union of wide
2371
+ * records). A closed object's extra keys never
2372
+ * fault — `parse` silently drops them, so `explain` mirrors that leniency; an
2373
+ * open object with a constraining `additionalProperties` shape recurses extras
2374
+ * against it instead. A hostile getter or throwing `Proxy` trap is contained
2375
+ * via {@link attempt} and surfaces as a single top-level type fault, never a
2376
+ * throw (AGENTS §14).
2377
+ *
2378
+ * @param shape - The shape to report against
2379
+ * @param value - The value to check
2380
+ * @param path - The path prefix for faults produced at this call (defaults to the root)
2381
+ * @returns The faults found, empty when the value parses successfully
2382
+ *
2383
+ * @example
2384
+ * ```ts
2385
+ * const user = objectShape({ name: stringShape({ min: 1 }) })
2386
+ * compileReporter(user, { name: '' })
2387
+ * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '""' }]
2388
+ * compileReporter(user, { name: 'Ada' }) // []
2389
+ * ```
2390
+ */
2391
+ function compileReporter(shape, value, path = []) {
2392
+ switch (shape.type) {
2393
+ case "string": {
2394
+ const parsed = parseString(value);
2395
+ if (parsed === void 0) return [{
2396
+ reason: "type",
2397
+ path,
2398
+ expected: "string",
2399
+ received: preview(value)
2400
+ }];
2401
+ const faults = [];
2402
+ if (shape.min !== void 0 && parsed.length < shape.min) faults.push({
2403
+ reason: "constraint",
2404
+ path,
2405
+ expected: "string",
2406
+ constraint: "min",
2407
+ limit: shape.min,
2408
+ received: preview(parsed)
2409
+ });
2410
+ if (shape.max !== void 0 && parsed.length > shape.max) faults.push({
2411
+ reason: "constraint",
2412
+ path,
2413
+ expected: "string",
2414
+ constraint: "max",
2415
+ limit: shape.max,
2416
+ received: preview(parsed)
2417
+ });
2418
+ if (shape.pattern !== void 0 && !shape.pattern.test(parsed)) faults.push({
2419
+ reason: "constraint",
2420
+ path,
2421
+ expected: "string",
2422
+ constraint: "pattern",
2423
+ limit: shape.pattern.source,
2424
+ received: preview(parsed)
2425
+ });
2426
+ return faults;
2427
+ }
2428
+ case "number": {
2429
+ const kind = shape.integer === true ? "integer" : "number";
2430
+ const parsed = parseNumber(value);
2431
+ if (parsed === void 0) return [{
2432
+ reason: "type",
2433
+ path,
2434
+ expected: kind,
2435
+ received: preview(value)
2436
+ }];
2437
+ const faults = [];
2438
+ if (shape.integer === true && !Number.isInteger(parsed)) faults.push({
2439
+ reason: "constraint",
2440
+ path,
2441
+ expected: kind,
2442
+ constraint: "integer",
2443
+ received: preview(parsed)
2444
+ });
2445
+ if (shape.min !== void 0 && parsed < shape.min) faults.push({
2446
+ reason: "constraint",
2447
+ path,
2448
+ expected: kind,
2449
+ constraint: "min",
2450
+ limit: shape.min,
2451
+ received: preview(parsed)
2452
+ });
2453
+ if (shape.max !== void 0 && parsed > shape.max) faults.push({
2454
+ reason: "constraint",
2455
+ path,
2456
+ expected: kind,
2457
+ constraint: "max",
2458
+ limit: shape.max,
2459
+ received: preview(parsed)
2460
+ });
2461
+ return faults;
2462
+ }
2463
+ case "boolean": return parseBoolean(value) === void 0 ? [{
2464
+ reason: "type",
2465
+ path,
2466
+ expected: "boolean",
2467
+ received: preview(value)
2468
+ }] : [];
2469
+ case "null": return value === null ? [] : [{
2470
+ reason: "type",
2471
+ path,
2472
+ expected: "null",
2473
+ received: preview(value)
2474
+ }];
2475
+ case "json": return isJSONValue(value) ? [] : [{
2476
+ reason: "type",
2477
+ path,
2478
+ expected: "json",
2479
+ received: preview(value)
2480
+ }];
2481
+ case "literal": {
2482
+ const allowed = new Set(shape.values);
2483
+ return allowed.has(value) || isString(value) && allowed.has(value.trim()) ? [] : [{
2484
+ reason: "type",
2485
+ path,
2486
+ expected: "literal",
2487
+ received: preview(value)
2488
+ }];
2489
+ }
2490
+ case "array": {
2491
+ if (!isArray(value)) return [{
2492
+ reason: "type",
2493
+ path,
2494
+ expected: "array",
2495
+ received: preview(value)
2496
+ }];
2497
+ const faults = [];
2498
+ if (!attempt(() => {
2499
+ for (let index = 0; index < value.length; index += 1) {
2500
+ if (faults.length >= 64) return;
2501
+ faults.push(...compileReporter(shape.items, value[index], [...path, String(index)]));
2502
+ }
2503
+ }).success) return [{
2504
+ reason: "type",
2505
+ path,
2506
+ expected: "array",
2507
+ received: preview(value)
2508
+ }];
2509
+ if (shape.min !== void 0 && value.length < shape.min) faults.push({
2510
+ reason: "constraint",
2511
+ path,
2512
+ expected: "array",
2513
+ constraint: "min",
2514
+ limit: shape.min,
2515
+ received: String(value.length)
2516
+ });
2517
+ if (shape.max !== void 0 && value.length > shape.max) faults.push({
2518
+ reason: "constraint",
2519
+ path,
2520
+ expected: "array",
2521
+ constraint: "max",
2522
+ limit: shape.max,
2523
+ received: String(value.length)
2524
+ });
2525
+ return faults.length > 64 ? faults.slice(0, 64) : faults;
2526
+ }
2527
+ case "object": {
2528
+ if (!isRecord(value)) return [{
2529
+ reason: "type",
2530
+ path,
2531
+ expected: "object",
2532
+ received: preview(value)
2533
+ }];
2534
+ const record = value;
2535
+ const faults = [];
2536
+ const known = /* @__PURE__ */ new Set();
2537
+ if (!attempt(() => {
2538
+ for (const key of Object.keys(shape.properties)) {
2539
+ if (faults.length >= 64) return;
2540
+ const child = shape.properties[key];
2541
+ if (child === void 0) continue;
2542
+ known.add(key);
2543
+ const optional = child.type === "optional";
2544
+ const inner = optional ? child.inner : child;
2545
+ const raw = record[key];
2546
+ if (raw === void 0) {
2547
+ if (!optional) faults.push({
2548
+ reason: "missing",
2549
+ path: [...path, key],
2550
+ expected: shapeToKind(inner)
2551
+ });
2552
+ continue;
2553
+ }
2554
+ faults.push(...compileReporter(inner, raw, [...path, key]));
2555
+ }
2556
+ const extra = shape.additionalProperties;
2557
+ if (extra !== void 0 && extra !== true && extra !== false) for (const key of Object.keys(record)) {
2558
+ if (faults.length >= 64) return;
2559
+ if (known.has(key)) continue;
2560
+ faults.push(...compileReporter(extra, record[key], [...path, key]));
2561
+ }
2562
+ }).success) return [{
2563
+ reason: "type",
2564
+ path,
2565
+ expected: "object",
2566
+ received: preview(value)
2567
+ }];
2568
+ return faults.length > 64 ? faults.slice(0, 64) : faults;
2569
+ }
2570
+ case "union": {
2571
+ const perVariant = shape.variants.map((variant) => compileReporter(variant, value, path));
2572
+ let bestIndex = 0;
2573
+ for (let index = 1; index < perVariant.length; index += 1) {
2574
+ const current = perVariant[index];
2575
+ const best = perVariant[bestIndex];
2576
+ if (current !== void 0 && best !== void 0 && current.length < best.length) bestIndex = index;
2577
+ }
2578
+ const closest = perVariant[bestIndex] ?? [];
2579
+ if (shape.mode === "oneOf") {
2580
+ let matched = 0;
2581
+ for (const variant of shape.variants) if (compileGuard(variant)(value)) matched += 1;
2582
+ if (matched === 1) return [];
2583
+ if (matched === 0) return [{
2584
+ reason: "oneOf",
2585
+ path,
2586
+ matched: 0
2587
+ }, ...closest].slice(0, 64);
2588
+ return [{
2589
+ reason: "oneOf",
2590
+ path,
2591
+ matched
2592
+ }];
2593
+ }
2594
+ if (perVariant.some((variantFaults) => variantFaults.length === 0)) return [];
2595
+ return [{
2596
+ reason: "variant",
2597
+ path,
2598
+ variants: shape.variants.length
2599
+ }, ...closest].slice(0, 64);
2600
+ }
2601
+ case "optional": return value === void 0 ? [] : compileReporter(shape.inner, value, path);
2602
+ case "nullable": return value === null ? [] : compileReporter(shape.inner, value, path);
2603
+ case "raw": return [];
2604
+ }
2605
+ }
2189
2606
  function createContract(shape) {
2190
2607
  validateShape(shape);
2191
2608
  const schema = compileSchema(shape);
@@ -2197,6 +2614,9 @@ function createContract(shape) {
2197
2614
  parse(value) {
2198
2615
  return parser(value);
2199
2616
  },
2617
+ explain(value) {
2618
+ return compileReporter(shape, value);
2619
+ },
2200
2620
  generate(random) {
2201
2621
  return compileGenerator(shape, random);
2202
2622
  }
@@ -2415,16 +2835,32 @@ function unionShape(...variants) {
2415
2835
  * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
2416
2836
  *
2417
2837
  * @remarks
2418
- * Runtime behavior is identical to {@link unionShape} — only the emitted schema
2419
- * keyword differs (`oneOf` vs `anyOf`).
2838
+ * Unlike {@link unionShape} (`anyOf` — at least one variant matches),
2839
+ * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:
2840
+ *
2841
+ * - **Guard**: accepts the value only when exactly one variant's guard
2842
+ * accepts it. A value matching two-or-more variants — which would violate
2843
+ * the emitted `oneOf` schema — is rejected, even though it would pass
2844
+ * {@link unionShape}'s guard.
2845
+ * - **Parser**: judged on the RAW input's guard matches only, with NO
2846
+ * coercion fallback for an ambiguous input. When exactly one variant's
2847
+ * guard accepts the raw value, that variant's parser runs. Zero matches or
2848
+ * two-or-more matches both parse to `undefined` — a value ambiguous
2849
+ * between variants has no well-defined coercion target.
2850
+ *
2851
+ * Prefer {@link unionShape} when a value may legitimately satisfy more than
2852
+ * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer
2853
+ * `oneOfShape` when overlap between variants indicates malformed input that
2854
+ * must be rejected.
2420
2855
  *
2421
2856
  * @param variants - The candidate shapes
2422
2857
  * @returns A union shape with `mode: 'oneOf'`
2423
2858
  *
2424
2859
  * @example
2425
2860
  * ```ts
2426
- * const id = oneOfShape(stringShape(), integerShape())
2427
- * // Infer<typeof id> = string | number
2861
+ * const id = oneOfShape(numberShape(), integerShape())
2862
+ * // 3 fails — matches both numberShape and integerShape
2863
+ * // 3.5 passes — matches numberShape only
2428
2864
  * ```
2429
2865
  */
2430
2866
  function oneOfShape(...variants) {
@@ -2512,6 +2948,6 @@ function rawShape(schema) {
2512
2948
  };
2513
2949
  }
2514
2950
  //#endregion
2515
- export { JSON_SCHEMA_TYPES, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, compileGenerator, compileGuard, compileParser, compileSchema, complementOf, createContract, enumOf, enumerableSymbolCount, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isConstructor, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterableOf, jsonShape, keyOf, lazyOf, literalOf, literalShape, mapOf, matchOf, notOf, nullShape, nullableOf, nullableShape, numberShape, objectShape, omitOf, oneOfShape, optionalOf, optionalShape, orOf, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pickOf, rawShape, recordOf, recordShape, resolveField, schemaToParameters, seededRandom, setOf, stringOf, stringShape, transformOf, tupleOf, unionOf, unionShape, validateShape, whereOf };
2951
+ export { FAULT_LIMIT, JSON_SCHEMA_TYPES, PREVIEW_LIMIT, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, createContract, enumOf, enumerableSymbolCount, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isConstructor, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInstance, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterableOf, jsonShape, keyOf, lazyOf, literalOf, literalShape, mapOf, matchOf, notOf, nullShape, nullableOf, nullableShape, numberShape, objectShape, omitOf, oneOfShape, optionalOf, optionalShape, orOf, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pickOf, preview, rawShape, recordOf, recordShape, resolveField, schemaToParameters, seededRandom, setOf, shapeToKind, stringOf, stringShape, transformOf, tupleOf, unionOf, unionShape, validateShape, whereOf };
2516
2952
 
2517
2953
  //# sourceMappingURL=index.js.map