@orkestrel/contract 0.0.7 → 0.0.9

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.
@@ -47,6 +47,50 @@ var FAULT_LIMIT = 64;
47
47
  */
48
48
  var PREVIEW_LIMIT = 64;
49
49
  /**
50
+ * The maximum number of active {@link lazyOf} invocations for one lazy guard,
51
+ * frozen.
52
+ *
53
+ * @remarks
54
+ * Bounds explicitly recursive guards before the JavaScript call stack becomes
55
+ * the limiting mechanism. An invocation beyond this depth returns `false`, and
56
+ * the counter unwinds after every contained guard call.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * GUARD_DEPTH_LIMIT // 512
61
+ * ```
62
+ */
63
+ var GUARD_DEPTH_LIMIT = 512;
64
+ /**
65
+ * The maximum supported nesting depth of a compiled contract shape, frozen.
66
+ *
67
+ * @remarks
68
+ * {@link validateShape} rejects the next level with a depth-coded
69
+ * {@link ContractError} before recursive artifact compilation begins, so a
70
+ * finite but pathologically deep developer-authored shape fails predictably
71
+ * instead of reaching the JavaScript call-stack limit.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * COMPILE_DEPTH_LIMIT // 512
76
+ * ```
77
+ */
78
+ var COMPILE_DEPTH_LIMIT = 512;
79
+ /**
80
+ * The maximum number of candidate-generation attempts for a constrained
81
+ * generated value, frozen.
82
+ *
83
+ * @remarks
84
+ * Provides one deterministic work bound for generators that must retry a
85
+ * candidate against a contract constraint.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * GENERATION_ATTEMPT_LIMIT // 32
90
+ * ```
91
+ */
92
+ var GENERATION_ATTEMPT_LIMIT = 32;
93
+ /**
50
94
  * The default maximum object/array nesting depth {@link valueToSchema} walks,
51
95
  * frozen.
52
96
  *
@@ -107,6 +151,55 @@ var FORMAT_PATTERNS = Object.freeze({
107
151
  uri: /^[a-z][a-z0-9+.-]*:\/\//i
108
152
  });
109
153
  //#endregion
154
+ //#region src/core/errors.ts
155
+ /**
156
+ * Error carrying a machine-readable contract category and optional context.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * const error = new ContractError('Minimum exceeds maximum', {
161
+ * code: 'range',
162
+ * context: { path: ['properties', 'age'] },
163
+ * })
164
+ * ```
165
+ */
166
+ var ContractError = class extends Error {
167
+ name = "ContractError";
168
+ code;
169
+ context;
170
+ /**
171
+ * Create a contract error.
172
+ *
173
+ * @param message - Human-readable error description
174
+ * @param options - Machine-readable category, optional context, and optional cause
175
+ */
176
+ constructor(message, options) {
177
+ const cause = options.cause;
178
+ super(message, cause === void 0 ? void 0 : { cause });
179
+ this.code = options.code;
180
+ this.context = options.context;
181
+ }
182
+ };
183
+ /**
184
+ * Determine whether an unknown value is a {@link ContractError}.
185
+ *
186
+ * @param value - The value to inspect
187
+ * @returns `true` only when the value is a `ContractError`
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * isContractError(new ContractError('Invalid shape', { code: 'placement' })) // true
192
+ * isContractError(new Error('Invalid shape')) // false
193
+ * ```
194
+ */
195
+ function isContractError(value) {
196
+ try {
197
+ return value instanceof ContractError;
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
202
+ //#endregion
110
203
  //#region src/core/validators.ts
111
204
  /** Determine whether a value is `null`.
112
205
  *
@@ -304,7 +397,7 @@ function isNullableBoolean(value) {
304
397
  * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
305
398
  * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
306
399
  * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
307
- * wraps the check in {@link attempt} (see ./helpers.js) so any such throw
400
+ * wraps the check in {@link holds} (see ./helpers.js) so any such throw
308
401
  * yields `false` instead of escaping.
309
402
  *
310
403
  * @param value - The value to test
@@ -320,8 +413,7 @@ function isNullableBoolean(value) {
320
413
  */
321
414
  function isInstance(value, ctor) {
322
415
  const target = ctor;
323
- const outcome = attempt(() => isFunction(target) && value instanceof target);
324
- return outcome.success && outcome.value;
416
+ return holds(() => isFunction(target) && value instanceof target);
325
417
  }
326
418
  /** Determine whether a value is a `Date`.
327
419
  *
@@ -383,14 +475,13 @@ function isPromise(value) {
383
475
  * ```
384
476
  */
385
477
  function isPromiseLike(value) {
386
- if (!isObject(value)) return false;
387
- const outcome = attempt(() => {
478
+ return holds(() => {
479
+ if (!isObject(value)) return false;
388
480
  const thenValue = Reflect.get(value, "then");
389
481
  const catchValue = Reflect.get(value, "catch");
390
482
  const finallyValue = Reflect.get(value, "finally");
391
483
  return isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue);
392
484
  });
393
- return outcome.success && outcome.value;
394
485
  }
395
486
  /** Determine whether a value is an `ArrayBuffer`.
396
487
  *
@@ -434,10 +525,10 @@ function isSharedArrayBuffer(value) {
434
525
  * ```
435
526
  */
436
527
  function isIterable(value) {
437
- if (isString(value)) return true;
438
- if (!isObject(value)) return false;
439
- const outcome = attempt(() => isFunction(Reflect.get(value, Symbol.iterator)));
440
- return outcome.success && outcome.value;
528
+ return holds(() => {
529
+ if (isString(value)) return true;
530
+ return isObject(value) && isFunction(Reflect.get(value, Symbol.iterator));
531
+ });
441
532
  }
442
533
  /** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).
443
534
  *
@@ -448,9 +539,7 @@ function isIterable(value) {
448
539
  * ```
449
540
  */
450
541
  function isAsyncIterable(value) {
451
- if (!isObject(value)) return false;
452
- const outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)));
453
- return outcome.success && outcome.value;
542
+ return holds(() => isObject(value) && isFunction(Reflect.get(value, Symbol.asyncIterator)));
454
543
  }
455
544
  /**
456
545
  * Determine whether a value is a non-null object.
@@ -484,7 +573,7 @@ function isObject(value) {
484
573
  * above `null`. Arrays and class instances are still rejected: an array's
485
574
  * prototype chain runs through `Array.prototype` before `null`, and a class
486
575
  * instance's runs through the class's own prototype. The whole body runs
487
- * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
576
+ * inside `holds` (AGENTS §14) so a revoked `Proxy` or a hostile
488
577
  * `getPrototypeOf` trap cannot escape as a thrown error.
489
578
  *
490
579
  * @example
@@ -496,12 +585,11 @@ function isObject(value) {
496
585
  * ```
497
586
  */
498
587
  function isRecord(value) {
499
- const outcome = attempt(() => {
588
+ return holds(() => {
500
589
  if (!isObject(value) || isArray(value)) return false;
501
590
  const prototype = Object.getPrototypeOf(value);
502
591
  return prototype === null || Object.getPrototypeOf(prototype) === null;
503
592
  });
504
- return outcome.success && outcome.value;
505
593
  }
506
594
  /** Determine whether a value is a `Map`.
507
595
  *
@@ -556,7 +644,7 @@ function isWeakSet(value) {
556
644
  * ```
557
645
  */
558
646
  function isArray(value) {
559
- return Array.isArray(value);
647
+ return holds(() => Array.isArray(value));
560
648
  }
561
649
  /** Determine whether a value is a `DataView`.
562
650
  *
@@ -578,7 +666,7 @@ function isDataView(value) {
578
666
  * ```
579
667
  */
580
668
  function isArrayBufferView(value) {
581
- return ArrayBuffer.isView(value);
669
+ return holds(() => ArrayBuffer.isView(value));
582
670
  }
583
671
  /** Determine whether a value is an `Int8Array`.
584
672
  *
@@ -731,7 +819,7 @@ function isEmptyString(value) {
731
819
  * ```
732
820
  */
733
821
  function isEmptyArray(value) {
734
- return isArray(value) && value.length === 0;
822
+ return holds(() => isArray(value) && value.length === 0);
735
823
  }
736
824
  /** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).
737
825
  *
@@ -742,9 +830,7 @@ function isEmptyArray(value) {
742
830
  * ```
743
831
  */
744
832
  function isEmptyObject(value) {
745
- if (!isRecord(value)) return false;
746
- const outcome = attempt(() => Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0);
747
- return outcome.success && outcome.value;
833
+ return holds(() => isRecord(value) && Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0);
748
834
  }
749
835
  /** Determine whether a value is an empty `Map`.
750
836
  *
@@ -755,7 +841,7 @@ function isEmptyObject(value) {
755
841
  * ```
756
842
  */
757
843
  function isEmptyMap(value) {
758
- return isMap(value) && value.size === 0;
844
+ return holds(() => isMap(value) && value.size === 0);
759
845
  }
760
846
  /** Determine whether a value is an empty `Set`.
761
847
  *
@@ -766,7 +852,7 @@ function isEmptyMap(value) {
766
852
  * ```
767
853
  */
768
854
  function isEmptySet(value) {
769
- return isSet(value) && value.size === 0;
855
+ return holds(() => isSet(value) && value.size === 0);
770
856
  }
771
857
  /** Determine whether a value is a non-empty string (at least one character).
772
858
  *
@@ -788,7 +874,7 @@ function isNonEmptyString(value) {
788
874
  * ```
789
875
  */
790
876
  function isNonEmptyArray(value) {
791
- return isArray(value) && value.length > 0;
877
+ return holds(() => isArray(value) && value.length > 0);
792
878
  }
793
879
  /** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).
794
880
  *
@@ -799,9 +885,7 @@ function isNonEmptyArray(value) {
799
885
  * ```
800
886
  */
801
887
  function isNonEmptyObject(value) {
802
- if (!isRecord(value)) return false;
803
- const outcome = attempt(() => Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0);
804
- return outcome.success && outcome.value;
888
+ return holds(() => isRecord(value) && (Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0));
805
889
  }
806
890
  /** Determine whether a value is a non-empty `Map` (at least one entry).
807
891
  *
@@ -812,7 +896,7 @@ function isNonEmptyObject(value) {
812
896
  * ```
813
897
  */
814
898
  function isNonEmptyMap(value) {
815
- return isMap(value) && value.size > 0;
899
+ return holds(() => isMap(value) && value.size > 0);
816
900
  }
817
901
  /** Determine whether a value is a non-empty `Set` (at least one element).
818
902
  *
@@ -823,7 +907,7 @@ function isNonEmptyMap(value) {
823
907
  * ```
824
908
  */
825
909
  function isNonEmptySet(value) {
826
- return isSet(value) && value.size > 0;
910
+ return holds(() => isSet(value) && value.size > 0);
827
911
  }
828
912
  /** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).
829
913
  *
@@ -834,7 +918,7 @@ function isNonEmptySet(value) {
834
918
  * ```
835
919
  */
836
920
  function isZeroArg(value) {
837
- return isFunction(value) && value.length === 0;
921
+ return holds(() => isFunction(value) && value.length === 0);
838
922
  }
839
923
  /**
840
924
  * Determine whether a value is a native `async function`.
@@ -851,7 +935,7 @@ function isZeroArg(value) {
851
935
  * ```
852
936
  */
853
937
  function isAsyncFunction(value) {
854
- return isFunction(value) && value.constructor?.name === "AsyncFunction";
938
+ return holds(() => isFunction(value) && value.constructor?.name === "AsyncFunction");
855
939
  }
856
940
  /** Determine whether a value is a generator function (`function*`).
857
941
  *
@@ -862,7 +946,7 @@ function isAsyncFunction(value) {
862
946
  * ```
863
947
  */
864
948
  function isGeneratorFunction(value) {
865
- return isFunction(value) && value.constructor?.name === "GeneratorFunction";
949
+ return holds(() => isFunction(value) && value.constructor?.name === "GeneratorFunction");
866
950
  }
867
951
  /** Determine whether a value is an async generator function (`async function*`).
868
952
  *
@@ -873,7 +957,7 @@ function isGeneratorFunction(value) {
873
957
  * ```
874
958
  */
875
959
  function isAsyncGeneratorFunction(value) {
876
- return isFunction(value) && value.constructor?.name === "AsyncGeneratorFunction";
960
+ return holds(() => isFunction(value) && value.constructor?.name === "AsyncGeneratorFunction");
877
961
  }
878
962
  /** Determine whether a value is a zero-argument async function.
879
963
  *
@@ -923,13 +1007,11 @@ function isZeroArgAsyncGenerator(value) {
923
1007
  * ```
924
1008
  */
925
1009
  function isConstructor(value) {
926
- if (!isFunction(value)) return false;
927
- try {
1010
+ return holds(() => {
1011
+ if (!isFunction(value)) return false;
928
1012
  Reflect.construct(String, [], value);
929
1013
  return true;
930
- } catch {
931
- return false;
932
- }
1014
+ });
933
1015
  }
934
1016
  /**
935
1017
  * Determine whether a value is a cycle-safe JSON value.
@@ -938,7 +1020,7 @@ function isConstructor(value) {
938
1020
  * Total guard: never throws, returns `false` for cycles, functions, `Date`
939
1021
  * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records
940
1022
  * are walked with an ancestor set so recursive input fails instead of hanging.
941
- * The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a
1023
+ * The whole walk runs inside `holds` (AGENTS §14): a hostile getter on a
942
1024
  * record property, or a revoked `Proxy` anywhere in the structure, is caught
943
1025
  * and yields `false` instead of escaping as a thrown error.
944
1026
  *
@@ -952,25 +1034,7 @@ function isConstructor(value) {
952
1034
  * ```
953
1035
  */
954
1036
  function isJSONValue(value) {
955
- const ancestors = /* @__PURE__ */ new WeakSet();
956
- const check = (entry) => {
957
- if (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true;
958
- if (Array.isArray(entry)) {
959
- if (ancestors.has(entry)) return false;
960
- ancestors.add(entry);
961
- const valid = entry.every(check);
962
- ancestors.delete(entry);
963
- return valid;
964
- }
965
- if (!isRecord(entry)) return false;
966
- if (ancestors.has(entry)) return false;
967
- ancestors.add(entry);
968
- const valid = Object.values(entry).every(check);
969
- ancestors.delete(entry);
970
- return valid;
971
- };
972
- const outcome = attempt(() => check(value));
973
- return outcome.success && outcome.value;
1037
+ return holds(() => matchesJSONValue(value, /* @__PURE__ */ new WeakSet()));
974
1038
  }
975
1039
  /**
976
1040
  * Determine whether a value is a primitive JSON value.
@@ -1007,13 +1071,14 @@ function isJSONPrimitive(value) {
1007
1071
  * a throw escape.
1008
1072
  *
1009
1073
  * @remarks
1010
- * The single sanctioned never-throw boundary for the guards (AGENTS §14). The
1074
+ * The sanctioned never-throw boundary for the guards (AGENTS §14). The
1011
1075
  * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
1012
1076
  * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
1013
1077
  * `boolean`. This converts a throwing callback into a `Failure` so the
1014
1078
  * surrounding guard can treat it as a non-match instead of propagating the
1015
1079
  * exception, written once and shared rather than copy-pasted as ad-hoc
1016
- * `try`/`catch`.
1080
+ * `try`/`catch`. The sole hand-written exception is {@link isContractError},
1081
+ * whose local boundary avoids an `errors` → `helpers` dependency inversion.
1017
1082
  *
1018
1083
  * @param callback - The callback to invoke with no arguments
1019
1084
  * @returns A `Success` carrying the return value, or a `Failure` carrying the
@@ -1032,21 +1097,92 @@ function attempt(callback) {
1032
1097
  value: callback()
1033
1098
  };
1034
1099
  } catch (reason) {
1035
- if (reason instanceof Error) return {
1036
- success: false,
1037
- error: reason
1038
- };
1039
- let message = "Unknown thrown value";
1040
1100
  try {
1041
- message = String(reason);
1042
- } catch {}
1043
- return {
1044
- success: false,
1045
- error: new Error(message)
1046
- };
1101
+ return {
1102
+ success: false,
1103
+ error: reason instanceof Error ? reason : new Error(String(reason))
1104
+ };
1105
+ } catch {
1106
+ return {
1107
+ success: false,
1108
+ error: /* @__PURE__ */ new Error("Unknown thrown value")
1109
+ };
1110
+ }
1047
1111
  }
1048
1112
  }
1049
1113
  /**
1114
+ * Invoke a predicate through the sanctioned never-throw boundary.
1115
+ *
1116
+ * @param callback - The predicate to invoke with no arguments
1117
+ * @returns `true` only when the callback returns the boolean value `true`
1118
+ *
1119
+ * @example
1120
+ * ```ts
1121
+ * holds(() => value instanceof Widget) // false when inspection throws
1122
+ * ```
1123
+ */
1124
+ function holds(callback) {
1125
+ const outcome = attempt(callback);
1126
+ return outcome.success && outcome.value === true;
1127
+ }
1128
+ /**
1129
+ * Snapshot an object's own enumerable string keys through a total boundary.
1130
+ *
1131
+ * @remarks
1132
+ * This is the package-wide runtime property view used by compiled object
1133
+ * guards, parsers, reporters, schema inference, and owned schema cloning. It
1134
+ * matches the object-key view serialized by `JSON.stringify`: inherited,
1135
+ * symbol, and non-enumerable properties are excluded. A hostile Proxy trap
1136
+ * returns `undefined` rather than escaping.
1137
+ *
1138
+ * @param value - The object whose keys to snapshot
1139
+ * @returns A frozen owned key list, or `undefined` when enumeration throws
1140
+ *
1141
+ * @example
1142
+ * ```ts
1143
+ * enumerableKeys({ visible: 1 }) // ['visible']
1144
+ * ```
1145
+ */
1146
+ function enumerableKeys(value) {
1147
+ const outcome = attempt(() => Object.keys(value));
1148
+ return outcome.success ? Object.freeze([...outcome.value]) : void 0;
1149
+ }
1150
+ /**
1151
+ * Draw and validate one generator random sample.
1152
+ *
1153
+ * @param random - The caller-supplied random source
1154
+ * @param shape - The shape category consuming the sample
1155
+ * @returns A finite sample in `[0, 1)`
1156
+ * @throws {ContractError} When the source throws or returns outside `[0, 1)`
1157
+ *
1158
+ * @example
1159
+ * ```ts
1160
+ * drawRandom(() => 0.5, 'number') // 0.5
1161
+ * ```
1162
+ */
1163
+ function drawRandom(random, shape) {
1164
+ const outcome = attempt(random);
1165
+ if (!outcome.success) throw new ContractError("drawRandom: the random source threw", {
1166
+ code: "random",
1167
+ context: {
1168
+ shape,
1169
+ limit: "[0, 1)",
1170
+ received: "threw"
1171
+ },
1172
+ cause: outcome.error
1173
+ });
1174
+ const sample = outcome.value;
1175
+ if (!isFiniteNumber(sample) || sample < 0 || sample >= 1) throw new ContractError("drawRandom: the random source must return a value in [0, 1)", {
1176
+ code: "random",
1177
+ context: {
1178
+ shape,
1179
+ limit: "[0, 1)",
1180
+ received: String(sample)
1181
+ }
1182
+ });
1183
+ return sample;
1184
+ }
1185
+ /**
1050
1186
  * Resolve a (possibly nested) field value from a record by a key or key path.
1051
1187
  *
1052
1188
  * @remarks
@@ -1081,6 +1217,46 @@ function resolveField(record, path) {
1081
1217
  return current;
1082
1218
  }
1083
1219
  /**
1220
+ * Match an unknown value against the recursive JSON value structure.
1221
+ *
1222
+ * @remarks
1223
+ * The caller-owned ancestor set tracks only the active traversal path, so
1224
+ * cycles fail while shared references across sibling branches remain valid.
1225
+ * The set belongs to one traversal from one entry point; passing a shared or
1226
+ * pre-populated set is unsupported. Arrays and plain records recurse through
1227
+ * this helper; class instances and non-finite numbers are rejected.
1228
+ *
1229
+ * @param entry - The value to inspect
1230
+ * @param ancestors - Objects on the active traversal path
1231
+ * @returns `true` when the value is a cycle-free JSON value
1232
+ *
1233
+ * @example
1234
+ * ```ts
1235
+ * matchesJSONValue({ nested: [1, 'x', null] }, new WeakSet()) // true
1236
+ * matchesJSONValue(Number.NaN, new WeakSet()) // false
1237
+ * ```
1238
+ */
1239
+ function matchesJSONValue(entry, ancestors) {
1240
+ if (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true;
1241
+ if (Array.isArray(entry)) {
1242
+ if (ancestors.has(entry)) return false;
1243
+ ancestors.add(entry);
1244
+ let valid = true;
1245
+ for (let index = 0; index < entry.length; index += 1) if (!Object.hasOwn(entry, index) || !matchesJSONValue(entry[index], ancestors)) {
1246
+ valid = false;
1247
+ break;
1248
+ }
1249
+ ancestors.delete(entry);
1250
+ return valid;
1251
+ }
1252
+ if (!isRecord(entry)) return false;
1253
+ if (ancestors.has(entry)) return false;
1254
+ ancestors.add(entry);
1255
+ const valid = Object.values(entry).every((value) => matchesJSONValue(value, ancestors));
1256
+ ancestors.delete(entry);
1257
+ return valid;
1258
+ }
1259
+ /**
1084
1260
  * Build a deterministic pseudo-random source seeded from a single number.
1085
1261
  *
1086
1262
  * @remarks
@@ -1296,41 +1472,553 @@ function shapeToKind(shape) {
1296
1472
  }
1297
1473
  }
1298
1474
  //#endregion
1299
- //#region src/core/combinators.ts
1300
- function arrayOf(elementGuard) {
1301
- return (value) => {
1302
- if (!isArray(value)) return false;
1303
- const outcome = attempt(() => value.every(elementGuard));
1304
- return outcome.success && outcome.value;
1305
- };
1475
+ //#region src/core/cloners.ts
1476
+ /**
1477
+ * Deep-clone exact JSON data into an owned frozen snapshot.
1478
+ *
1479
+ * @remarks
1480
+ * Traverses iteratively so deeply nested input cannot exhaust the call stack.
1481
+ * Repeated noncyclic aliases are duplicated because JSON persistence represents
1482
+ * a tree, while a structural back-edge on the active path is rejected as a
1483
+ * cycle. Arrays are rebuilt as standard dense arrays and records as
1484
+ * null-prototype objects; every produced node is frozen after its children are
1485
+ * wired. Array keys must be exactly `length` plus every canonical index.
1486
+ * Writable and configurable index flags are normalized rather than treated as
1487
+ * JSON data, so frozen arrays remain valid. Property descriptors are inspected
1488
+ * without reading values through accessors, and every hostile reflective
1489
+ * operation is contained before a new clone-coded error is exposed.
1490
+ *
1491
+ * @param value - The unknown value to validate and snapshot
1492
+ * @returns The primitive unchanged, or a deeply cloned and frozen JSON graph
1493
+ * @throws {ContractError} When the value is not exact acyclic JSON data or traversal fails
1494
+ *
1495
+ * @example
1496
+ * ```ts
1497
+ * const source = { settings: { enabled: true } }
1498
+ * const clone = cloneJSONValue(source)
1499
+ * source.settings.enabled = false
1500
+ * clone // { settings: { enabled: true } }
1501
+ * ```
1502
+ */
1503
+ function cloneJSONValue(value) {
1504
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
1505
+ if (typeof value === "number") {
1506
+ if (Number.isFinite(value)) return value;
1507
+ throw new ContractError("cloneJSONValue: number is not finite", {
1508
+ code: "clone",
1509
+ context: { shape: "json" }
1510
+ });
1511
+ }
1512
+ if (typeof value !== "object") throw new ContractError("cloneJSONValue: value is not JSON data", {
1513
+ code: "clone",
1514
+ context: { shape: "json" }
1515
+ });
1516
+ const arrayOutcome = attempt(() => Array.isArray(value));
1517
+ if (!arrayOutcome.success) throw new ContractError("cloneJSONValue: value brand could not be inspected", {
1518
+ code: "clone",
1519
+ context: { shape: "json" }
1520
+ });
1521
+ let root;
1522
+ if (arrayOutcome.value) root = [];
1523
+ else if (isRecord(value)) root = Object.create(null);
1524
+ else throw new ContractError("cloneJSONValue: object is not a plain record", {
1525
+ code: "clone",
1526
+ context: { shape: "json" }
1527
+ });
1528
+ const active = /* @__PURE__ */ new WeakSet();
1529
+ active.add(value);
1530
+ const pending = [{
1531
+ source: value,
1532
+ clone: root,
1533
+ array: arrayOutcome.value,
1534
+ entries: void 0,
1535
+ index: 0
1536
+ }];
1537
+ while (pending.length > 0) {
1538
+ const frame = pending[pending.length - 1];
1539
+ if (frame === void 0) continue;
1540
+ if (frame.entries === void 0) {
1541
+ const keysOutcome = attempt(() => Reflect.ownKeys(frame.source));
1542
+ if (!keysOutcome.success) throw new ContractError("cloneJSONValue: own keys could not be inspected", {
1543
+ code: "clone",
1544
+ context: { shape: "json" }
1545
+ });
1546
+ const keys = keysOutcome.value;
1547
+ const entries = [];
1548
+ if (frame.array) {
1549
+ const lengthOutcome = attempt(() => Reflect.getOwnPropertyDescriptor(frame.source, "length"));
1550
+ if (!lengthOutcome.success) throw new ContractError("cloneJSONValue: array length could not be inspected", {
1551
+ code: "clone",
1552
+ context: { shape: "json" }
1553
+ });
1554
+ const lengthDescriptor = lengthOutcome.value;
1555
+ if (lengthDescriptor === void 0 || !("value" in lengthDescriptor) || typeof lengthDescriptor.value !== "number" || !Number.isInteger(lengthDescriptor.value) || lengthDescriptor.value < 0 || lengthDescriptor.value > 4294967295 || lengthDescriptor.enumerable !== false || lengthDescriptor.configurable !== false) throw new ContractError("cloneJSONValue: array is not intrinsic and dense", {
1556
+ code: "clone",
1557
+ context: { shape: "json" }
1558
+ });
1559
+ const remaining = new Set(keys);
1560
+ if (!remaining.delete("length")) throw new ContractError("cloneJSONValue: array own keys are not exact", {
1561
+ code: "clone",
1562
+ context: { shape: "json" }
1563
+ });
1564
+ for (let index = 0; index < lengthDescriptor.value; index += 1) {
1565
+ const key = String(index);
1566
+ if (!remaining.delete(key)) throw new ContractError("cloneJSONValue: array own keys are not exact", {
1567
+ code: "clone",
1568
+ context: { shape: "json" }
1569
+ });
1570
+ const descriptorOutcome = attempt(() => Reflect.getOwnPropertyDescriptor(frame.source, key));
1571
+ if (!descriptorOutcome.success) throw new ContractError("cloneJSONValue: array index could not be inspected", {
1572
+ code: "clone",
1573
+ context: { shape: "json" }
1574
+ });
1575
+ const descriptor = descriptorOutcome.value;
1576
+ if (descriptor === void 0 || !("value" in descriptor) || descriptor.enumerable !== true) throw new ContractError("cloneJSONValue: array index is not enumerable data", {
1577
+ code: "clone",
1578
+ context: { shape: "json" }
1579
+ });
1580
+ entries.push([key, descriptor.value]);
1581
+ }
1582
+ if (remaining.size !== 0) throw new ContractError("cloneJSONValue: array own keys are not exact", {
1583
+ code: "clone",
1584
+ context: { shape: "json" }
1585
+ });
1586
+ } else for (const key of keys) {
1587
+ if (typeof key !== "string") throw new ContractError("cloneJSONValue: record has a symbol property", {
1588
+ code: "clone",
1589
+ context: { shape: "json" }
1590
+ });
1591
+ const descriptorOutcome = attempt(() => Reflect.getOwnPropertyDescriptor(frame.source, key));
1592
+ if (!descriptorOutcome.success) throw new ContractError("cloneJSONValue: record property could not be inspected", {
1593
+ code: "clone",
1594
+ context: { shape: "json" }
1595
+ });
1596
+ const descriptor = descriptorOutcome.value;
1597
+ if (descriptor === void 0 || !("value" in descriptor) || descriptor.enumerable !== true) throw new ContractError("cloneJSONValue: record property is not enumerable data", {
1598
+ code: "clone",
1599
+ context: { shape: "json" }
1600
+ });
1601
+ entries.push([key, descriptor.value]);
1602
+ }
1603
+ frame.entries = entries;
1604
+ }
1605
+ const entry = frame.entries[frame.index];
1606
+ if (entry === void 0) {
1607
+ Object.freeze(frame.clone);
1608
+ active.delete(frame.source);
1609
+ pending.pop();
1610
+ continue;
1611
+ }
1612
+ frame.index += 1;
1613
+ const key = entry[0];
1614
+ const source = entry[1];
1615
+ let clone;
1616
+ if (source === null || typeof source === "string" || typeof source === "boolean") clone = source;
1617
+ else if (typeof source === "number") {
1618
+ if (!Number.isFinite(source)) throw new ContractError("cloneJSONValue: number is not finite", {
1619
+ code: "clone",
1620
+ context: { shape: "json" }
1621
+ });
1622
+ clone = source;
1623
+ } else if (typeof source === "object") {
1624
+ if (active.has(source)) throw new ContractError("cloneJSONValue: cycle detected", {
1625
+ code: "clone",
1626
+ context: { shape: "json" }
1627
+ });
1628
+ const childArrayOutcome = attempt(() => Array.isArray(source));
1629
+ if (!childArrayOutcome.success) throw new ContractError("cloneJSONValue: value brand could not be inspected", {
1630
+ code: "clone",
1631
+ context: { shape: "json" }
1632
+ });
1633
+ let child;
1634
+ if (childArrayOutcome.value) child = [];
1635
+ else if (isRecord(source)) child = Object.create(null);
1636
+ else throw new ContractError("cloneJSONValue: object is not a plain record", {
1637
+ code: "clone",
1638
+ context: { shape: "json" }
1639
+ });
1640
+ clone = child;
1641
+ active.add(source);
1642
+ pending.push({
1643
+ source,
1644
+ clone: child,
1645
+ array: childArrayOutcome.value,
1646
+ entries: void 0,
1647
+ index: 0
1648
+ });
1649
+ } else throw new ContractError("cloneJSONValue: property is not JSON data", {
1650
+ code: "clone",
1651
+ context: { shape: "json" }
1652
+ });
1653
+ Object.defineProperty(frame.clone, key, {
1654
+ value: clone,
1655
+ enumerable: true,
1656
+ configurable: true,
1657
+ writable: true
1658
+ });
1659
+ }
1660
+ return root;
1306
1661
  }
1307
- function tupleOf(...guards) {
1308
- return (value) => {
1309
- if (!isArray(value)) return false;
1310
- const outcome = attempt(() => {
1311
- if (value.length !== guards.length) return false;
1312
- for (let index = 0; index < guards.length; index += 1) {
1313
- const guard = guards[index];
1314
- if (!guard?.(value[index])) return false;
1662
+ /**
1663
+ * Deep-clone an exact JSON object record into an owned frozen snapshot.
1664
+ *
1665
+ * @remarks
1666
+ * Adds a record-root boundary to {@link cloneJSONValue}. The output is a
1667
+ * deeply frozen null-prototype record, and repeated noncyclic aliases are
1668
+ * duplicated as independent JSON tree branches.
1669
+ *
1670
+ * @param value - The unknown record value to validate and snapshot
1671
+ * @returns A deeply cloned and frozen JSON record
1672
+ * @throws {ContractError} When the root is not a record, nested data is inexact, or traversal fails
1673
+ *
1674
+ * @example
1675
+ * ```ts
1676
+ * cloneJSONRecord({ attempt: 1 }) // frozen null-prototype record
1677
+ * ```
1678
+ */
1679
+ function cloneJSONRecord(value) {
1680
+ if (!isRecord(value)) throw new ContractError("cloneJSONRecord: value is not a plain record", {
1681
+ code: "clone",
1682
+ context: { shape: "json" }
1683
+ });
1684
+ const clone = cloneJSONValue(value);
1685
+ if (!isRecord(clone)) throw new ContractError("cloneJSONRecord: cloned value is not a record", {
1686
+ code: "clone",
1687
+ context: { shape: "json" }
1688
+ });
1689
+ return clone;
1690
+ }
1691
+ /**
1692
+ * Deep-clone a JSON Schema graph into an owned frozen snapshot.
1693
+ *
1694
+ * @remarks
1695
+ * Walks arrays and records iteratively with a memo, preserving shared
1696
+ * references and closing cyclic edges onto their cloned nodes. Primitive
1697
+ * values and own enumerable string-keyed edges are copied; record nodes use
1698
+ * null prototypes, arrays retain only their intrinsic array prototype, and
1699
+ * every produced object is frozen after its edges are wired. Hostile traversal
1700
+ * throws a clone-coded {@link ContractError}, never a caller-owned raw error.
1701
+ *
1702
+ * @param schema - The JSON Schema graph to snapshot
1703
+ * @returns A deeply cloned and frozen JSON Schema graph
1704
+ * @throws {ContractError} When hostile schema traversal prevents ownership
1705
+ *
1706
+ * @example
1707
+ * ```ts
1708
+ * const child = { type: 'string' }
1709
+ * const clone = cloneSchema({ anyOf: [child, child] })
1710
+ * clone.anyOf?.[0] === clone.anyOf?.[1] // true
1711
+ * ```
1712
+ */
1713
+ function cloneSchema(schema) {
1714
+ try {
1715
+ const root = Object.create(null);
1716
+ const memo = /* @__PURE__ */ new Map([[schema, root]]);
1717
+ const pending = [{
1718
+ source: schema,
1719
+ clone: root,
1720
+ path: []
1721
+ }];
1722
+ while (pending.length > 0) {
1723
+ const frame = pending.pop();
1724
+ if (frame === void 0) continue;
1725
+ const keys = enumerableKeys(frame.source);
1726
+ if (keys === void 0) throw new ContractError("cloneSchema: property enumeration failed", {
1727
+ code: "clone",
1728
+ context: {
1729
+ path: frame.path,
1730
+ shape: "schema"
1731
+ }
1732
+ });
1733
+ for (const key of keys) {
1734
+ const outcome = attempt(() => Reflect.get(frame.source, key));
1735
+ if (!outcome.success) throw new ContractError("cloneSchema: property access failed", {
1736
+ code: "clone",
1737
+ context: {
1738
+ path: [...frame.path, key],
1739
+ shape: "schema"
1740
+ },
1741
+ cause: outcome.error
1742
+ });
1743
+ const source = outcome.value;
1744
+ let clone = source;
1745
+ if (typeof source === "object" && source !== null) {
1746
+ const existing = memo.get(source);
1747
+ if (existing !== void 0) clone = existing;
1748
+ else {
1749
+ const child = Array.isArray(source) ? [] : Object.create(null);
1750
+ memo.set(source, child);
1751
+ pending.push({
1752
+ source,
1753
+ clone: child,
1754
+ path: [...frame.path, key]
1755
+ });
1756
+ clone = child;
1757
+ }
1758
+ }
1759
+ Object.defineProperty(frame.clone, key, {
1760
+ value: clone,
1761
+ enumerable: true,
1762
+ configurable: true,
1763
+ writable: true
1764
+ });
1315
1765
  }
1316
- return true;
1766
+ Object.freeze(frame.clone);
1767
+ }
1768
+ return root;
1769
+ } catch (reason) {
1770
+ if (reason instanceof ContractError) throw reason;
1771
+ throw new ContractError("cloneSchema: failed to create an owned schema snapshot", {
1772
+ code: "clone",
1773
+ context: { shape: "schema" },
1774
+ cause: reason
1317
1775
  });
1318
- return outcome.success && outcome.value;
1319
- };
1776
+ }
1777
+ }
1778
+ function cloneShape(shape) {
1779
+ try {
1780
+ const memo = /* @__PURE__ */ new Map();
1781
+ const pending = [shape];
1782
+ const sources = [];
1783
+ let root = shape;
1784
+ while (pending.length > 0) {
1785
+ const source = pending.pop();
1786
+ if (source === void 0 || memo.has(source)) continue;
1787
+ let clone;
1788
+ switch (source.type) {
1789
+ case "string": {
1790
+ const pattern = source.pattern;
1791
+ const fields = {
1792
+ type: "string",
1793
+ ...source.min === void 0 ? {} : { min: source.min },
1794
+ ...source.max === void 0 ? {} : { max: source.max },
1795
+ ...source.description === void 0 ? {} : { description: source.description }
1796
+ };
1797
+ if (pattern === void 0) clone = fields;
1798
+ else {
1799
+ const patternSource = pattern.source;
1800
+ const patternFlags = pattern.flags;
1801
+ clone = {
1802
+ ...fields,
1803
+ get pattern() {
1804
+ return Object.freeze(new RegExp(patternSource, patternFlags));
1805
+ }
1806
+ };
1807
+ }
1808
+ break;
1809
+ }
1810
+ case "number":
1811
+ clone = {
1812
+ type: "number",
1813
+ ...source.min === void 0 ? {} : { min: source.min },
1814
+ ...source.max === void 0 ? {} : { max: source.max },
1815
+ ...source.integer === void 0 ? {} : { integer: source.integer },
1816
+ ...source.description === void 0 ? {} : { description: source.description }
1817
+ };
1818
+ break;
1819
+ case "boolean":
1820
+ clone = {
1821
+ type: "boolean",
1822
+ ...source.description === void 0 ? {} : { description: source.description }
1823
+ };
1824
+ break;
1825
+ case "null":
1826
+ clone = {
1827
+ type: "null",
1828
+ ...source.description === void 0 ? {} : { description: source.description }
1829
+ };
1830
+ break;
1831
+ case "literal":
1832
+ clone = {
1833
+ type: "literal",
1834
+ values: Object.freeze([...source.values]),
1835
+ ...source.description === void 0 ? {} : { description: source.description }
1836
+ };
1837
+ break;
1838
+ case "array":
1839
+ clone = {
1840
+ type: "array",
1841
+ items: source.items,
1842
+ ...source.min === void 0 ? {} : { min: source.min },
1843
+ ...source.max === void 0 ? {} : { max: source.max },
1844
+ ...source.description === void 0 ? {} : { description: source.description }
1845
+ };
1846
+ pending.push(source.items);
1847
+ break;
1848
+ case "object": {
1849
+ const extra = source.additionalProperties;
1850
+ clone = {
1851
+ type: "object",
1852
+ properties: Object.create(null),
1853
+ ...extra === void 0 || extra !== true && extra !== false ? {} : { additionalProperties: extra },
1854
+ ...source.description === void 0 ? {} : { description: source.description }
1855
+ };
1856
+ for (const key of Object.keys(source.properties)) {
1857
+ const child = source.properties[key];
1858
+ if (child !== void 0) pending.push(child);
1859
+ }
1860
+ if (extra !== void 0 && extra !== true && extra !== false) pending.push(extra);
1861
+ break;
1862
+ }
1863
+ case "union":
1864
+ clone = {
1865
+ type: "union",
1866
+ variants: [],
1867
+ ...source.mode === void 0 ? {} : { mode: source.mode },
1868
+ ...source.description === void 0 ? {} : { description: source.description }
1869
+ };
1870
+ for (const variant of source.variants) pending.push(variant);
1871
+ break;
1872
+ case "optional":
1873
+ clone = {
1874
+ type: "optional",
1875
+ inner: source.inner
1876
+ };
1877
+ pending.push(source.inner);
1878
+ break;
1879
+ case "nullable":
1880
+ clone = {
1881
+ type: "nullable",
1882
+ inner: source.inner
1883
+ };
1884
+ pending.push(source.inner);
1885
+ break;
1886
+ case "json":
1887
+ clone = {
1888
+ type: "json",
1889
+ ...source.description === void 0 ? {} : { description: source.description }
1890
+ };
1891
+ break;
1892
+ case "raw": {
1893
+ const outcome = attempt(() => source.schema);
1894
+ if (!outcome.success) throw new ContractError("cloneShape: raw schema access failed", {
1895
+ code: "clone",
1896
+ context: { shape: "raw" },
1897
+ cause: outcome.error
1898
+ });
1899
+ clone = {
1900
+ type: "raw",
1901
+ schema: cloneSchema(outcome.value)
1902
+ };
1903
+ break;
1904
+ }
1905
+ }
1906
+ memo.set(source, clone);
1907
+ if (source === shape) root = clone;
1908
+ sources.push(source);
1909
+ }
1910
+ for (const source of sources) {
1911
+ const clone = memo.get(source);
1912
+ if (clone === void 0) continue;
1913
+ switch (source.type) {
1914
+ case "array": {
1915
+ const items = memo.get(source.items);
1916
+ if (items !== void 0) Reflect.set(clone, "items", items);
1917
+ break;
1918
+ }
1919
+ case "object": {
1920
+ const properties = Object.create(null);
1921
+ for (const key of Object.keys(source.properties)) {
1922
+ const child = source.properties[key];
1923
+ if (child === void 0) continue;
1924
+ const clonedChild = memo.get(child);
1925
+ if (clonedChild !== void 0) properties[key] = clonedChild;
1926
+ }
1927
+ Reflect.set(clone, "properties", Object.freeze(properties));
1928
+ const extra = source.additionalProperties;
1929
+ if (extra !== void 0 && extra !== true && extra !== false) {
1930
+ const clonedExtra = memo.get(extra);
1931
+ if (clonedExtra !== void 0) Reflect.set(clone, "additionalProperties", clonedExtra);
1932
+ }
1933
+ break;
1934
+ }
1935
+ case "union": {
1936
+ const variants = [];
1937
+ for (const variant of source.variants) {
1938
+ const clonedVariant = memo.get(variant);
1939
+ if (clonedVariant !== void 0) variants.push(clonedVariant);
1940
+ }
1941
+ Reflect.set(clone, "variants", Object.freeze(variants));
1942
+ break;
1943
+ }
1944
+ case "optional":
1945
+ case "nullable": {
1946
+ const inner = memo.get(source.inner);
1947
+ if (inner !== void 0) Reflect.set(clone, "inner", inner);
1948
+ break;
1949
+ }
1950
+ default: break;
1951
+ }
1952
+ Object.freeze(clone);
1953
+ }
1954
+ return root;
1955
+ } catch (reason) {
1956
+ if (isContractError(reason) && reason.code === "clone") throw reason;
1957
+ throw new ContractError("cloneShape: failed to create an owned shape snapshot", {
1958
+ code: "clone",
1959
+ context: { shape: "shape" },
1960
+ cause: reason
1961
+ });
1962
+ }
1320
1963
  }
1321
1964
  /**
1322
- * Build a guard that accepts values identical (via `Object.is`) to one of the
1323
- * provided literal primitives.
1965
+ * Take ownership of a contract shape node — the node itself when it is already
1966
+ * frozen, otherwise a {@link cloneShape} snapshot of its graph.
1967
+ *
1968
+ * @remarks
1969
+ * Builder- and `cloneShape`-produced frozen means owned: those nodes have frozen
1970
+ * `properties` / `variants` / `values` collections and pattern accessors that
1971
+ * return fresh frozen snapshots, so they cannot drift under a caller who still
1972
+ * holds an input reference or a previously read pattern. `Object.freeze` on a
1973
+ * hand-authored pattern shape is not an ownership marker because it cannot
1974
+ * protect `RegExp` internal slots; leave that shape unfrozen for this function
1975
+ * to snapshot, or pass it through {@link cloneShape} first.
1976
+ *
1977
+ * Every compiler entry point (`compileSchema` / `compileGuard` /
1978
+ * `compileParser` / `compileGenerator` / `compileReporter`) opens with this
1979
+ * call, and the check applies per node as the recursion descends: a frozen
1980
+ * parent is trusted for its own fields while each child is owned again at its
1981
+ * own level, so a hand-assembled graph that froze only part of itself is still
1982
+ * compiled from owned data.
1983
+ *
1984
+ * @param shape - The contract shape to own
1985
+ * @returns The shape itself when frozen, otherwise a deeply cloned frozen snapshot
1324
1986
  *
1325
1987
  * @example
1326
1988
  * ```ts
1327
- * const isRole = literalOf('admin', 'member', 'guest')
1328
- * isRole('admin') // true
1329
- * isRole('owner') // false
1989
+ * const authored = stringShape() // builders freeze
1990
+ * ownShape(authored) === authored // true
1991
+ * ownShape({ type: 'string' }) // a frozen snapshot — the literal is caller-owned
1330
1992
  * ```
1331
1993
  */
1994
+ function ownShape(shape) {
1995
+ return Object.isFrozen(shape) ? shape : cloneShape(shape);
1996
+ }
1997
+ //#endregion
1998
+ //#region src/core/combinators.ts
1999
+ function arrayOf(elementGuard) {
2000
+ return (value) => holds(() => {
2001
+ if (!isArray(value)) return false;
2002
+ for (let index = 0; index < value.length; index += 1) if (!Object.hasOwn(value, index) || !elementGuard(value[index])) return false;
2003
+ return true;
2004
+ });
2005
+ }
2006
+ function tupleOf(...guards) {
2007
+ return (value) => holds(() => {
2008
+ if (!isArray(value)) return false;
2009
+ if (value.length !== guards.length) return false;
2010
+ for (let index = 0; index < guards.length; index += 1) {
2011
+ const guard = guards[index];
2012
+ if (!Object.hasOwn(value, index) || guard === void 0 || !guard(value[index])) return false;
2013
+ }
2014
+ return true;
2015
+ });
2016
+ }
1332
2017
  function literalOf(...literals) {
1333
- return (value) => literals.some((literal) => Object.is(literal, value));
2018
+ const [first] = literals;
2019
+ const values = literals.length === 1 && isArray(first) ? first : literals;
2020
+ const allowed = new Set(values);
2021
+ return (value) => allowed.has(value);
1334
2022
  }
1335
2023
  /**
1336
2024
  * Build a guard that accepts instances of the provided constructor.
@@ -1366,24 +2054,18 @@ function enumOf(enumeration) {
1366
2054
  return (value) => (isString(value) || isNumber(value)) && values.has(value);
1367
2055
  }
1368
2056
  function setOf(elementGuard) {
1369
- return (value) => {
2057
+ return (value) => holds(() => {
1370
2058
  if (!isSet(value)) return false;
1371
- const outcome = attempt(() => {
1372
- for (const entry of value) if (!elementGuard(entry)) return false;
1373
- return true;
1374
- });
1375
- return outcome.success && outcome.value;
1376
- };
2059
+ for (const entry of value) if (!elementGuard(entry)) return false;
2060
+ return true;
2061
+ });
1377
2062
  }
1378
2063
  function mapOf(keyGuard, valueGuard) {
1379
- return (value) => {
2064
+ return (value) => holds(() => {
1380
2065
  if (!isMap(value)) return false;
1381
- const outcome = attempt(() => {
1382
- for (const [key, entryValue] of value) if (!keyGuard(key) || !valueGuard(entryValue)) return false;
1383
- return true;
1384
- });
1385
- return outcome.success && outcome.value;
1386
- };
2066
+ for (const [key, entryValue] of value) if (!keyGuard(key) || !valueGuard(entryValue)) return false;
2067
+ return true;
2068
+ });
1387
2069
  }
1388
2070
  /**
1389
2071
  * Build a guard that accepts plain records matching a guard shape.
@@ -1397,9 +2079,8 @@ function mapOf(keyGuard, valueGuard) {
1397
2079
  * Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by
1398
2080
  * an inherited prototype member (`toString`, `constructor`, …) counts as absent.
1399
2081
  * A non-object / `null` / array input returns `false` rather than throwing. The
1400
- * extra-key check only inspects `Object.keys` (string keys), so an extra
1401
- * enumerable SYMBOL key is never rejected — intentional, for JSON fidelity, and
1402
- * matches the compiled guard.
2082
+ * The exactness check inspects every own string key, including non-enumerable
2083
+ * keys. Symbol keys are ignored intentionally for JSON fidelity.
1403
2084
  *
1404
2085
  * @example
1405
2086
  * ```ts
@@ -1413,35 +2094,21 @@ function mapOf(keyGuard, valueGuard) {
1413
2094
  */
1414
2095
  function recordOf(shape, optional) {
1415
2096
  const allowed = /* @__PURE__ */ new Set();
1416
- for (const key in shape) if (Object.prototype.hasOwnProperty.call(shape, key)) allowed.add(key);
2097
+ for (const key of Reflect.ownKeys(shape)) if (isString(key)) allowed.add(key);
1417
2098
  const optionalSet = new Set(optional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : []);
1418
- return (value) => {
2099
+ return (value) => holds(() => {
1419
2100
  if (!isRecord(value)) return false;
1420
- const outcome = attempt(() => {
1421
- for (const key of Object.keys(value)) if (!allowed.has(key)) return false;
1422
- for (const key in shape) {
1423
- if (!Object.prototype.hasOwnProperty.call(shape, key)) continue;
1424
- const present = Object.hasOwn(value, key);
1425
- if (!optionalSet.has(key) && !present) return false;
1426
- if (present) {
1427
- const guard = shape[key];
1428
- if (!guard(value[key])) return false;
1429
- }
2101
+ for (const key of Reflect.ownKeys(value)) if (isString(key) && !allowed.has(key)) return false;
2102
+ for (const key of allowed) {
2103
+ const present = Object.hasOwn(value, key);
2104
+ if (!optionalSet.has(key) && !present) return false;
2105
+ if (present) {
2106
+ const guard = shape[key];
2107
+ if (guard === void 0 || !guard(value[key])) return false;
1430
2108
  }
1431
- return true;
1432
- });
1433
- return outcome.success && outcome.value;
1434
- };
1435
- }
1436
- function iterableOf(elementGuard) {
1437
- return (value) => {
1438
- if (!isIterable(value)) return false;
1439
- const outcome = attempt(() => {
1440
- for (const entry of value) if (!elementGuard(entry)) return false;
1441
- return true;
1442
- });
1443
- return outcome.success && outcome.value;
1444
- };
2109
+ }
2110
+ return true;
2111
+ });
1445
2112
  }
1446
2113
  /**
1447
2114
  * Build a guard that accepts values that are own keys of the provided object.
@@ -1461,7 +2128,7 @@ function iterableOf(elementGuard) {
1461
2128
  * ```
1462
2129
  */
1463
2130
  function keyOf(value) {
1464
- return (entry) => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry);
2131
+ return (entry) => holds(() => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry));
1465
2132
  }
1466
2133
  /**
1467
2134
  * Build a new guard shape by keeping only the listed keys — the structural
@@ -1501,10 +2168,10 @@ function omitOf(shape, keys) {
1501
2168
  return result;
1502
2169
  }
1503
2170
  function andOf(left, right) {
1504
- return (value) => left(value) && right(value);
2171
+ return (value) => holds(() => left(value) && right(value));
1505
2172
  }
1506
2173
  function orOf(left, right) {
1507
- return (value) => left(value) || right(value);
2174
+ return (value) => holds(() => left(value) || right(value));
1508
2175
  }
1509
2176
  /**
1510
2177
  * Negate a guard or predicate — passes when `guard` returns `false`.
@@ -1519,7 +2186,7 @@ function orOf(left, right) {
1519
2186
  * ```
1520
2187
  */
1521
2188
  function notOf(guard) {
1522
- return (value) => !guard(value);
2189
+ return (value) => holds(() => !guard(value));
1523
2190
  }
1524
2191
  /**
1525
2192
  * Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass
@@ -1533,23 +2200,16 @@ function notOf(guard) {
1533
2200
  * ```
1534
2201
  */
1535
2202
  function complementOf(base, excluded) {
1536
- return (value) => {
1537
- if (!base(value)) return false;
1538
- return !excluded(value);
1539
- };
2203
+ return (value) => holds(() => base(value) && !excluded(value));
1540
2204
  }
1541
2205
  function unionOf(...guards) {
1542
- return (value) => guards.some((guard) => guard(value));
2206
+ return (value) => holds(() => guards.some((guard) => guard(value)));
1543
2207
  }
1544
2208
  function intersectionOf(...guards) {
1545
- return (value) => guards.every((guard) => guard(value));
2209
+ return (value) => holds(() => guards.every((guard) => guard(value)));
1546
2210
  }
1547
2211
  function whereOf(base, predicate) {
1548
- return (value) => {
1549
- if (!base(value)) return false;
1550
- const outcome = attempt(() => predicate(value));
1551
- return outcome.success && outcome.value;
1552
- };
2212
+ return (value) => holds(() => base(value) && predicate(value));
1553
2213
  }
1554
2214
  /**
1555
2215
  * Defer guard creation until first use by calling `thunk()` on every
@@ -1561,10 +2221,10 @@ function whereOf(base, predicate) {
1561
2221
  * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard
1562
2222
  * it resolves to) is contained and reported as a non-match.
1563
2223
  *
1564
- * A recursive guard built this way has no cycle/depth detection: a cyclic or
1565
- * pathologically deep input is stack-bounded — the overflow is contained and the
1566
- * guard returns `false` rather than throwing, but it is not validated correctly
1567
- * past that bound.
2224
+ * Each lazy guard tracks its active invocation depth. An invocation that would
2225
+ * exceed {@link GUARD_DEPTH_LIMIT} returns `false` before resolving `thunk`; the
2226
+ * counter always unwinds after the contained call, so one deep or cyclic input
2227
+ * cannot poison later guard calls.
1568
2228
  *
1569
2229
  * @example
1570
2230
  * ```ts
@@ -1574,17 +2234,19 @@ function whereOf(base, predicate) {
1574
2234
  * ```
1575
2235
  */
1576
2236
  function lazyOf(thunk) {
2237
+ let depth = 0;
1577
2238
  return (value) => {
1578
- const outcome = attempt(() => thunk()(value));
1579
- return outcome.success && outcome.value;
2239
+ if (depth >= 512) return false;
2240
+ depth += 1;
2241
+ try {
2242
+ return holds(() => thunk()(value));
2243
+ } finally {
2244
+ depth -= 1;
2245
+ }
1580
2246
  };
1581
2247
  }
1582
2248
  function transformOf(base, project, target) {
1583
- return (value) => {
1584
- if (!base(value)) return false;
1585
- const outcome = attempt(() => project(value));
1586
- return outcome.success && target(outcome.value);
1587
- };
2249
+ return (value) => holds(() => base(value) && target(project(value)));
1588
2250
  }
1589
2251
  /**
1590
2252
  * Build a guard that accepts finite numbers within an inclusive `[min, max]`
@@ -1614,6 +2276,13 @@ function boundsOf(min, max) {
1614
2276
  /**
1615
2277
  * Build a guard that accepts strings matching a regular expression.
1616
2278
  *
2279
+ * @remarks
2280
+ * Clones the pattern for the guard and strips the stateful `g` / `y` flags, so
2281
+ * repeated checks are stable and never change the caller's `lastIndex`.
2282
+ *
2283
+ * @param pattern - The regular expression to own and apply
2284
+ * @returns A stateless string guard
2285
+ *
1617
2286
  * @example
1618
2287
  * ```ts
1619
2288
  * const isHex = matchOf(/^[0-9a-f]+$/)
@@ -1622,7 +2291,8 @@ function boundsOf(min, max) {
1622
2291
  * ```
1623
2292
  */
1624
2293
  function matchOf(pattern) {
1625
- return whereOf(isString, (value) => pattern.test(value));
2294
+ const owned = new RegExp(pattern.source, pattern.flags.replaceAll("g", "").replaceAll("y", ""));
2295
+ return whereOf(isString, (value) => owned.test(value));
1626
2296
  }
1627
2297
  /**
1628
2298
  * Build a guard that accepts strings satisfying optional length and pattern
@@ -1630,10 +2300,14 @@ function matchOf(pattern) {
1630
2300
  *
1631
2301
  * @remarks
1632
2302
  * Composes {@link isString} with {@link boundsOf} on the string's `.length` and
1633
- * an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns
1634
- * the bare {@link isString} guard (the unconstrained fast path), so an
1635
- * unrefined string leaf pays no wrapping cost. The single source of the string
1636
- * refinement shared by the compiled guard and parser (compilers.ts).
2303
+ * an owned stateless pattern (the same refinement {@link matchOf} performs).
2304
+ * When all three options are absent it returns the bare {@link isString} guard
2305
+ * (the unconstrained fast path), so an unrefined string leaf pays no wrapping
2306
+ * cost. The single source of the string refinement shared by the compiled guard
2307
+ * and parser (compilers.ts).
2308
+ *
2309
+ * @param options - Optional length bounds and regular expression refinement
2310
+ * @returns A string guard enforcing the requested refinements
1637
2311
  *
1638
2312
  * @example
1639
2313
  * ```ts
@@ -1648,7 +2322,8 @@ function matchOf(pattern) {
1648
2322
  function stringOf(options) {
1649
2323
  const min = options?.min;
1650
2324
  const max = options?.max;
1651
- const pattern = options?.pattern;
2325
+ const source = options?.pattern;
2326
+ const pattern = source === void 0 ? void 0 : new RegExp(source.source, source.flags.replaceAll("g", "").replaceAll("y", ""));
1652
2327
  if (min === void 0 && max === void 0 && pattern === void 0) return isString;
1653
2328
  const withinLength = boundsOf(min, max);
1654
2329
  return whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || pattern.test(value)));
@@ -1665,7 +2340,7 @@ function stringOf(options) {
1665
2340
  * ```
1666
2341
  */
1667
2342
  function nullableOf(guard) {
1668
- return (value) => value === null || guard(value);
2343
+ return (value) => holds(() => value === null || guard(value));
1669
2344
  }
1670
2345
  /**
1671
2346
  * Extend a guard to also allow `undefined` — the optional counterpart of
@@ -1680,7 +2355,7 @@ function nullableOf(guard) {
1680
2355
  * ```
1681
2356
  */
1682
2357
  function optionalOf(guard) {
1683
- return (value) => value === void 0 || guard(value);
2358
+ return (value) => holds(() => value === void 0 || guard(value));
1684
2359
  }
1685
2360
  //#endregion
1686
2361
  //#region src/core/parsers.ts
@@ -1824,7 +2499,10 @@ function parseRecord(value) {
1824
2499
  */
1825
2500
  function parseArray(value, guard) {
1826
2501
  if (!isArray(value)) return void 0;
1827
- if (guard !== void 0 && !value.every(guard)) return void 0;
2502
+ if (guard !== void 0 && !holds(() => {
2503
+ for (let index = 0; index < value.length; index += 1) if (!Object.hasOwn(value, index) || !guard(value[index])) return false;
2504
+ return true;
2505
+ })) return;
1828
2506
  return value;
1829
2507
  }
1830
2508
  /**
@@ -1851,27 +2529,10 @@ function parseArray(value, guard) {
1851
2529
  function parseJSONValue(value) {
1852
2530
  return isJSONValue(value) ? value : void 0;
1853
2531
  }
1854
- /**
1855
- * Parse an unknown value as one of the allowed literal primitives.
1856
- *
1857
- * @remarks
1858
- * Pairs with {@link literalOf} — both match by `Object.is`, so the
1859
- * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
1860
- * (string, number, or boolean), not only strings. Matching is identity, never
1861
- * cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
1862
- *
1863
- * @param value - The value to parse
1864
- * @param allowed - The permitted literal values
1865
- * @returns The matched literal (by identity), or `undefined`
1866
- *
1867
- * @example
1868
- * ```ts
1869
- * parseEnum('b', ['a', 'b', 'c']) // 'b'
1870
- * parseEnum('z', ['a', 'b', 'c']) // undefined
1871
- * ```
1872
- */
1873
2532
  function parseEnum(value, allowed) {
1874
- for (const option of allowed) if (Object.is(value, option)) return option;
2533
+ const outcome = attempt(() => Object.freeze(new Set(allowed)));
2534
+ if (!outcome.success || !outcome.value.has(value)) return void 0;
2535
+ return isString(value) || isNumber(value) || isBoolean(value) ? value : void 0;
1875
2536
  }
1876
2537
  /**
1877
2538
  * Read and parse a string field from a record by key or nested key path.
@@ -2049,18 +2710,119 @@ function parseJSON(value) {
2049
2710
  function parseJSONAs(value, guard) {
2050
2711
  const parsed = parseJSON(value);
2051
2712
  if (parsed === void 0) return void 0;
2052
- return guard(parsed) ? parsed : void 0;
2713
+ let result = void 0;
2714
+ holds(() => {
2715
+ if (!guard(parsed)) return false;
2716
+ result = parsed;
2717
+ return true;
2718
+ });
2719
+ return result;
2053
2720
  }
2054
2721
  //#endregion
2055
2722
  //#region src/core/compilers.ts
2056
2723
  /**
2057
- * Validate that a {@link ContractShape} tree is well-formed — a pure recursive
2058
- * prepass run before compilation.
2724
+ * Gate recursive compiler work on shape depth and structural cycles.
2725
+ *
2726
+ * @remarks
2727
+ * Walks the shape graph iteratively in linear time and stack space, tracking
2728
+ * active ancestors so shared children remain legal. Every standalone compiler
2729
+ * calls this gate before its recursive branch begins. The depth check runs
2730
+ * before the active-ancestor check, so a back-edge first reached beyond
2731
+ * {@link COMPILE_DEPTH_LIMIT} reports `depth`; a shallower cycle reports
2732
+ * `cycle`.
2733
+ *
2734
+ * @param shape - The shape graph to gate
2735
+ * @returns Nothing; successful return means recursive compilation is depth-safe
2736
+ * @throws {ContractError} When the shape is cyclic or exceeds the compilation depth limit
2737
+ */
2738
+ function validateShapeDepth(shape) {
2739
+ const active = /* @__PURE__ */ new WeakSet();
2740
+ const stack = [{
2741
+ operation: "enter",
2742
+ shape,
2743
+ depth: 0
2744
+ }];
2745
+ while (stack.length > 0) {
2746
+ const frame = stack.pop();
2747
+ if (frame === void 0) continue;
2748
+ if (frame.operation === "exit") {
2749
+ active.delete(frame.shape);
2750
+ continue;
2751
+ }
2752
+ const current = frame.shape;
2753
+ if (frame.depth > 512) throw new ContractError("validateShapeDepth: a shape exceeds the compilation depth limit", {
2754
+ code: "depth",
2755
+ context: {
2756
+ shape: current.type,
2757
+ limit: 512
2758
+ }
2759
+ });
2760
+ if (active.has(current)) throw new ContractError("validateShapeDepth: a shape graph may not contain a cycle", { code: "cycle" });
2761
+ active.add(current);
2762
+ stack.push({
2763
+ operation: "exit",
2764
+ shape: current
2765
+ });
2766
+ switch (current.type) {
2767
+ case "array":
2768
+ stack.push({
2769
+ operation: "enter",
2770
+ shape: current.items,
2771
+ depth: frame.depth + 1
2772
+ });
2773
+ break;
2774
+ case "object": {
2775
+ const extra = current.additionalProperties;
2776
+ if (extra !== void 0 && extra !== true && extra !== false) stack.push({
2777
+ operation: "enter",
2778
+ shape: extra,
2779
+ depth: frame.depth + 1
2780
+ });
2781
+ const keys = Object.keys(current.properties);
2782
+ for (let index = keys.length - 1; index >= 0; index -= 1) {
2783
+ const key = keys[index];
2784
+ if (key === void 0) continue;
2785
+ const child = current.properties[key];
2786
+ if (child !== void 0) stack.push({
2787
+ operation: "enter",
2788
+ shape: child,
2789
+ depth: frame.depth + 1
2790
+ });
2791
+ }
2792
+ break;
2793
+ }
2794
+ case "union":
2795
+ for (let index = current.variants.length - 1; index >= 0; index -= 1) {
2796
+ const variant = current.variants[index];
2797
+ if (variant !== void 0) stack.push({
2798
+ operation: "enter",
2799
+ shape: variant,
2800
+ depth: frame.depth + 1
2801
+ });
2802
+ }
2803
+ break;
2804
+ case "optional":
2805
+ case "nullable":
2806
+ stack.push({
2807
+ operation: "enter",
2808
+ shape: current.inner,
2809
+ depth: frame.depth + 1
2810
+ });
2811
+ break;
2812
+ default: break;
2813
+ }
2814
+ }
2815
+ }
2816
+ /**
2817
+ * Validate that a {@link ContractShape} graph is well-formed before
2818
+ * compilation.
2059
2819
  *
2060
2820
  * @remarks
2061
2821
  * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
2062
- * throws a plain `Error` immediately rather than surfacing as a silently-wrong
2063
- * guard, parser, schema, or generator later. Checks, recursively:
2822
+ * throws a coded {@link ContractError} immediately rather than surfacing as a
2823
+ * silently-wrong guard, parser, schema, or generator later. The iterative walk
2824
+ * tracks active ancestors, so a structural cycle reports its precise path while
2825
+ * a shared child reached through separate paths remains legal. Checks:
2064
2826
  *
2065
2827
  * - An {@link OptionalShape} is only legal as a direct object-property value —
2066
2828
  * `optionalShape` wrapping an array item, a union variant, another
@@ -2073,14 +2835,19 @@ function parseJSONAs(value, guard) {
2073
2835
  * `-Infinity`) number values.
2074
2836
  * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
2075
2837
  * needs `min <= max` when both are set.
2838
+ * - Every present number bound is finite.
2076
2839
  * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
2077
2840
  * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
2841
+ * - Shape nesting may not exceed {@link COMPILE_DEPTH_LIMIT}; excessive depth
2842
+ * fails before recursive artifact compilation begins. Because the depth check
2843
+ * runs before the active-ancestor check, a back-edge first reached beyond the
2844
+ * limit reports `depth`; a cycle reached within the limit reports `cycle`.
2078
2845
  * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
2079
2846
  * continues into array items, object properties (and `additionalProperties`
2080
2847
  * when it is a shape), union variants, and optional/nullable inner shapes.
2081
2848
  *
2082
2849
  * @param shape - The shape to validate
2083
- * @throws {Error} When the shape is malformed
2850
+ * @throws {ContractError} When the shape is malformed or cyclic
2084
2851
  *
2085
2852
  * @example
2086
2853
  * ```ts
@@ -2089,46 +2856,201 @@ function parseJSONAs(value, guard) {
2089
2856
  * ```
2090
2857
  */
2091
2858
  function validateShape(shape) {
2092
- switch (shape.type) {
2093
- case "string":
2094
- if (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error("validateShape: a string shape has min greater than max");
2095
- return;
2096
- case "number":
2097
- if (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error("validateShape: a number shape has min greater than max");
2098
- if (shape.integer === true) {
2099
- if (Math.ceil(shape.min ?? Number.NEGATIVE_INFINITY) > Math.floor(shape.max ?? Number.POSITIVE_INFINITY)) throw new Error("validateShape: an integer number shape has an empty integer range");
2859
+ const active = /* @__PURE__ */ new WeakSet();
2860
+ const stack = [{
2861
+ operation: "enter",
2862
+ shape,
2863
+ path: [],
2864
+ optional: false,
2865
+ depth: 0
2866
+ }];
2867
+ while (stack.length > 0) {
2868
+ const frame = stack.pop();
2869
+ if (frame === void 0) continue;
2870
+ if (frame.operation === "exit") {
2871
+ active.delete(frame.shape);
2872
+ continue;
2873
+ }
2874
+ const current = frame.shape;
2875
+ if (frame.depth > 512) throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
2876
+ code: "depth",
2877
+ context: {
2878
+ path: frame.path,
2879
+ shape: current.type,
2880
+ limit: 512
2100
2881
  }
2101
- return;
2102
- case "boolean":
2103
- case "null":
2104
- case "json":
2105
- case "raw": return;
2106
- case "literal":
2107
- if (shape.values.length === 0) throw new Error("validateShape: a literal shape needs at least one value");
2108
- for (const value of shape.values) if (typeof value === "number" && !Number.isFinite(value)) throw new Error("validateShape: a literal shape may not contain non-finite number values");
2109
- return;
2110
- case "array":
2111
- if (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error("validateShape: an array shape has min greater than max");
2112
- validateShape(shape.items);
2113
- return;
2114
- case "object": {
2115
- for (const key of Object.keys(shape.properties)) {
2116
- const child = shape.properties[key];
2117
- if (child === void 0) continue;
2118
- validateShape(child.type === "optional" ? child.inner : child);
2882
+ });
2883
+ if (active.has(current)) throw new ContractError("validateShape: a shape graph may not contain a cycle", {
2884
+ code: "cycle",
2885
+ context: { path: frame.path }
2886
+ });
2887
+ active.add(current);
2888
+ stack.push({
2889
+ operation: "exit",
2890
+ shape: current
2891
+ });
2892
+ switch (current.type) {
2893
+ case "string":
2894
+ if (current.min !== void 0 && current.max !== void 0 && current.min > current.max) throw new ContractError("validateShape: a string shape has min greater than max", {
2895
+ code: "range",
2896
+ context: {
2897
+ path: frame.path,
2898
+ shape: "string"
2899
+ }
2900
+ });
2901
+ break;
2902
+ case "number":
2903
+ if (current.min !== void 0 && !Number.isFinite(current.min)) throw new ContractError("validateShape: a number shape min must be finite", {
2904
+ code: "bound",
2905
+ context: {
2906
+ path: frame.path,
2907
+ shape: current.integer === true ? "integer" : "number",
2908
+ limit: "finite number",
2909
+ received: String(current.min)
2910
+ }
2911
+ });
2912
+ if (current.max !== void 0 && !Number.isFinite(current.max)) throw new ContractError("validateShape: a number shape max must be finite", {
2913
+ code: "bound",
2914
+ context: {
2915
+ path: frame.path,
2916
+ shape: current.integer === true ? "integer" : "number",
2917
+ limit: "finite number",
2918
+ received: String(current.max)
2919
+ }
2920
+ });
2921
+ if (current.min !== void 0 && current.max !== void 0 && current.min > current.max) throw new ContractError("validateShape: a number shape has min greater than max", {
2922
+ code: "range",
2923
+ context: {
2924
+ path: frame.path,
2925
+ shape: current.integer === true ? "integer" : "number"
2926
+ }
2927
+ });
2928
+ if (current.integer === true) {
2929
+ if (Math.ceil(current.min ?? Number.NEGATIVE_INFINITY) > Math.floor(current.max ?? Number.POSITIVE_INFINITY)) throw new ContractError("validateShape: an integer number shape has an empty integer range", {
2930
+ code: "range",
2931
+ context: {
2932
+ path: frame.path,
2933
+ shape: "integer"
2934
+ }
2935
+ });
2936
+ }
2937
+ break;
2938
+ case "boolean":
2939
+ case "null":
2940
+ case "json":
2941
+ case "raw": break;
2942
+ case "literal":
2943
+ if (current.values.length === 0) throw new ContractError("validateShape: a literal shape needs at least one value", {
2944
+ code: "empty",
2945
+ context: {
2946
+ path: frame.path,
2947
+ shape: "literal"
2948
+ }
2949
+ });
2950
+ for (const value of current.values) if (typeof value === "number" && !Number.isFinite(value)) throw new ContractError("validateShape: a literal shape may not contain non-finite number values", {
2951
+ code: "literal",
2952
+ context: {
2953
+ path: frame.path,
2954
+ shape: "literal",
2955
+ received: String(value)
2956
+ }
2957
+ });
2958
+ break;
2959
+ case "array":
2960
+ if (current.min !== void 0 && current.max !== void 0 && current.min > current.max) throw new ContractError("validateShape: an array shape has min greater than max", {
2961
+ code: "range",
2962
+ context: {
2963
+ path: frame.path,
2964
+ shape: "array"
2965
+ }
2966
+ });
2967
+ stack.push({
2968
+ operation: "enter",
2969
+ shape: current.items,
2970
+ path: [...frame.path, "items"],
2971
+ optional: false,
2972
+ depth: frame.depth + 1
2973
+ });
2974
+ break;
2975
+ case "object": {
2976
+ const extra = current.additionalProperties;
2977
+ if (extra !== void 0 && extra !== true && extra !== false) stack.push({
2978
+ operation: "enter",
2979
+ shape: extra,
2980
+ path: [...frame.path, "additionalProperties"],
2981
+ optional: false,
2982
+ depth: frame.depth + 1
2983
+ });
2984
+ const keys = Object.keys(current.properties);
2985
+ for (let index = keys.length - 1; index >= 0; index -= 1) {
2986
+ const key = keys[index];
2987
+ if (key === void 0) continue;
2988
+ const child = current.properties[key];
2989
+ if (child === void 0) continue;
2990
+ stack.push({
2991
+ operation: "enter",
2992
+ shape: child,
2993
+ path: [
2994
+ ...frame.path,
2995
+ "properties",
2996
+ key
2997
+ ],
2998
+ optional: true,
2999
+ depth: frame.depth + 1
3000
+ });
3001
+ }
3002
+ break;
2119
3003
  }
2120
- const extra = shape.additionalProperties;
2121
- if (extra !== void 0 && extra !== true && extra !== false) validateShape(extra);
2122
- return;
3004
+ case "union":
3005
+ if (current.variants.length === 0) throw new ContractError("validateShape: a union shape needs at least one variant", {
3006
+ code: "empty",
3007
+ context: {
3008
+ path: frame.path,
3009
+ shape: "union"
3010
+ }
3011
+ });
3012
+ for (let index = current.variants.length - 1; index >= 0; index -= 1) {
3013
+ const variant = current.variants[index];
3014
+ if (variant === void 0) continue;
3015
+ stack.push({
3016
+ operation: "enter",
3017
+ shape: variant,
3018
+ path: [
3019
+ ...frame.path,
3020
+ "variants",
3021
+ String(index)
3022
+ ],
3023
+ optional: false,
3024
+ depth: frame.depth + 1
3025
+ });
3026
+ }
3027
+ break;
3028
+ case "optional":
3029
+ if (!frame.optional) throw new ContractError("validateShape: an optional shape may only appear as a direct object-property value", {
3030
+ code: "placement",
3031
+ context: {
3032
+ path: frame.path,
3033
+ shape: "optional"
3034
+ }
3035
+ });
3036
+ stack.push({
3037
+ operation: "enter",
3038
+ shape: current.inner,
3039
+ path: [...frame.path, "inner"],
3040
+ optional: false,
3041
+ depth: frame.depth + 1
3042
+ });
3043
+ break;
3044
+ case "nullable":
3045
+ stack.push({
3046
+ operation: "enter",
3047
+ shape: current.inner,
3048
+ path: [...frame.path, "inner"],
3049
+ optional: false,
3050
+ depth: frame.depth + 1
3051
+ });
3052
+ break;
2123
3053
  }
2124
- case "union":
2125
- if (shape.variants.length === 0) throw new Error("validateShape: a union shape needs at least one variant");
2126
- for (const variant of shape.variants) validateShape(variant);
2127
- return;
2128
- case "optional": throw new Error("validateShape: an optional shape may only appear as a direct object-property value");
2129
- case "nullable":
2130
- validateShape(shape.inner);
2131
- return;
2132
3054
  }
2133
3055
  }
2134
3056
  /**
@@ -2137,7 +3059,10 @@ function validateShape(shape) {
2137
3059
  * @remarks
2138
3060
  * Object shapes emit `additionalProperties: false` (unless opened) and list only
2139
3061
  * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
2140
- * 'null' }`. Emission only — it never inspects a runtime value.
3062
+ * 'null' }`. The result is an owned deeply frozen graph; raw schemas are cloned
3063
+ * rather than retained by reference. Emission only — it never inspects a
3064
+ * runtime value. {@link validateShapeDepth} iteratively rejects excessive
3065
+ * nesting or cycles before recursive emission begins.
2141
3066
  *
2142
3067
  * @param shape - The shape to compile
2143
3068
  * @returns The emitted JSON Schema
@@ -2148,114 +3073,122 @@ function validateShape(shape) {
2148
3073
  * ```
2149
3074
  */
2150
3075
  function compileSchema(shape) {
2151
- switch (shape.type) {
2152
- case "string": return {
3076
+ const owned = ownShape(shape);
3077
+ validateShapeDepth(owned);
3078
+ switch (owned.type) {
3079
+ case "string": return Object.freeze({
2153
3080
  type: "string",
2154
- ...shape.min !== void 0 ? { minLength: shape.min } : {},
2155
- ...shape.max !== void 0 ? { maxLength: shape.max } : {},
2156
- ...shape.pattern !== void 0 ? { pattern: shape.pattern.source } : {},
2157
- ...shape.description !== void 0 ? { description: shape.description } : {}
2158
- };
2159
- case "number": return {
2160
- type: shape.integer === true ? "integer" : "number",
2161
- ...shape.min !== void 0 ? { minimum: shape.min } : {},
2162
- ...shape.max !== void 0 ? { maximum: shape.max } : {},
2163
- ...shape.description !== void 0 ? { description: shape.description } : {}
2164
- };
2165
- case "boolean": return {
3081
+ ...owned.min !== void 0 ? { minLength: owned.min } : {},
3082
+ ...owned.max !== void 0 ? { maxLength: owned.max } : {},
3083
+ ...owned.pattern !== void 0 ? { pattern: owned.pattern.source } : {},
3084
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3085
+ });
3086
+ case "number": return Object.freeze({
3087
+ type: owned.integer === true ? "integer" : "number",
3088
+ ...owned.min !== void 0 ? { minimum: owned.min } : {},
3089
+ ...owned.max !== void 0 ? { maximum: owned.max } : {},
3090
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3091
+ });
3092
+ case "boolean": return Object.freeze({
2166
3093
  type: "boolean",
2167
- ...shape.description !== void 0 ? { description: shape.description } : {}
2168
- };
2169
- case "null": return {
3094
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3095
+ });
3096
+ case "null": return Object.freeze({
2170
3097
  type: "null",
2171
- ...shape.description !== void 0 ? { description: shape.description } : {}
2172
- };
2173
- case "json": return { ...shape.description !== void 0 ? { description: shape.description } : {} };
2174
- case "literal": return {
2175
- enum: [...shape.values],
2176
- ...shape.description !== void 0 ? { description: shape.description } : {}
2177
- };
2178
- case "array": return {
3098
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3099
+ });
3100
+ case "json": return Object.freeze({ ...owned.description !== void 0 ? { description: owned.description } : {} });
3101
+ case "literal": return Object.freeze({
3102
+ enum: Object.freeze([...owned.values]),
3103
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3104
+ });
3105
+ case "array": return Object.freeze({
2179
3106
  type: "array",
2180
- items: compileSchema(shape.items),
2181
- ...shape.min !== void 0 ? { minItems: shape.min } : {},
2182
- ...shape.max !== void 0 ? { maxItems: shape.max } : {},
2183
- ...shape.description !== void 0 ? { description: shape.description } : {}
2184
- };
3107
+ items: compileSchema(owned.items),
3108
+ ...owned.min !== void 0 ? { minItems: owned.min } : {},
3109
+ ...owned.max !== void 0 ? { maxItems: owned.max } : {},
3110
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3111
+ });
2185
3112
  case "object": {
2186
- const properties = {};
3113
+ const properties = Object.create(null);
2187
3114
  const required = [];
2188
- for (const key of Object.keys(shape.properties)) {
2189
- const child = shape.properties[key];
3115
+ for (const key of Object.keys(owned.properties)) {
3116
+ const child = owned.properties[key];
2190
3117
  if (child === void 0) continue;
2191
3118
  properties[key] = compileSchema(child);
2192
3119
  if (child.type !== "optional") required.push(key);
2193
3120
  }
2194
- const extra = shape.additionalProperties;
3121
+ const extra = owned.additionalProperties;
2195
3122
  const additionalProperties = extra === true ? true : extra !== void 0 && extra !== false ? compileSchema(extra) : false;
2196
- return {
3123
+ return Object.freeze({
2197
3124
  type: "object",
2198
- ...Object.keys(properties).length > 0 ? { properties } : {},
2199
- ...required.length > 0 ? { required } : {},
3125
+ ...Object.keys(properties).length > 0 ? { properties: Object.freeze(properties) } : {},
3126
+ ...required.length > 0 ? { required: Object.freeze(required) } : {},
2200
3127
  additionalProperties,
2201
- ...shape.description !== void 0 ? { description: shape.description } : {}
2202
- };
3128
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3129
+ });
2203
3130
  }
2204
- case "union": return {
2205
- ...shape.mode === "oneOf" ? { oneOf: shape.variants.map((variant) => compileSchema(variant)) } : { anyOf: shape.variants.map((variant) => compileSchema(variant)) },
2206
- ...shape.description !== void 0 ? { description: shape.description } : {}
2207
- };
2208
- case "optional": return compileSchema(shape.inner);
2209
- case "nullable": return { anyOf: [compileSchema(shape.inner), { type: "null" }] };
2210
- case "raw": return shape.schema;
3131
+ case "union": return Object.freeze({
3132
+ ...owned.mode === "oneOf" ? { oneOf: Object.freeze(owned.variants.map((variant) => compileSchema(variant))) } : { anyOf: Object.freeze(owned.variants.map((variant) => compileSchema(variant))) },
3133
+ ...owned.description !== void 0 ? { description: owned.description } : {}
3134
+ });
3135
+ case "optional": return compileSchema(owned.inner);
3136
+ case "nullable": return Object.freeze({ anyOf: Object.freeze([compileSchema(owned.inner), Object.freeze({ type: "null" })]) });
3137
+ case "raw": return cloneSchema(owned.schema);
2211
3138
  }
2212
3139
  }
2213
3140
  function compileGuard(shape) {
2214
- switch (shape.type) {
3141
+ const owned = ownShape(shape);
3142
+ validateShapeDepth(owned);
3143
+ switch (owned.type) {
2215
3144
  case "string": return stringOf({
2216
- min: shape.min,
2217
- max: shape.max,
2218
- pattern: shape.pattern
3145
+ ...owned.min === void 0 ? {} : { min: owned.min },
3146
+ ...owned.max === void 0 ? {} : { max: owned.max },
3147
+ ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
2219
3148
  });
2220
3149
  case "number": {
2221
- const base = shape.integer === true ? isInteger : isFiniteNumber;
2222
- if (shape.min === void 0 && shape.max === void 0) return base;
2223
- return shape.integer === true ? intersectionOf(isInteger, boundsOf(shape.min, shape.max)) : boundsOf(shape.min, shape.max);
3150
+ const base = owned.integer === true ? isInteger : isFiniteNumber;
3151
+ if (owned.min === void 0 && owned.max === void 0) return base;
3152
+ return owned.integer === true ? intersectionOf(isInteger, boundsOf(owned.min, owned.max)) : boundsOf(owned.min, owned.max);
2224
3153
  }
2225
3154
  case "boolean": return isBoolean;
2226
3155
  case "null": return isNull;
2227
3156
  case "json": return isJSONValue;
2228
- case "literal": return literalOf(...shape.values);
3157
+ case "literal": return literalOf(owned.values);
2229
3158
  case "array": {
2230
- const base = arrayOf(compileGuard(shape.items));
2231
- if (shape.min === void 0 && shape.max === void 0) return base;
2232
- const withinLength = boundsOf(shape.min, shape.max);
3159
+ const base = arrayOf(compileGuard(owned.items));
3160
+ if (owned.min === void 0 && owned.max === void 0) return base;
3161
+ const withinLength = boundsOf(owned.min, owned.max);
2233
3162
  return whereOf(base, (value) => withinLength(value.length));
2234
3163
  }
2235
3164
  case "object": {
2236
3165
  const map = Object.create(null);
2237
3166
  const optionalKeys = [];
2238
- for (const key of Object.keys(shape.properties)) {
2239
- const child = shape.properties[key];
3167
+ for (const key of Object.keys(owned.properties)) {
3168
+ const child = owned.properties[key];
2240
3169
  if (child === void 0) continue;
2241
3170
  if (child.type === "optional") {
2242
3171
  map[key] = compileGuard(child.inner);
2243
3172
  optionalKeys.push(key);
2244
3173
  } else map[key] = compileGuard(child);
2245
3174
  }
2246
- const extra = shape.additionalProperties;
2247
- if (extra === void 0 || extra === false) return optionalKeys.length > 0 ? recordOf(map, optionalKeys) : recordOf(map);
2248
- const additional = extra === true ? void 0 : compileGuard(extra);
3175
+ const extra = owned.additionalProperties;
3176
+ const closed = extra === void 0 || extra === false;
3177
+ const additional = closed || extra === true ? void 0 : compileGuard(extra);
2249
3178
  const required = Object.keys(map).filter((key) => !optionalKeys.includes(key));
2250
3179
  return (value) => {
2251
3180
  if (!isRecord(value)) return false;
2252
- for (const key of required) if (!Object.hasOwn(value, key)) return false;
3181
+ const keys = enumerableKeys(value);
3182
+ if (keys === void 0) return false;
3183
+ const present = new Set(keys);
3184
+ for (const key of required) if (!present.has(key)) return false;
2253
3185
  const outcome = attempt(() => {
2254
- for (const key of Object.keys(value)) {
3186
+ for (const key of keys) {
2255
3187
  const guard = Object.hasOwn(map, key) ? map[key] : void 0;
2256
3188
  if (guard !== void 0) {
2257
3189
  if (!guard(value[key])) return false;
2258
- } else if (additional !== void 0 && !additional(value[key])) return false;
3190
+ } else if (closed) return false;
3191
+ else if (additional !== void 0 && !additional(value[key])) return false;
2259
3192
  }
2260
3193
  return true;
2261
3194
  });
@@ -2263,23 +3196,25 @@ function compileGuard(shape) {
2263
3196
  };
2264
3197
  }
2265
3198
  case "union": {
2266
- const guards = shape.variants.map((variant) => compileGuard(variant));
2267
- if (shape.mode === "oneOf") return (value) => guards.filter((guard) => guard(value)).length === 1;
3199
+ const guards = owned.variants.map((variant) => compileGuard(variant));
3200
+ if (owned.mode === "oneOf") return (value) => guards.filter((guard) => guard(value)).length === 1;
2268
3201
  return unionOf(...guards);
2269
3202
  }
2270
- case "optional": return orOf(isUndefined, compileGuard(shape.inner));
2271
- case "nullable": return nullableOf(compileGuard(shape.inner));
2272
- case "raw": return (_value) => true;
3203
+ case "optional": return orOf(isUndefined, compileGuard(owned.inner));
3204
+ case "nullable": return nullableOf(compileGuard(owned.inner));
3205
+ case "raw": return (value) => value !== void 0;
2273
3206
  }
2274
3207
  }
2275
3208
  function compileParser(shape) {
2276
- switch (shape.type) {
3209
+ const owned = ownShape(shape);
3210
+ validateShapeDepth(owned);
3211
+ switch (owned.type) {
2277
3212
  case "string": {
2278
- if (shape.min === void 0 && shape.max === void 0 && shape.pattern === void 0) return parseString;
3213
+ if (owned.min === void 0 && owned.max === void 0 && owned.pattern === void 0) return parseString;
2279
3214
  const guard = stringOf({
2280
- min: shape.min,
2281
- max: shape.max,
2282
- pattern: shape.pattern
3215
+ ...owned.min === void 0 ? {} : { min: owned.min },
3216
+ ...owned.max === void 0 ? {} : { max: owned.max },
3217
+ ...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
2283
3218
  });
2284
3219
  return (value) => {
2285
3220
  const parsed = parseString(value);
@@ -2287,9 +3222,9 @@ function compileParser(shape) {
2287
3222
  };
2288
3223
  }
2289
3224
  case "number": {
2290
- const base = shape.integer === true ? parseInteger : parseNumber;
2291
- if (shape.min === void 0 && shape.max === void 0) return base;
2292
- const within = boundsOf(shape.min, shape.max);
3225
+ const base = owned.integer === true ? parseInteger : parseNumber;
3226
+ if (owned.min === void 0 && owned.max === void 0) return base;
3227
+ const within = boundsOf(owned.min, owned.max);
2293
3228
  return (value) => {
2294
3229
  const parsed = base(value);
2295
3230
  return parsed !== void 0 && within(parsed) ? parsed : void 0;
@@ -2299,19 +3234,19 @@ function compileParser(shape) {
2299
3234
  case "null": return (value) => value === null ? null : void 0;
2300
3235
  case "json": return (value) => isJSONValue(value) ? value : void 0;
2301
3236
  case "literal": {
2302
- const allowed = new Set(shape.values);
3237
+ const allowed = literalOf(owned.values);
2303
3238
  return (value) => {
2304
- if (allowed.has(value)) return value;
3239
+ if (allowed(value)) return value;
2305
3240
  if (isString(value)) {
2306
3241
  const trimmed = value.trim();
2307
- if (allowed.has(trimmed)) return trimmed;
3242
+ if (allowed(trimmed)) return trimmed;
2308
3243
  }
2309
3244
  };
2310
3245
  }
2311
3246
  case "array": {
2312
- const item = compileParser(shape.items);
2313
- const unbounded = shape.min === void 0 && shape.max === void 0;
2314
- const withinLength = boundsOf(shape.min, shape.max);
3247
+ const item = compileParser(owned.items);
3248
+ const unbounded = owned.min === void 0 && owned.max === void 0;
3249
+ const withinLength = boundsOf(owned.min, owned.max);
2315
3250
  return (value) => {
2316
3251
  if (!isArray(value)) return void 0;
2317
3252
  const result = [];
@@ -2325,8 +3260,8 @@ function compileParser(shape) {
2325
3260
  }
2326
3261
  case "object": {
2327
3262
  const entries = [];
2328
- for (const key of Object.keys(shape.properties)) {
2329
- const child = shape.properties[key];
3263
+ for (const key of Object.keys(owned.properties)) {
3264
+ const child = owned.properties[key];
2330
3265
  if (child === void 0) continue;
2331
3266
  const optional = child.type === "optional";
2332
3267
  entries.push({
@@ -2336,15 +3271,22 @@ function compileParser(shape) {
2336
3271
  });
2337
3272
  }
2338
3273
  const known = new Set(entries.map((entry) => entry.key));
2339
- const extra = shape.additionalProperties;
3274
+ const extra = owned.additionalProperties;
2340
3275
  const additional = extra === void 0 || extra === false || extra === true ? void 0 : compileParser(extra);
2341
3276
  const open = extra === true || additional !== void 0;
2342
3277
  return (value) => {
2343
3278
  const record = parseRecord(value);
2344
3279
  if (record === void 0) return void 0;
3280
+ const keys = enumerableKeys(record);
3281
+ if (keys === void 0) return void 0;
3282
+ const present = new Set(keys);
2345
3283
  const outcome = attempt(() => {
2346
3284
  const result = Object.create(null);
2347
3285
  for (const entry of entries) {
3286
+ if (!present.has(entry.key)) {
3287
+ if (entry.optional) continue;
3288
+ return;
3289
+ }
2348
3290
  const raw = record[entry.key];
2349
3291
  if (raw === void 0) {
2350
3292
  if (entry.optional) continue;
@@ -2354,7 +3296,7 @@ function compileParser(shape) {
2354
3296
  if (parsed === void 0) return void 0;
2355
3297
  result[entry.key] = parsed;
2356
3298
  }
2357
- if (open) for (const key of Object.keys(record)) {
3299
+ if (open) for (const key of keys) {
2358
3300
  if (known.has(key)) continue;
2359
3301
  if (additional === void 0) result[key] = record[key];
2360
3302
  else {
@@ -2369,11 +3311,11 @@ function compileParser(shape) {
2369
3311
  };
2370
3312
  }
2371
3313
  case "union": {
2372
- const variants = shape.variants.map((variant) => ({
3314
+ const variants = owned.variants.map((variant) => ({
2373
3315
  parse: compileParser(variant),
2374
3316
  guard: compileGuard(variant)
2375
3317
  }));
2376
- if (shape.mode === "oneOf") return (value) => {
3318
+ if (owned.mode === "oneOf") return (value) => {
2377
3319
  const matches = variants.filter((variant) => variant.guard(value));
2378
3320
  const [only] = matches;
2379
3321
  return matches.length === 1 && only !== void 0 ? only.parse(value) : void 0;
@@ -2387,89 +3329,143 @@ function compileParser(shape) {
2387
3329
  };
2388
3330
  }
2389
3331
  case "optional": {
2390
- const inner = compileParser(shape.inner);
3332
+ const inner = compileParser(owned.inner);
2391
3333
  return (value) => value === void 0 ? void 0 : inner(value);
2392
3334
  }
2393
3335
  case "nullable": {
2394
- const inner = compileParser(shape.inner);
3336
+ const inner = compileParser(owned.inner);
2395
3337
  return (value) => value === null ? null : inner(value);
2396
3338
  }
2397
3339
  case "raw": return (value) => value;
2398
3340
  }
2399
3341
  }
2400
3342
  function compileGenerator(shape, random = seededRandom(Date.now())) {
2401
- switch (shape.type) {
3343
+ const owned = ownShape(shape);
3344
+ validateShapeDepth(owned);
3345
+ switch (owned.type) {
2402
3346
  case "string": {
2403
- const min = shape.min ?? 0;
2404
- const max = shape.max ?? Math.max(min, 12);
3347
+ const min = owned.min ?? 0;
3348
+ const max = owned.max ?? Math.max(min, 12);
2405
3349
  const length = Math.max(min, Math.min(max, 8));
2406
3350
  const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
2407
3351
  let value = "";
2408
- for (let index = 0; index < length; index += 1) value += alphabet[Math.floor(random() * 36)];
2409
- if (shape.pattern !== void 0 && !shape.pattern.test(value)) throw new Error("compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way");
3352
+ for (let index = 0; index < length; index += 1) value += alphabet[Math.floor(drawRandom(random, "string") * 36)];
3353
+ if (owned.pattern !== void 0 && !matchOf(owned.pattern)(value)) throw new ContractError("compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way", {
3354
+ code: "generate",
3355
+ context: {
3356
+ shape: "string",
3357
+ limit: owned.pattern.source
3358
+ }
3359
+ });
2410
3360
  return value;
2411
3361
  }
2412
3362
  case "number": {
2413
- const min = shape.min ?? 0;
2414
- const max = shape.max ?? 100;
2415
- if (shape.integer === true) {
2416
- const lo = Math.ceil(min);
2417
- const hi = Math.floor(max);
2418
- return Math.floor(random() * (hi - lo + 1)) + lo;
3363
+ const sample = drawRandom(random, owned.integer === true ? "integer" : "number");
3364
+ if (owned.integer === true) {
3365
+ const lo = Math.ceil(owned.min ?? (owned.max === void 0 ? -100 : owned.max - 100));
3366
+ const hi = Math.floor(owned.max ?? (owned.min === void 0 ? 100 : owned.min + 100));
3367
+ return lo === hi ? lo : Math.floor(lo * (1 - sample) + hi * sample);
2419
3368
  }
2420
- return random() * (max - min) + min;
3369
+ const lo = owned.min ?? (owned.max === void 0 ? -100 : owned.max - 100);
3370
+ const hi = owned.max ?? (owned.min === void 0 ? 100 : owned.min + 100);
3371
+ return lo === hi ? lo : lo * (1 - sample) + hi * sample;
2421
3372
  }
2422
- case "boolean": return random() >= .5;
3373
+ case "boolean": return drawRandom(random, "boolean") >= .5;
2423
3374
  case "null": return null;
2424
3375
  case "json": {
2425
- const pick = Math.floor(random() * 5);
3376
+ const pick = Math.floor(drawRandom(random, "json") * 5);
2426
3377
  if (pick === 0) return null;
2427
- if (pick === 1) return random() >= .5;
2428
- if (pick === 2) return Math.floor(random() * 1e3);
3378
+ if (pick === 1) return drawRandom(random, "json") >= .5;
3379
+ if (pick === 2) return Math.floor(drawRandom(random, "json") * 1e3);
2429
3380
  if (pick === 3) {
2430
3381
  const alphabet = "abcdefghijklmnopqrstuvwxyz";
2431
3382
  let value = "";
2432
- for (let index = 0; index < 6; index += 1) value += alphabet[Math.floor(random() * 26)];
3383
+ for (let index = 0; index < 6; index += 1) value += alphabet[Math.floor(drawRandom(random, "json") * 26)];
2433
3384
  return value;
2434
3385
  }
2435
- return { value: Math.floor(random() * 1e3) };
3386
+ return { value: Math.floor(drawRandom(random, "json") * 1e3) };
2436
3387
  }
2437
3388
  case "literal":
2438
- if (shape.values.length === 0) throw new Error("compileGenerator: a literal shape needs at least one value");
2439
- return shape.values[Math.floor(random() * shape.values.length)];
3389
+ if (owned.values.length === 0) throw new ContractError("compileGenerator: a literal shape needs at least one value", {
3390
+ code: "generate",
3391
+ context: {
3392
+ shape: "literal",
3393
+ limit: 1
3394
+ }
3395
+ });
3396
+ return owned.values[Math.floor(drawRandom(random, "literal") * owned.values.length)];
2440
3397
  case "array": {
2441
- const lo = shape.min ?? Math.min(1, shape.max ?? 1);
2442
- const hi = shape.max ?? Math.max(lo, 3);
2443
- const length = Math.floor(random() * (hi - lo + 1)) + lo;
3398
+ const lo = owned.min ?? Math.min(1, owned.max ?? 1);
3399
+ const hi = owned.max ?? Math.max(lo, 3);
3400
+ const length = Math.floor(drawRandom(random, "array") * (hi - lo + 1)) + lo;
2444
3401
  const result = [];
2445
- for (let index = 0; index < length; index += 1) result.push(compileGenerator(shape.items, random));
3402
+ for (let index = 0; index < length; index += 1) result.push(compileGenerator(owned.items, random));
2446
3403
  return result;
2447
3404
  }
2448
3405
  case "object": {
2449
3406
  const result = {};
2450
- for (const key of Object.keys(shape.properties)) {
2451
- const child = shape.properties[key];
3407
+ for (const key of Object.keys(owned.properties)) {
3408
+ const child = owned.properties[key];
2452
3409
  if (child === void 0) continue;
2453
- if (child.type === "optional" && random() < .3) continue;
2454
- result[key] = compileGenerator(child, random);
3410
+ if (child.type === "optional" && drawRandom(random, "object") < .3) continue;
3411
+ Object.defineProperty(result, key, {
3412
+ value: compileGenerator(child, random),
3413
+ enumerable: true,
3414
+ configurable: true,
3415
+ writable: true
3416
+ });
2455
3417
  }
2456
- const extra = shape.additionalProperties;
3418
+ const extra = owned.additionalProperties;
2457
3419
  if (extra !== void 0 && extra !== true && extra !== false) {
2458
- const count = 1 + Math.floor(random() * 2);
3420
+ const count = 1 + Math.floor(drawRandom(random, "object") * 2);
2459
3421
  for (let index = 0; index < count; index += 1) {
2460
3422
  const key = `key${index}`;
2461
3423
  if (Object.hasOwn(result, key)) continue;
2462
- result[key] = compileGenerator(extra, random);
3424
+ Object.defineProperty(result, key, {
3425
+ value: compileGenerator(extra, random),
3426
+ enumerable: true,
3427
+ configurable: true,
3428
+ writable: true
3429
+ });
2463
3430
  }
2464
3431
  }
2465
3432
  return result;
2466
3433
  }
2467
- case "union":
2468
- if (shape.variants.length === 0) throw new Error("compileGenerator: a union shape needs at least one variant");
2469
- return compileGenerator(shape.variants[Math.floor(random() * shape.variants.length)], random);
2470
- case "optional": return compileGenerator(shape.inner, random);
2471
- case "nullable": return random() < .2 ? null : compileGenerator(shape.inner, random);
2472
- case "raw": throw new Error("compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way");
3434
+ case "union": {
3435
+ if (owned.variants.length === 0) throw new ContractError("compileGenerator: a union shape needs at least one variant", {
3436
+ code: "generate",
3437
+ context: {
3438
+ shape: "union",
3439
+ limit: 1
3440
+ }
3441
+ });
3442
+ const guard = compileGuard(owned);
3443
+ const attempts = Math.max(32, owned.variants.length);
3444
+ const start = Math.floor(drawRandom(random, "union") * owned.variants.length);
3445
+ for (let attemptIndex = 0; attemptIndex < attempts; attemptIndex += 1) {
3446
+ const variant = owned.variants[(start + attemptIndex) % owned.variants.length];
3447
+ if (variant === void 0) continue;
3448
+ const outcome = attempt(() => compileGenerator(variant, random));
3449
+ if (!outcome.success && isContractError(outcome.error) && outcome.error.code === "random") throw outcome.error;
3450
+ if (outcome.success && guard(outcome.value)) return outcome.value;
3451
+ }
3452
+ throw new ContractError("compileGenerator: no union candidate satisfied the compiled guard", {
3453
+ code: "generate",
3454
+ context: {
3455
+ shape: "union",
3456
+ limit: attempts
3457
+ }
3458
+ });
3459
+ }
3460
+ case "optional": return compileGenerator(owned.inner, random);
3461
+ case "nullable": return drawRandom(random, "nullable") < .2 ? null : compileGenerator(owned.inner, random);
3462
+ case "raw": throw new ContractError("compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way", {
3463
+ code: "generate",
3464
+ context: {
3465
+ shape: "raw",
3466
+ limit: "explicit value source"
3467
+ }
3468
+ });
2473
3469
  }
2474
3470
  }
2475
3471
  /**
@@ -2496,7 +3492,8 @@ function compileGenerator(shape, random = seededRandom(Date.now())) {
2496
3492
  * open object with a constraining `additionalProperties` shape recurses extras
2497
3493
  * against it instead. A hostile getter or throwing `Proxy` trap is contained
2498
3494
  * via {@link attempt} and surfaces as a single top-level type fault, never a
2499
- * throw (AGENTS §14).
3495
+ * throw (AGENTS §14). {@link validateShapeDepth} iteratively rejects excessive
3496
+ * shape nesting or cycles before recursive reporting begins.
2500
3497
  *
2501
3498
  * @param shape - The shape to report against
2502
3499
  * @param value - The value to check
@@ -2512,7 +3509,9 @@ function compileGenerator(shape, random = seededRandom(Date.now())) {
2512
3509
  * ```
2513
3510
  */
2514
3511
  function compileReporter(shape, value, path = []) {
2515
- switch (shape.type) {
3512
+ const owned = ownShape(shape);
3513
+ validateShapeDepth(owned);
3514
+ switch (owned.type) {
2516
3515
  case "string": {
2517
3516
  const parsed = parseString(value);
2518
3517
  if (parsed === void 0) return [{
@@ -2522,34 +3521,34 @@ function compileReporter(shape, value, path = []) {
2522
3521
  received: preview(value)
2523
3522
  }];
2524
3523
  const faults = [];
2525
- if (shape.min !== void 0 && parsed.length < shape.min) faults.push({
3524
+ if (owned.min !== void 0 && parsed.length < owned.min) faults.push({
2526
3525
  reason: "constraint",
2527
3526
  path,
2528
3527
  expected: "string",
2529
3528
  constraint: "min",
2530
- limit: shape.min,
3529
+ limit: owned.min,
2531
3530
  received: preview(parsed)
2532
3531
  });
2533
- if (shape.max !== void 0 && parsed.length > shape.max) faults.push({
3532
+ if (owned.max !== void 0 && parsed.length > owned.max) faults.push({
2534
3533
  reason: "constraint",
2535
3534
  path,
2536
3535
  expected: "string",
2537
3536
  constraint: "max",
2538
- limit: shape.max,
3537
+ limit: owned.max,
2539
3538
  received: preview(parsed)
2540
3539
  });
2541
- if (shape.pattern !== void 0 && !shape.pattern.test(parsed)) faults.push({
3540
+ if (owned.pattern !== void 0 && !matchOf(owned.pattern)(parsed)) faults.push({
2542
3541
  reason: "constraint",
2543
3542
  path,
2544
3543
  expected: "string",
2545
3544
  constraint: "pattern",
2546
- limit: shape.pattern.source,
3545
+ limit: owned.pattern.source,
2547
3546
  received: preview(parsed)
2548
3547
  });
2549
3548
  return faults;
2550
3549
  }
2551
3550
  case "number": {
2552
- const kind = shape.integer === true ? "integer" : "number";
3551
+ const kind = owned.integer === true ? "integer" : "number";
2553
3552
  const parsed = parseNumber(value);
2554
3553
  if (parsed === void 0) return [{
2555
3554
  reason: "type",
@@ -2558,27 +3557,27 @@ function compileReporter(shape, value, path = []) {
2558
3557
  received: preview(value)
2559
3558
  }];
2560
3559
  const faults = [];
2561
- if (shape.integer === true && !Number.isInteger(parsed)) faults.push({
3560
+ if (owned.integer === true && !Number.isInteger(parsed)) faults.push({
2562
3561
  reason: "constraint",
2563
3562
  path,
2564
3563
  expected: kind,
2565
3564
  constraint: "integer",
2566
3565
  received: preview(parsed)
2567
3566
  });
2568
- if (shape.min !== void 0 && parsed < shape.min) faults.push({
3567
+ if (owned.min !== void 0 && parsed < owned.min) faults.push({
2569
3568
  reason: "constraint",
2570
3569
  path,
2571
3570
  expected: kind,
2572
3571
  constraint: "min",
2573
- limit: shape.min,
3572
+ limit: owned.min,
2574
3573
  received: preview(parsed)
2575
3574
  });
2576
- if (shape.max !== void 0 && parsed > shape.max) faults.push({
3575
+ if (owned.max !== void 0 && parsed > owned.max) faults.push({
2577
3576
  reason: "constraint",
2578
3577
  path,
2579
3578
  expected: kind,
2580
3579
  constraint: "max",
2581
- limit: shape.max,
3580
+ limit: owned.max,
2582
3581
  received: preview(parsed)
2583
3582
  });
2584
3583
  return faults;
@@ -2602,8 +3601,8 @@ function compileReporter(shape, value, path = []) {
2602
3601
  received: preview(value)
2603
3602
  }];
2604
3603
  case "literal": {
2605
- const allowed = new Set(shape.values);
2606
- return allowed.has(value) || isString(value) && allowed.has(value.trim()) ? [] : [{
3604
+ const allowed = literalOf(owned.values);
3605
+ return allowed(value) || isString(value) && allowed(value.trim()) ? [] : [{
2607
3606
  reason: "type",
2608
3607
  path,
2609
3608
  expected: "literal",
@@ -2621,7 +3620,7 @@ function compileReporter(shape, value, path = []) {
2621
3620
  if (!attempt(() => {
2622
3621
  for (let index = 0; index < value.length; index += 1) {
2623
3622
  if (faults.length >= 64) return;
2624
- faults.push(...compileReporter(shape.items, value[index], [...path, String(index)]));
3623
+ faults.push(...compileReporter(owned.items, value[index], [...path, String(index)]));
2625
3624
  }
2626
3625
  }).success) return [{
2627
3626
  reason: "type",
@@ -2629,20 +3628,20 @@ function compileReporter(shape, value, path = []) {
2629
3628
  expected: "array",
2630
3629
  received: preview(value)
2631
3630
  }];
2632
- if (shape.min !== void 0 && value.length < shape.min) faults.push({
3631
+ if (owned.min !== void 0 && value.length < owned.min) faults.push({
2633
3632
  reason: "constraint",
2634
3633
  path,
2635
3634
  expected: "array",
2636
3635
  constraint: "min",
2637
- limit: shape.min,
3636
+ limit: owned.min,
2638
3637
  received: String(value.length)
2639
3638
  });
2640
- if (shape.max !== void 0 && value.length > shape.max) faults.push({
3639
+ if (owned.max !== void 0 && value.length > owned.max) faults.push({
2641
3640
  reason: "constraint",
2642
3641
  path,
2643
3642
  expected: "array",
2644
3643
  constraint: "max",
2645
- limit: shape.max,
3644
+ limit: owned.max,
2646
3645
  received: String(value.length)
2647
3646
  });
2648
3647
  return faults.length > 64 ? faults.slice(0, 64) : faults;
@@ -2655,16 +3654,32 @@ function compileReporter(shape, value, path = []) {
2655
3654
  received: preview(value)
2656
3655
  }];
2657
3656
  const record = value;
3657
+ const keys = enumerableKeys(record);
3658
+ if (keys === void 0) return [{
3659
+ reason: "type",
3660
+ path,
3661
+ expected: "object",
3662
+ received: preview(value)
3663
+ }];
3664
+ const present = new Set(keys);
2658
3665
  const faults = [];
2659
3666
  const known = /* @__PURE__ */ new Set();
2660
3667
  if (!attempt(() => {
2661
- for (const key of Object.keys(shape.properties)) {
3668
+ for (const key of Object.keys(owned.properties)) {
2662
3669
  if (faults.length >= 64) return;
2663
- const child = shape.properties[key];
3670
+ const child = owned.properties[key];
2664
3671
  if (child === void 0) continue;
2665
3672
  known.add(key);
2666
3673
  const optional = child.type === "optional";
2667
3674
  const inner = optional ? child.inner : child;
3675
+ if (!present.has(key)) {
3676
+ if (!optional) faults.push({
3677
+ reason: "missing",
3678
+ path: [...path, key],
3679
+ expected: shapeToKind(inner)
3680
+ });
3681
+ continue;
3682
+ }
2668
3683
  const raw = record[key];
2669
3684
  if (raw === void 0) {
2670
3685
  if (!optional) faults.push({
@@ -2676,8 +3691,8 @@ function compileReporter(shape, value, path = []) {
2676
3691
  }
2677
3692
  faults.push(...compileReporter(inner, raw, [...path, key]));
2678
3693
  }
2679
- const extra = shape.additionalProperties;
2680
- if (extra !== void 0 && extra !== true && extra !== false) for (const key of Object.keys(record)) {
3694
+ const extra = owned.additionalProperties;
3695
+ if (extra !== void 0 && extra !== true && extra !== false) for (const key of keys) {
2681
3696
  if (faults.length >= 64) return;
2682
3697
  if (known.has(key)) continue;
2683
3698
  faults.push(...compileReporter(extra, record[key], [...path, key]));
@@ -2691,7 +3706,7 @@ function compileReporter(shape, value, path = []) {
2691
3706
  return faults.length > 64 ? faults.slice(0, 64) : faults;
2692
3707
  }
2693
3708
  case "union": {
2694
- const perVariant = shape.variants.map((variant) => compileReporter(variant, value, path));
3709
+ const perVariant = owned.variants.map((variant) => compileReporter(variant, value, path));
2695
3710
  let bestIndex = 0;
2696
3711
  for (let index = 1; index < perVariant.length; index += 1) {
2697
3712
  const current = perVariant[index];
@@ -2699,9 +3714,9 @@ function compileReporter(shape, value, path = []) {
2699
3714
  if (current !== void 0 && best !== void 0 && current.length < best.length) bestIndex = index;
2700
3715
  }
2701
3716
  const closest = perVariant[bestIndex] ?? [];
2702
- if (shape.mode === "oneOf") {
3717
+ if (owned.mode === "oneOf") {
2703
3718
  let matched = 0;
2704
- for (const variant of shape.variants) if (compileGuard(variant)(value)) matched += 1;
3719
+ for (const variant of owned.variants) if (compileGuard(variant)(value)) matched += 1;
2705
3720
  if (matched === 1) return [];
2706
3721
  if (matched === 0) return [{
2707
3722
  reason: "oneOf",
@@ -2718,19 +3733,25 @@ function compileReporter(shape, value, path = []) {
2718
3733
  return [{
2719
3734
  reason: "variant",
2720
3735
  path,
2721
- variants: shape.variants.length
3736
+ variants: owned.variants.length
2722
3737
  }, ...closest].slice(0, 64);
2723
3738
  }
2724
- case "optional": return value === void 0 ? [] : compileReporter(shape.inner, value, path);
2725
- case "nullable": return value === null ? [] : compileReporter(shape.inner, value, path);
2726
- case "raw": return [];
3739
+ case "optional": return value === void 0 ? [] : compileReporter(owned.inner, value, path);
3740
+ case "nullable": return value === null ? [] : compileReporter(owned.inner, value, path);
3741
+ case "raw": return value === void 0 ? [{
3742
+ reason: "type",
3743
+ path,
3744
+ expected: "json",
3745
+ received: preview(value)
3746
+ }] : [];
2727
3747
  }
2728
3748
  }
2729
3749
  function createContract(shape) {
2730
- validateShape(shape);
2731
- const schema = compileSchema(shape);
2732
- const guard = compileGuard(shape);
2733
- const parser = compileParser(shape);
3750
+ const snapshot = cloneShape(shape);
3751
+ validateShape(snapshot);
3752
+ const schema = compileSchema(snapshot);
3753
+ const guard = compileGuard(snapshot);
3754
+ const parser = compileParser(snapshot);
2734
3755
  return {
2735
3756
  schema,
2736
3757
  is: guard,
@@ -2738,39 +3759,123 @@ function createContract(shape) {
2738
3759
  return parser(value);
2739
3760
  },
2740
3761
  explain(value) {
2741
- return compileReporter(shape, value);
3762
+ return compileReporter(snapshot, value);
2742
3763
  },
2743
3764
  generate(random) {
2744
- return compileGenerator(shape, random);
3765
+ return compileGenerator(snapshot, random);
2745
3766
  }
2746
3767
  };
2747
3768
  }
2748
3769
  //#endregion
2749
3770
  //#region src/core/inferers.ts
2750
3771
  /**
2751
- * Render a value as a deterministic, key-sorted JSON string.
3772
+ * Encode one value as a deterministic, key-sorted JSON string — the recursive
3773
+ * spine of {@link canonicalStringify}.
3774
+ *
3775
+ * @remarks
3776
+ * Arrays keep their element order; records sort their own keys before encoding,
3777
+ * recursively at every nesting level. Every other value is encoded by
3778
+ * `JSON.stringify`, so `NaN` / `±Infinity` collapse to `'null'` and `-0`
3779
+ * encodes as `'0'` — the same lossy-but-deterministic mapping real JSON makes.
3780
+ *
3781
+ * Returns `undefined` for anything JSON cannot encode: `undefined` itself, a
3782
+ * function, a symbol, an array hole, or a cyclic back-edge to an ancestor. A
3783
+ * container carrying such a member is itself un-encodable and returns
3784
+ * `undefined` too, so the result is either a faithful encoding of the WHOLE
3785
+ * value or nothing — a partially-encoded key is never emitted. Traversal is NOT
3786
+ * contained here: a hostile getter or `Proxy` trap throws through to
3787
+ * {@link canonicalStringify}, which owns the single {@link attempt} boundary
3788
+ * for the walk.
3789
+ *
3790
+ * @param value - The value to encode
3791
+ * @param ancestors - Objects on the active traversal path, guarding cycles
3792
+ * @returns The deterministic encoding, or `undefined` when JSON cannot encode
3793
+ * `value`
3794
+ *
3795
+ * @example
3796
+ * ```ts
3797
+ * canonicalizeValue({ b: 1, a: 2 }, new WeakSet()) // '{"a":2,"b":1}'
3798
+ * canonicalizeValue(undefined, new WeakSet()) // undefined
3799
+ * ```
3800
+ */
3801
+ function canonicalizeValue(value, ancestors) {
3802
+ if (isArray(value)) {
3803
+ if (ancestors.has(value)) return void 0;
3804
+ ancestors.add(value);
3805
+ const parts = [];
3806
+ for (let index = 0; index < value.length; index += 1) {
3807
+ const part = Object.hasOwn(value, index) ? canonicalizeValue(value[index], ancestors) : void 0;
3808
+ if (part === void 0) {
3809
+ ancestors.delete(value);
3810
+ return;
3811
+ }
3812
+ parts.push(part);
3813
+ }
3814
+ ancestors.delete(value);
3815
+ return `[${parts.join(",")}]`;
3816
+ }
3817
+ if (isRecord(value)) {
3818
+ if (ancestors.has(value)) return void 0;
3819
+ ancestors.add(value);
3820
+ const parts = [];
3821
+ for (const key of Object.keys(value).sort()) {
3822
+ const part = canonicalizeValue(value[key], ancestors);
3823
+ if (part === void 0) {
3824
+ ancestors.delete(value);
3825
+ return;
3826
+ }
3827
+ parts.push(`${JSON.stringify(key)}:${part}`);
3828
+ }
3829
+ ancestors.delete(value);
3830
+ return `{${parts.join(",")}}`;
3831
+ }
3832
+ return JSON.stringify(value);
3833
+ }
3834
+ /**
3835
+ * Render a value as a deterministic, key-sorted JSON string — or `undefined`
3836
+ * when it has no faithful JSON encoding.
2752
3837
  *
2753
3838
  * @remarks
2754
3839
  * The stable-stringify backing {@link unifySchemas}'s de-duplication and
2755
3840
  * ordering: unlike `JSON.stringify`, object keys are sorted before encoding
2756
3841
  * (recursively, at every nesting level), so two structurally-equal
2757
3842
  * `JSONSchema` fragments built independently always canonicalize to the same
2758
- * string. Pure ECMAScript — no `structuredClone`, no `node:*` import.
3843
+ * string. Pure host-independent ECMAScript with no environment-specific imports.
3844
+ *
3845
+ * TOTAL: it NEVER throws, for any input. It returns `undefined` — never a
3846
+ * partial or invalid encoding — for every value JSON cannot faithfully encode:
3847
+ *
3848
+ * - `undefined` itself, a function, a symbol, or an array hole (JSON encodes
3849
+ * none of them), at the top level or anywhere inside a container;
3850
+ * - a bigint (`JSON.stringify` throws on one);
3851
+ * - cyclic input, tracked with the same ancestor-{@link WeakSet} discipline
3852
+ * {@link inferArray} / {@link inferObject} use, so a shared (non-cyclic)
3853
+ * reference reached twice through different paths still encodes;
3854
+ * - hostile traversal — a throwing own-getter, a hostile `ownKeys` trap, or a
3855
+ * revoked `Proxy` anywhere in the value — contained via {@link attempt}.
3856
+ *
3857
+ * A caller therefore treats `undefined` as "this value has no canonical key",
3858
+ * never as an encoding: see {@link unifySchemas} (an un-keyed member cannot
3859
+ * participate in de-duplication or ordering) and {@link inferPrimitiveEnum} (an
3860
+ * un-keyed member makes the slot enum-ineligible).
2759
3861
  *
2760
3862
  * @param value - The value to canonicalize (a `JSONSchema` fragment, or any
2761
3863
  * nested piece of one)
2762
- * @returns A deterministic string encoding of `value`
3864
+ * @returns A deterministic string encoding of `value`, or `undefined` when JSON
3865
+ * cannot encode it
2763
3866
  *
2764
3867
  * @example
2765
3868
  * ```ts
2766
3869
  * canonicalStringify({ type: 'object', properties: {} }) ===
2767
3870
  * canonicalStringify({ properties: {}, type: 'object' }) // true
3871
+ * canonicalStringify(Number.NaN) // 'null' — JSON.stringify semantics
3872
+ * canonicalStringify(undefined) // undefined
3873
+ * canonicalStringify(cyclicValue) // undefined
2768
3874
  * ```
2769
3875
  */
2770
3876
  function canonicalStringify(value) {
2771
- if (isArray(value)) return `[${value.map((entry) => canonicalStringify(entry)).join(",")}]`;
2772
- if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(value[key])}`).join(",")}}`;
2773
- return JSON.stringify(value);
3877
+ const outcome = attempt(() => canonicalizeValue(value, /* @__PURE__ */ new WeakSet()));
3878
+ return outcome.success ? outcome.value : void 0;
2774
3879
  }
2775
3880
  /**
2776
3881
  * Unify a list of inferred `JSONSchema` fragments into one schema.
@@ -2784,6 +3889,14 @@ function canonicalStringify(value) {
2784
3889
  * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
2785
3890
  * An empty input list returns the empty accept-anything schema `{}`.
2786
3891
  *
3892
+ * A member {@link canonicalStringify} cannot key — a cyclic, hostile, or
3893
+ * otherwise JSON-inexpressible fragment, which only a direct caller can supply
3894
+ * since the inferers always build plain encodable fragments — has NO
3895
+ * de-duplication key, so it can participate in neither de-duplication nor the
3896
+ * canonical-key ordering. It is KEPT (dropping a variant would narrow the
3897
+ * union, and unification only ever widens), appended in input order after the
3898
+ * sorted keyed members, so the result stays total and deterministic.
3899
+ *
2787
3900
  * @param schemas - The schemas to unify
2788
3901
  * @returns The unified schema
2789
3902
  *
@@ -2797,19 +3910,24 @@ function canonicalStringify(value) {
2797
3910
  function unifySchemas(schemas) {
2798
3911
  if (schemas.length === 0) return {};
2799
3912
  const seen = /* @__PURE__ */ new Map();
3913
+ const unkeyed = [];
2800
3914
  for (const schema of schemas) {
2801
3915
  const key = canonicalStringify(schema);
3916
+ if (key === void 0) {
3917
+ unkeyed.push(schema);
3918
+ continue;
3919
+ }
2802
3920
  if (!seen.has(key)) seen.set(key, schema);
2803
3921
  }
2804
3922
  const integerKey = canonicalStringify({ type: "integer" });
2805
3923
  const numberKey = canonicalStringify({ type: "number" });
2806
- if (seen.has(integerKey) && seen.has(numberKey)) seen.delete(integerKey);
2807
- const distinct = [...seen.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, schema]) => schema);
2808
- if (distinct.length <= 1) {
2809
- const [only] = distinct;
3924
+ if (integerKey !== void 0 && numberKey !== void 0 && seen.has(integerKey) && seen.has(numberKey)) seen.delete(integerKey);
3925
+ const members = [...[...seen.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, schema]) => schema), ...unkeyed];
3926
+ if (members.length <= 1) {
3927
+ const [only] = members;
2810
3928
  return only ?? {};
2811
3929
  }
2812
- return { anyOf: distinct };
3930
+ return { anyOf: members };
2813
3931
  }
2814
3932
  /**
2815
3933
  * Determine whether an ISO-8601-shaped string parses to a valid instant.
@@ -2917,6 +4035,12 @@ function samplesToFormat(values) {
2917
4035
  * `literalShape` emission. Members are sorted by canonical key for
2918
4036
  * deterministic output.
2919
4037
  *
4038
+ * A member {@link canonicalStringify} cannot key has no identity to
4039
+ * de-duplicate against, so the whole slot is enum-INELIGIBLE and returns
4040
+ * `undefined` — widening to the caller's bare `type` rather than emitting an
4041
+ * `enum` that might silently omit a value. (A string or finite number always
4042
+ * canonicalizes, so this only guards the total contract.)
4043
+ *
2920
4044
  * @param values - The collected slot values
2921
4045
  * @param limit - The maximum distinct-value count before giving up
2922
4046
  * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
@@ -2934,7 +4058,12 @@ function inferPrimitiveEnum(values, limit) {
2934
4058
  const allNumber = !allString && values.every((value) => isFiniteNumber(value));
2935
4059
  if (!allString && !allNumber) return void 0;
2936
4060
  const distinct = /* @__PURE__ */ new Map();
2937
- for (const value of values) if (isString(value) || isFiniteNumber(value)) distinct.set(canonicalStringify(value), value);
4061
+ for (const value of values) {
4062
+ if (!isString(value) && !isFiniteNumber(value)) continue;
4063
+ const key = canonicalStringify(value);
4064
+ if (key === void 0) return void 0;
4065
+ distinct.set(key, value);
4066
+ }
2938
4067
  if (distinct.size >= values.length || distinct.size > limit) return void 0;
2939
4068
  return { enum: [...distinct.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, value]) => value) };
2940
4069
  }
@@ -2946,13 +4075,21 @@ function inferPrimitiveEnum(values, limit) {
2946
4075
  * @remarks
2947
4076
  * Total: never throws, and terminates on cyclic input via `visited`. Leaf
2948
4077
  * classification order: `null`, boolean, integer (`Number.isInteger`
2949
- * semantics — `-0` counts), finite non-integer number, non-finite number
2950
- * (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
4078
+ * semantics — `-0` counts), finite non-integer number, string (gaining a
2951
4079
  * `format` keyword when `format` is on and {@link stringToFormat} matches),
2952
4080
  * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
2953
- * plus `format: 'date-time'` when `format` is on); everything else
2954
- * (function, symbol, bigint, `undefined`, and other non-plain objects such as
2955
- * `Map` / `Set`) is the empty accept-anything schema `{}`.
4081
+ * plus `format: 'date-time'` when `format` is on); everything else — a
4082
+ * NON-FINITE number (`NaN` / `±Infinity`), a function, a symbol, a bigint,
4083
+ * `undefined`, and other non-plain objects such as `Map` / `Set` — is the
4084
+ * empty accept-anything schema `{}`.
4085
+ *
4086
+ * A non-finite number bottoms out with the other JSON-inexpressible values on
4087
+ * purpose: JSON carries no `NaN` / `±Infinity` (`JSON.stringify(Number.NaN)`
4088
+ * is `'null'`), so `{ type: 'number' }` would ASSERT something a JSON Schema
4089
+ * validator rejects — and the shape {@link schemaToShape} builds from it would
4090
+ * reject the very sample it was inferred from. `{}` is the truthful
4091
+ * description, and it inverts to an accept-anything shape, keeping
4092
+ * `compileGuard(schemaToShape(valueToSchema(v)))(v)` true.
2956
4093
  *
2957
4094
  * @param value - The value to classify
2958
4095
  * @param depth - Remaining descent budget (0 halts recursion with `{}`)
@@ -2974,7 +4111,7 @@ function inferValue(value, depth, breadth, closed, format, visited, memo) {
2974
4111
  if (isBoolean(value)) return { type: "boolean" };
2975
4112
  if (isInteger(value)) return { type: "integer" };
2976
4113
  if (isFiniteNumber(value)) return { type: "number" };
2977
- if (isNumber(value)) return { type: "number" };
4114
+ if (isNumber(value)) return {};
2978
4115
  if (isString(value)) {
2979
4116
  if (format) {
2980
4117
  const detected = stringToFormat(value);
@@ -3060,22 +4197,28 @@ function inferArray(value, depth, breadth, closed, format, visited, memo) {
3060
4197
  * properties.
3061
4198
  *
3062
4199
  * @remarks
3063
- * Own enumerable string keys via `Object.keys`, sorted lexicographically for
3064
- * deterministic output, capped at `breadth`. Each property value is read
3065
- * through {@link attempt} so a hostile getter cannot escape as a thrown
3066
- * error; a property whose value is `undefined` (hostile-getter failure
3067
- * included) is treated as ABSENT — it contributes neither a `properties`
3068
- * entry nor a `required` entry. Every other present key is required (single-
3069
- * value mode). Emits `additionalProperties: false` when `closed`, `true`
3070
- * otherwise — mirroring {@link compileSchema}'s object-emission convention —
3071
- * EXCEPT when the own-key list exceeds `breadth`: a truncated key list means
3072
- * the sampled schema no longer describes every property `value` actually
3073
- * carries, so `additionalProperties` is forced to `true` regardless of
3074
- * `closed` (a closed schema built from a truncated sample would otherwise
3075
- * reject the very object it was inferred from). Depth exhaustion or a cyclic
3076
- * re-encounter of `value` both yield `{}`. A same-object re-inference at the
3077
- * same remaining `depth` is served from `memo` instead of recomputing
3078
- * (guards a shared-reference DAG against exponential blowup).
4200
+ * Own enumerable string keys via {@link enumerableKeys}, sorted
4201
+ * lexicographically for deterministic output, capped at `breadth`. This is the
4202
+ * same property view compiled object guards, parsers, and reporters use. Each
4203
+ * property value is read through {@link attempt} so a hostile getter cannot
4204
+ * escape as a thrown error; a property whose value is `undefined` is DROPPED
4205
+ * — JSON encodes no such property (`JSON.stringify({ a: undefined })` is
4206
+ * `'{}'`), so it contributes neither a `properties` entry nor a `required`
4207
+ * entry. Every other present key is required (single-value mode).
4208
+ *
4209
+ * Emits `additionalProperties: false` when `closed`, `true` otherwise —
4210
+ * mirroring {@link compileSchema}'s object-emission convention — EXCEPT when
4211
+ * the sampled key list no longer describes every key `value` actually carries,
4212
+ * which happens two ways: the own-key list exceeds `breadth` (truncation), or
4213
+ * a key was dropped for holding `undefined`. Either way `additionalProperties`
4214
+ * is forced to `true` regardless of `closed`, because a CLOSED schema built
4215
+ * from an incomplete key list would reject the very object it was inferred
4216
+ * from (`recordOf` rejects any own key the shape does not declare).
4217
+ *
4218
+ * Depth exhaustion or a cyclic re-encounter of `value` both yield `{}`. A
4219
+ * same-object re-inference at the same remaining `depth` is served from `memo`
4220
+ * instead of recomputing (guards a shared-reference DAG against exponential
4221
+ * blowup).
3079
4222
  *
3080
4223
  * @param value - The record to infer from
3081
4224
  * @param depth - Remaining descent budget
@@ -3100,31 +4243,37 @@ function inferObject(value, depth, breadth, closed, format, visited, memo) {
3100
4243
  if (cached) return cached;
3101
4244
  visited.add(value);
3102
4245
  const outcome = attempt(() => {
3103
- const allKeys = Object.keys(value).sort();
4246
+ const snapshot = enumerableKeys(value);
4247
+ if (snapshot === void 0) throw new Error("inferObject: property enumeration failed");
4248
+ const allKeys = [...snapshot].sort();
3104
4249
  const keys = allKeys.slice(0, breadth);
3105
4250
  const truncated = allKeys.length > breadth;
3106
4251
  const properties = Object.create(null);
3107
4252
  const required = [];
4253
+ let dropped = false;
3108
4254
  for (const key of keys) {
3109
4255
  const propertyValue = value[key];
3110
- if (propertyValue === void 0) continue;
4256
+ if (propertyValue === void 0) {
4257
+ dropped = true;
4258
+ continue;
4259
+ }
3111
4260
  properties[key] = inferValue(propertyValue, depth - 1, breadth, closed, format, visited, memo);
3112
4261
  required.push(key);
3113
4262
  }
3114
4263
  return {
3115
4264
  properties,
3116
4265
  required,
3117
- truncated
4266
+ partial: truncated || dropped
3118
4267
  };
3119
4268
  });
3120
4269
  visited.delete(value);
3121
4270
  if (!outcome.success) return {};
3122
- const { properties, required, truncated } = outcome.value;
4271
+ const { properties, required, partial } = outcome.value;
3123
4272
  const schema = {
3124
4273
  type: "object",
3125
4274
  ...Object.keys(properties).length > 0 ? { properties } : {},
3126
4275
  ...required.length > 0 ? { required } : {},
3127
- additionalProperties: truncated ? true : !closed
4276
+ additionalProperties: partial ? true : !closed
3128
4277
  };
3129
4278
  let depths = memo.get(value);
3130
4279
  if (!depths) {
@@ -3236,14 +4385,20 @@ function inferSamples(samples, depth, breadth, closed, format, enumOn) {
3236
4385
  * {@link inferArray}, this path carries no `visited` `WeakSet` — a value
3237
4386
  * shared by reference across multiple sample rows is legitimate (not a
3238
4387
  * cycle back to an ancestor), so termination on cyclic row data relies on
3239
- * the decrementing `depth` budget alone. When the union of sample keys
3240
- * exceeds `breadth`, the key list is truncated and `additionalProperties` is
3241
- * forced to `true` regardless of `closed` — the same truncation-opens-the-
3242
- * schema rule {@link inferObject} applies, so a closed schema built from a
3243
- * truncated key union never rejects the very rows it was inferred from. A
3244
- * hostile getter on ONE sample row drops that key for ALL rows (the whole
3245
- * per-key value collection is a single {@link attempt}-contained walk) —
3246
- * this is a deliberate all-or-nothing scope, not a per-row partial failure.
4388
+ * the decrementing `depth` budget alone.
4389
+ *
4390
+ * `additionalProperties` is forced to `true` regardless of `closed` whenever
4391
+ * the declared key list stops describing every key the rows carry — the same
4392
+ * incomplete-sample-opens-the-schema rule {@link inferObject} applies, so a
4393
+ * closed schema never rejects the very rows it was inferred from. That happens
4394
+ * three ways: the union of sample keys exceeds `breadth` (truncation); a
4395
+ * hostile getter defeats a key's value walk (which drops that key for ALL
4396
+ * rows — a deliberate all-or-nothing scope, not a per-row partial failure);
4397
+ * or some row carries the key as an own property holding `undefined`, which
4398
+ * JSON encodes as no property at all, so the key is dropped rather than
4399
+ * declared with a shape that row would fail. When the KEY walk itself fails
4400
+ * (a hostile `ownKeys` trap on any row), nothing is known and the whole slot
4401
+ * widens to `{}`.
3247
4402
  *
3248
4403
  * @param samples - The plain-record samples
3249
4404
  * @param depth - Remaining descent budget
@@ -3262,29 +4417,44 @@ function inferSamples(samples, depth, breadth, closed, format, enumOn) {
3262
4417
  */
3263
4418
  function inferRecordSamples(samples, depth, breadth, closed, format, enumOn) {
3264
4419
  if (!(depth > 0)) return {};
3265
- const keysOutcome = attempt(() => {
3266
- const keySet = /* @__PURE__ */ new Set();
3267
- for (const sample of samples) for (const key of Object.keys(sample)) keySet.add(key);
3268
- const allKeys = [...keySet].sort();
3269
- return {
3270
- keys: allKeys.slice(0, breadth),
3271
- truncated: allKeys.length > breadth
3272
- };
3273
- });
3274
- const keys = keysOutcome.success ? keysOutcome.value.keys : [];
3275
- const truncated = keysOutcome.success && keysOutcome.value.truncated;
4420
+ const keySet = /* @__PURE__ */ new Set();
4421
+ for (const sample of samples) {
4422
+ const sampleKeys = enumerableKeys(sample);
4423
+ if (sampleKeys === void 0) return {};
4424
+ for (const key of sampleKeys) keySet.add(key);
4425
+ }
4426
+ const allKeys = [...keySet].sort();
4427
+ const keys = allKeys.slice(0, breadth);
4428
+ const truncated = allKeys.length > breadth;
3276
4429
  const properties = Object.create(null);
3277
4430
  const required = [];
4431
+ let partial = truncated;
3278
4432
  for (const key of keys) {
3279
4433
  const valuesOutcome = attempt(() => {
3280
4434
  const values = [];
4435
+ let dropped = false;
3281
4436
  for (const sample of samples) {
3282
4437
  const propertyValue = sample[key];
3283
- if (propertyValue !== void 0) values.push(propertyValue);
4438
+ if (propertyValue === void 0) {
4439
+ if (Object.hasOwn(sample, key)) dropped = true;
4440
+ continue;
4441
+ }
4442
+ values.push(propertyValue);
3284
4443
  }
3285
- return values;
4444
+ return {
4445
+ values,
4446
+ dropped
4447
+ };
3286
4448
  });
3287
- const values = valuesOutcome.success ? valuesOutcome.value : [];
4449
+ if (!valuesOutcome.success) {
4450
+ partial = true;
4451
+ continue;
4452
+ }
4453
+ const { values, dropped } = valuesOutcome.value;
4454
+ if (dropped) {
4455
+ partial = true;
4456
+ continue;
4457
+ }
3288
4458
  if (values.length > 0) properties[key] = inferSamples(values, depth - 1, breadth, closed, format, enumOn);
3289
4459
  if (values.length === samples.length) required.push(key);
3290
4460
  }
@@ -3292,7 +4462,7 @@ function inferRecordSamples(samples, depth, breadth, closed, format, enumOn) {
3292
4462
  type: "object",
3293
4463
  ...Object.keys(properties).length > 0 ? { properties } : {},
3294
4464
  ...required.length > 0 ? { required } : {},
3295
- additionalProperties: truncated ? true : !closed
4465
+ additionalProperties: partial ? true : !closed
3296
4466
  };
3297
4467
  }
3298
4468
  /**
@@ -3334,8 +4504,14 @@ function samplesToSchema(samples, options) {
3334
4504
  /**
3335
4505
  * Build a string {@link StringShape}.
3336
4506
  *
4507
+ * @remarks
4508
+ * A supplied pattern is captured by source and flags. The shape exposes a fresh
4509
+ * frozen zero-state `RegExp` on every `pattern` read, so neither the caller's
4510
+ * original nor a value read from the shape can drift later compiled artifacts.
4511
+ *
3337
4512
  * @param options - Optional length (`min` / `max`), `pattern`, and `description`
3338
4513
  * @returns A string shape
4514
+ * @throws {ContractError} When a present bound is invalid or `pattern` has flags
3339
4515
  *
3340
4516
  * @example
3341
4517
  * ```ts
@@ -3343,19 +4519,44 @@ function samplesToSchema(samples, options) {
3343
4519
  * ```
3344
4520
  */
3345
4521
  function stringShape(options) {
3346
- return {
4522
+ const pattern = options?.pattern;
4523
+ if (options?.min !== void 0 && (!Number.isSafeInteger(options.min) || options.min < 0)) throw new ContractError("stringShape: min must be a non-negative safe integer", {
4524
+ code: "bound",
4525
+ context: {
4526
+ shape: "string",
4527
+ limit: "non-negative safe integer",
4528
+ received: String(options.min)
4529
+ }
4530
+ });
4531
+ if (options?.max !== void 0 && (!Number.isSafeInteger(options.max) || options.max < 0)) throw new ContractError("stringShape: max must be a non-negative safe integer", {
4532
+ code: "bound",
4533
+ context: {
4534
+ shape: "string",
4535
+ limit: "non-negative safe integer",
4536
+ received: String(options.max)
4537
+ }
4538
+ });
4539
+ if (pattern !== void 0 && pattern.flags.length > 0) throw new ContractError("stringShape: pattern must not use flags; use inline pattern constructs instead", {
4540
+ code: "pattern",
4541
+ context: {
4542
+ shape: "string",
4543
+ received: pattern.toString()
4544
+ }
4545
+ });
4546
+ return cloneShape({
3347
4547
  type: "string",
3348
- min: options?.min,
3349
- max: options?.max,
3350
- pattern: options?.pattern,
3351
- description: options?.description
3352
- };
4548
+ ...options?.min === void 0 ? {} : { min: options.min },
4549
+ ...options?.max === void 0 ? {} : { max: options.max },
4550
+ ...pattern === void 0 ? {} : { pattern },
4551
+ ...options?.description === void 0 ? {} : { description: options.description }
4552
+ });
3353
4553
  }
3354
4554
  /**
3355
4555
  * Build a numeric {@link NumberShape}.
3356
4556
  *
3357
4557
  * @param options - Optional bounds (`min` / `max`), `integer`, and `description`
3358
4558
  * @returns A number shape
4559
+ * @throws {ContractError} When a present bound is not finite
3359
4560
  *
3360
4561
  * @example
3361
4562
  * ```ts
@@ -3363,13 +4564,30 @@ function stringShape(options) {
3363
4564
  * ```
3364
4565
  */
3365
4566
  function numberShape(options) {
3366
- return {
4567
+ const shape = options?.integer === true ? "integer" : "number";
4568
+ if (options?.min !== void 0 && !Number.isFinite(options.min)) throw new ContractError("numberShape: min must be finite", {
4569
+ code: "bound",
4570
+ context: {
4571
+ shape,
4572
+ limit: "finite number",
4573
+ received: String(options.min)
4574
+ }
4575
+ });
4576
+ if (options?.max !== void 0 && !Number.isFinite(options.max)) throw new ContractError("numberShape: max must be finite", {
4577
+ code: "bound",
4578
+ context: {
4579
+ shape,
4580
+ limit: "finite number",
4581
+ received: String(options.max)
4582
+ }
4583
+ });
4584
+ return Object.freeze({
3367
4585
  type: "number",
3368
- min: options?.min,
3369
- max: options?.max,
3370
- integer: options?.integer,
3371
- description: options?.description
3372
- };
4586
+ ...options?.min === void 0 ? {} : { min: options.min },
4587
+ ...options?.max === void 0 ? {} : { max: options.max },
4588
+ ...options?.integer === void 0 ? {} : { integer: options.integer },
4589
+ ...options?.description === void 0 ? {} : { description: options.description }
4590
+ });
3373
4591
  }
3374
4592
  /**
3375
4593
  * Build an integer {@link NumberShape} — forces `integer: true`.
@@ -3380,15 +4598,13 @@ function numberShape(options) {
3380
4598
  *
3381
4599
  * @param options - Optional bounds and `description` (no `integer` key)
3382
4600
  * @returns An integer number shape
4601
+ * @throws {ContractError} When a present bound is not finite
3383
4602
  */
3384
4603
  function integerShape(options) {
3385
- return {
3386
- type: "number",
3387
- integer: true,
3388
- min: options?.min,
3389
- max: options?.max,
3390
- description: options?.description
3391
- };
4604
+ return numberShape({
4605
+ ...options,
4606
+ integer: true
4607
+ });
3392
4608
  }
3393
4609
  /**
3394
4610
  * Build a {@link BooleanShape}.
@@ -3402,10 +4618,10 @@ function integerShape(options) {
3402
4618
  * ```
3403
4619
  */
3404
4620
  function booleanShape(options) {
3405
- return {
4621
+ return Object.freeze({
3406
4622
  type: "boolean",
3407
- description: options?.description
3408
- };
4623
+ ...options?.description === void 0 ? {} : { description: options.description }
4624
+ });
3409
4625
  }
3410
4626
  /**
3411
4627
  * Build a {@link NullShape}.
@@ -3419,32 +4635,18 @@ function booleanShape(options) {
3419
4635
  * ```
3420
4636
  */
3421
4637
  function nullShape(options) {
3422
- return {
4638
+ return Object.freeze({
3423
4639
  type: "null",
3424
- description: options?.description
3425
- };
4640
+ ...options?.description === void 0 ? {} : { description: options.description }
4641
+ });
3426
4642
  }
3427
- /**
3428
- * Build a literal shape from a fixed set of primitive values.
3429
- *
3430
- * @param values - The permitted literals
3431
- * @param options - Optional `description`
3432
- * @returns A literal shape whose `Infer` is the union of `values`
3433
- *
3434
- * @example
3435
- * ```ts
3436
- * const role = literalShape(['admin', 'member', 'guest'])
3437
- * // Infer<typeof role> = 'admin' | 'member' | 'guest'
3438
- *
3439
- * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
3440
- * ```
3441
- */
3442
4643
  function literalShape(values, options) {
3443
- return {
4644
+ const snapshot = Object.freeze([...values]);
4645
+ return Object.freeze({
3444
4646
  type: "literal",
3445
- values,
3446
- description: options?.description
3447
- };
4647
+ values: snapshot,
4648
+ ...options?.description === void 0 ? {} : { description: options.description }
4649
+ });
3448
4650
  }
3449
4651
  /**
3450
4652
  * Build an {@link ArrayShape} from an element shape.
@@ -3452,6 +4654,7 @@ function literalShape(values, options) {
3452
4654
  * @param items - The element shape
3453
4655
  * @param options - Optional length bounds and `description`
3454
4656
  * @returns An array shape
4657
+ * @throws {ContractError} When a present bound is not a non-negative safe integer
3455
4658
  *
3456
4659
  * @example
3457
4660
  * ```ts
@@ -3459,13 +4662,29 @@ function literalShape(values, options) {
3459
4662
  * ```
3460
4663
  */
3461
4664
  function arrayShape(items, options) {
3462
- return {
4665
+ if (options?.min !== void 0 && (!Number.isSafeInteger(options.min) || options.min < 0)) throw new ContractError("arrayShape: min must be a non-negative safe integer", {
4666
+ code: "bound",
4667
+ context: {
4668
+ shape: "array",
4669
+ limit: "non-negative safe integer",
4670
+ received: String(options.min)
4671
+ }
4672
+ });
4673
+ if (options?.max !== void 0 && (!Number.isSafeInteger(options.max) || options.max < 0)) throw new ContractError("arrayShape: max must be a non-negative safe integer", {
4674
+ code: "bound",
4675
+ context: {
4676
+ shape: "array",
4677
+ limit: "non-negative safe integer",
4678
+ received: String(options.max)
4679
+ }
4680
+ });
4681
+ return Object.freeze({
3463
4682
  type: "array",
3464
4683
  items,
3465
- min: options?.min,
3466
- max: options?.max,
3467
- description: options?.description
3468
- };
4684
+ ...options?.min === void 0 ? {} : { min: options.min },
4685
+ ...options?.max === void 0 ? {} : { max: options.max },
4686
+ ...options?.description === void 0 ? {} : { description: options.description }
4687
+ });
3469
4688
  }
3470
4689
  /**
3471
4690
  * Build an {@link ObjectShape} from a property map.
@@ -3489,12 +4708,14 @@ function arrayShape(items, options) {
3489
4708
  * ```
3490
4709
  */
3491
4710
  function objectShape(properties, options) {
3492
- return {
4711
+ const snapshot = Object.create(null);
4712
+ for (const key in properties) if (Object.hasOwn(properties, key)) snapshot[key] = properties[key];
4713
+ return Object.freeze({
3493
4714
  type: "object",
3494
- properties,
3495
- additionalProperties: options?.additionalProperties,
3496
- description: options?.description
3497
- };
4715
+ properties: Object.freeze(snapshot),
4716
+ ...options?.additionalProperties === void 0 ? {} : { additionalProperties: options.additionalProperties },
4717
+ ...options?.description === void 0 ? {} : { description: options.description }
4718
+ });
3498
4719
  }
3499
4720
  /**
3500
4721
  * Build an open {@link ObjectShape} with no fixed properties — a dictionary.
@@ -3513,12 +4734,12 @@ function objectShape(properties, options) {
3513
4734
  * ```
3514
4735
  */
3515
4736
  function recordShape(values, options) {
3516
- return {
4737
+ return Object.freeze({
3517
4738
  type: "object",
3518
- properties: {},
4739
+ properties: Object.freeze({}),
3519
4740
  additionalProperties: values,
3520
- description: options?.description
3521
- };
4741
+ ...options?.description === void 0 ? {} : { description: options.description }
4742
+ });
3522
4743
  }
3523
4744
  /**
3524
4745
  * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
@@ -3533,10 +4754,10 @@ function recordShape(values, options) {
3533
4754
  * ```
3534
4755
  */
3535
4756
  function unionShape(...variants) {
3536
- return {
4757
+ return Object.freeze({
3537
4758
  type: "union",
3538
- variants
3539
- };
4759
+ variants: Object.freeze(variants)
4760
+ });
3540
4761
  }
3541
4762
  /**
3542
4763
  * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
@@ -3571,11 +4792,11 @@ function unionShape(...variants) {
3571
4792
  * ```
3572
4793
  */
3573
4794
  function oneOfShape(...variants) {
3574
- return {
4795
+ return Object.freeze({
3575
4796
  type: "union",
3576
- variants,
4797
+ variants: Object.freeze(variants),
3577
4798
  mode: "oneOf"
3578
- };
4799
+ });
3579
4800
  }
3580
4801
  /**
3581
4802
  * Wrap a shape so it may be absent (`undefined`).
@@ -3588,10 +4809,10 @@ function oneOfShape(...variants) {
3588
4809
  * @returns An optional shape
3589
4810
  */
3590
4811
  function optionalShape(inner) {
3591
- return {
4812
+ return Object.freeze({
3592
4813
  type: "optional",
3593
4814
  inner
3594
- };
4815
+ });
3595
4816
  }
3596
4817
  /**
3597
4818
  * Wrap a shape so it may be `null`.
@@ -3606,18 +4827,18 @@ function optionalShape(inner) {
3606
4827
  * ```
3607
4828
  */
3608
4829
  function nullableShape(inner) {
3609
- return {
4830
+ return Object.freeze({
3610
4831
  type: "nullable",
3611
4832
  inner
3612
- };
4833
+ });
3613
4834
  }
3614
4835
  /**
3615
4836
  * Build a {@link JSONShape}.
3616
4837
  *
3617
4838
  * @remarks
3618
4839
  * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
3619
- * schema fragment and accepts anything at runtime, while `jsonShape` validates
3620
- * that a value is real JSON (via {@link isJSONValue}).
4840
+ * schema fragment and accepts every defined value at runtime, while `jsonShape`
4841
+ * validates that a value is real JSON (via {@link isJSONValue}).
3621
4842
  *
3622
4843
  * @param options - Optional `description`
3623
4844
  * @returns A JSON passthrough shape
@@ -3628,20 +4849,27 @@ function nullableShape(inner) {
3628
4849
  * ```
3629
4850
  */
3630
4851
  function jsonShape(options) {
3631
- return {
4852
+ return Object.freeze({
3632
4853
  type: "json",
3633
- description: options?.description
3634
- };
4854
+ ...options?.description === void 0 ? {} : { description: options.description }
4855
+ });
3635
4856
  }
3636
4857
  /**
3637
4858
  * Build a {@link RawShape} from a JSON Schema fragment.
3638
4859
  *
3639
4860
  * @remarks
3640
- * For values the shape DSL can't express. The compiled guard accepts any value;
3641
- * the parser passes it through; the schema is emitted verbatim.
4861
+ * For values the shape DSL can't express. The compiled guard accepts every
4862
+ * DEFINED value — `undefined` alone fails, because it is the parser's failure
4863
+ * sentinel; wrap the shape in {@link optionalShape} to admit absence. The
4864
+ * parser passes a defined value through unchanged, and the fragment is
4865
+ * deep-cloned into an owned frozen snapshot ({@link cloneSchema}), so
4866
+ * `rawShape(fragment).schema !== fragment` and later edits to the caller's
4867
+ * fragment cannot reach the shape. `compileSchema` re-emits that snapshot
4868
+ * structurally verbatim; `compileGenerator` throws, since an arbitrary embedded
4869
+ * schema has no auto-generatable sample.
3642
4870
  *
3643
4871
  * @param schema - The JSON Schema fragment to embed
3644
- * @returns A raw shape
4872
+ * @returns A raw shape owning a frozen copy of the fragment
3645
4873
  *
3646
4874
  * @example
3647
4875
  * ```ts
@@ -3649,10 +4877,10 @@ function jsonShape(options) {
3649
4877
  * ```
3650
4878
  */
3651
4879
  function rawShape(schema) {
3652
- return {
4880
+ return Object.freeze({
3653
4881
  type: "raw",
3654
- schema
3655
- };
4882
+ schema: cloneSchema(schema)
4883
+ });
3656
4884
  }
3657
4885
  /**
3658
4886
  * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON
@@ -3660,10 +4888,11 @@ function rawShape(schema) {
3660
4888
  *
3661
4889
  * @remarks
3662
4890
  * Total and pure. Either keyword is used only when it is a non-negative
3663
- * integer (`isInteger` + `>= 0`); a malformed value (a string, a negative
3664
- * number, `NaN`, `Infinity`, a fraction) is dropped as if absent. When both
3665
- * bounds are present and `min` exceeds `max`, the PAIR is dropped entirely
3666
- * (an unbounded shape is always a legal widening of a contradictory schema).
4891
+ * safe integer (`Number.isSafeInteger` + `>= 0`); a malformed value (a string,
4892
+ * a negative number, `NaN`, `Infinity`, a fraction, or an unsafe integer) is
4893
+ * dropped as if absent. When both bounds are present and `min` exceeds `max`,
4894
+ * the PAIR is dropped entirely (an unbounded shape is always a legal widening
4895
+ * of a contradictory schema).
3667
4896
  *
3668
4897
  * @param min - The raw `minLength` / `minItems` keyword value
3669
4898
  * @param max - The raw `maxLength` / `maxItems` keyword value
@@ -3677,12 +4906,12 @@ function rawShape(schema) {
3677
4906
  * ```
3678
4907
  */
3679
4908
  function deriveLengthBounds(min, max) {
3680
- const lo = isInteger(min) && min >= 0 ? min : void 0;
3681
- const hi = isInteger(max) && max >= 0 ? max : void 0;
4909
+ const lo = isInteger(min) && Number.isSafeInteger(min) && min >= 0 ? min : void 0;
4910
+ const hi = isInteger(max) && Number.isSafeInteger(max) && max >= 0 ? max : void 0;
3682
4911
  if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
3683
4912
  return {
3684
- min: lo,
3685
- max: hi
4913
+ ...lo === void 0 ? {} : { min: lo },
4914
+ ...hi === void 0 ? {} : { max: hi }
3686
4915
  };
3687
4916
  }
3688
4917
  /**
@@ -3710,8 +4939,8 @@ function deriveRangeBounds(min, max) {
3710
4939
  const hi = isFiniteNumber(max) ? max : void 0;
3711
4940
  if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
3712
4941
  return {
3713
- min: lo,
3714
- max: hi
4942
+ ...lo === void 0 ? {} : { min: lo },
4943
+ ...hi === void 0 ? {} : { max: hi }
3715
4944
  };
3716
4945
  }
3717
4946
  /**
@@ -3723,7 +4952,7 @@ function deriveRangeBounds(min, max) {
3723
4952
  * `properties` (when a record) contributes one child shape per own key, capped
3724
4953
  * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}
3725
4954
  * unless it appears as a string entry of `required`. A property whose value is
3726
- * not itself a record widens to {@link jsonShape}. `additionalProperties`:
4955
+ * not itself a record widens to {@link rawShape}. `additionalProperties`:
3727
4956
  * `false` closes the object; a record value recurses into it (`objectShape`
3728
4957
  * validates extras against that shape); anything else — `true`, absent, or
3729
4958
  * malformed — leaves the object OPEN (`true`), matching JSON Schema's own
@@ -3733,8 +4962,8 @@ function deriveRangeBounds(min, max) {
3733
4962
  * keys than {@link INFER_BREADTH_LIMIT}, the schema's own
3734
4963
  * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —
3735
4964
  * a dropped key's value could otherwise fail a `false` or record-valued rest
3736
- * shape it was never checked against — mirroring `inferObject`'s
3737
- * `truncated ? true : !closed` rule (inferers.ts:485). The accumulator uses a
4965
+ * shape it was never checked against — mirroring {@link inferObject}'s
4966
+ * partial-key handling in `inferers.ts`. The accumulator uses a
3738
4967
  * null-prototype record so a property literally named `__proto__` becomes an
3739
4968
  * own data key rather than mutating the prototype, mirroring
3740
4969
  * {@link inferObject} (inferers.ts).
@@ -3775,14 +5004,14 @@ function buildObjectShape(schema, depth, visited, memo, description) {
3775
5004
  const keys = allKeys.slice(0, 256);
3776
5005
  for (const key of keys) {
3777
5006
  const child = propertiesSource[key];
3778
- const childShape = isRecord(child) ? schemaNodeToShape(child, depth - 1, visited, memo) : jsonShape();
5007
+ const childShape = isRecord(child) ? schemaNodeToShape(child, depth - 1, visited, memo) : rawShape({});
3779
5008
  properties[key] = requiredSource.includes(key) ? childShape : optionalShape(childShape);
3780
5009
  }
3781
5010
  }
3782
5011
  const extra = schema.additionalProperties;
3783
5012
  return objectShape(properties, {
3784
5013
  additionalProperties: truncated ? true : extra === false ? false : isRecord(extra) ? schemaNodeToShape(extra, depth - 1, visited, memo) : true,
3785
- description
5014
+ ...description === void 0 ? {} : { description }
3786
5015
  });
3787
5016
  }
3788
5017
  /**
@@ -3805,7 +5034,7 @@ function buildObjectShape(schema, depth, visited, memo, description) {
3805
5034
  * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the
3806
5035
  * limit, building a subset union would be strictly narrower than the
3807
5036
  * schema's full union (a value matching only a dropped variant would be
3808
- * wrongly rejected), so the whole node widens to {@link jsonShape} instead
5037
+ * wrongly rejected), so the whole node widens to {@link rawShape} instead
3809
5038
  * of sampling a subset.
3810
5039
  * 3. `anyOf` — identically, via {@link unionShape}.
3811
5040
  * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —
@@ -3815,14 +5044,16 @@ function buildObjectShape(schema, depth, visited, memo, description) {
3815
5044
  * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
3816
5045
  * rejects — so the result is always a valid shape.
3817
5046
  * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
3818
- * a record-valued `items` (widening to {@link jsonShape} otherwise), with
5047
+ * a record-valued `items` (widening to {@link rawShape} otherwise), with
3819
5048
  * bounds from `minItems` / `maxItems`.
3820
5049
  * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
3821
5050
  * record-valued `properties` — delegates to {@link buildObjectShape}.
3822
5051
  * 7. Everything else — an empty schema, an unrecognized/absent `type`,
3823
5052
  * exhausted depth/breadth, or an attempt failure — widens to
3824
- * {@link jsonShape} (the exact inverse of `compileSchema(jsonShape())`,
3825
- * and where the inferers themselves bottom out at their own limits).
5053
+ * {@link rawShape}, whose guard accepts every defined value and whose
5054
+ * emitted schema is the same `{}` (plus `description`) the node carried.
5055
+ * This is the exact inverse of `{}`, JSON Schema's accept-anything schema,
5056
+ * and where the inferers themselves bottom out at their own limits.
3826
5057
  *
3827
5058
  * `format` and `pattern` are NEVER read into the compiled shape — `format` is
3828
5059
  * annotation-only and `pattern` compiling an attacker-supplied string into a
@@ -3830,7 +5061,7 @@ function buildObjectShape(schema, depth, visited, memo, description) {
3830
5061
  * the produced shape's `description` option.
3831
5062
  *
3832
5063
  * @param schema - The schema node to convert
3833
- * @param depth - Remaining descent budget (0 halts recursion with `jsonShape()`)
5064
+ * @param depth - Remaining descent budget (0 halts recursion with `rawShape({})`)
3834
5065
  * @param visited - The ancestor set guarding against cycles — recursion
3835
5066
  * state owned by the {@link schemaToShape} entry point; passing a shared or
3836
5067
  * pre-populated `WeakSet` changes cycle-detection behavior and is not
@@ -3853,58 +5084,44 @@ function buildShapeFromNode(schema, depth, visited, memo) {
3853
5084
  const description = isString(schema.description) ? schema.description : void 0;
3854
5085
  if (isArray(schema.enum)) {
3855
5086
  const literals = schema.enum.filter((entry) => isString(entry) || isFiniteNumber(entry) || isBoolean(entry));
3856
- if (literals.length > 0) return literalShape(literals, { description });
5087
+ if (literals.length > 0) return literalShape(literals, description === void 0 ? void 0 : { description });
3857
5088
  }
3858
5089
  if (isArray(schema.oneOf)) {
3859
5090
  const records = schema.oneOf.filter((entry) => isRecord(entry));
3860
- if (records.length > 256) return jsonShape({ description });
5091
+ if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
3861
5092
  const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
3862
5093
  if (variants.length > 0) return oneOfShape(...variants);
3863
5094
  }
3864
5095
  if (isArray(schema.anyOf)) {
3865
5096
  const records = schema.anyOf.filter((entry) => isRecord(entry));
3866
- if (records.length > 256) return jsonShape({ description });
5097
+ if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
3867
5098
  const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
3868
5099
  if (variants.length > 0) return unionShape(...variants);
3869
5100
  }
3870
5101
  const type = isString(schema.type) ? schema.type : void 0;
3871
- if (type === "string") {
3872
- const bounds = deriveLengthBounds(schema.minLength, schema.maxLength);
3873
- return stringShape({
3874
- min: bounds.min,
3875
- max: bounds.max,
3876
- description
3877
- });
3878
- }
3879
- if (type === "number") {
3880
- const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
3881
- return numberShape({
3882
- min: bounds.min,
3883
- max: bounds.max,
3884
- description
3885
- });
3886
- }
5102
+ if (type === "string") return stringShape({
5103
+ ...deriveLengthBounds(schema.minLength, schema.maxLength),
5104
+ ...description === void 0 ? {} : { description }
5105
+ });
5106
+ if (type === "number") return numberShape({
5107
+ ...deriveRangeBounds(schema.minimum, schema.maximum),
5108
+ ...description === void 0 ? {} : { description }
5109
+ });
3887
5110
  if (type === "integer") {
3888
5111
  const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
3889
- return integerShape(Math.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > Math.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? { description } : {
3890
- min: bounds.min,
3891
- max: bounds.max,
3892
- description
3893
- });
3894
- }
3895
- if (type === "boolean") return booleanShape({ description });
3896
- if (type === "null") return nullShape({ description });
3897
- if (type === "array") {
3898
- const items = isRecord(schema.items) ? schemaNodeToShape(schema.items, depth - 1, visited, memo) : jsonShape();
3899
- const bounds = deriveLengthBounds(schema.minItems, schema.maxItems);
3900
- return arrayShape(items, {
3901
- min: bounds.min,
3902
- max: bounds.max,
3903
- description
5112
+ return integerShape(Math.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > Math.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? description === void 0 ? void 0 : { description } : {
5113
+ ...bounds,
5114
+ ...description === void 0 ? {} : { description }
3904
5115
  });
3905
5116
  }
5117
+ if (type === "boolean") return booleanShape(description === void 0 ? void 0 : { description });
5118
+ if (type === "null") return nullShape(description === void 0 ? void 0 : { description });
5119
+ if (type === "array") return arrayShape(isRecord(schema.items) ? schemaNodeToShape(schema.items, depth - 1, visited, memo) : rawShape({}), {
5120
+ ...deriveLengthBounds(schema.minItems, schema.maxItems),
5121
+ ...description === void 0 ? {} : { description }
5122
+ });
3906
5123
  if (type === "object" || type === void 0 && isRecord(schema.properties)) return buildObjectShape(schema, depth, visited, memo, description);
3907
- return jsonShape({ description });
5124
+ return rawShape(description === void 0 ? {} : { description });
3908
5125
  }
3909
5126
  /**
3910
5127
  * Convert one JSON Schema node into a {@link ContractShape} — the recursion
@@ -3915,13 +5132,13 @@ function buildShapeFromNode(schema, depth, visited, memo) {
3915
5132
  * @remarks
3916
5133
  * Total: never throws. Guards depth exhaustion, a non-record node (the
3917
5134
  * node's static `JSONSchema` type is not trusted at runtime), and a cyclic
3918
- * re-encounter of `schema` — all three widen to {@link jsonShape}. The
5135
+ * re-encounter of `schema` — all three widen to {@link rawShape}. The
3919
5136
  * ancestor set is added to and removed from around the WHOLE subtree
3920
5137
  * conversion (not permanently), so a DAG-shaped schema reached twice via two
3921
5138
  * different, non-cyclic paths does not false-positive as a cycle. The
3922
5139
  * subtree conversion itself runs inside {@link attempt}, so a hostile
3923
5140
  * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
3924
- * — it degrades to {@link jsonShape} instead. A same-node re-conversion at
5141
+ * — it degrades to {@link rawShape} instead. A same-node re-conversion at
3925
5142
  * the same remaining `depth` is served from `memo` (guards a
3926
5143
  * shared-reference schema DAG against exponential blowup), mirroring
3927
5144
  * {@link inferObject} / {@link inferArray} (inferers.ts).
@@ -3936,7 +5153,7 @@ function buildShapeFromNode(schema, depth, visited, memo) {
3936
5153
  * recursion state owned by the {@link schemaToShape} entry point; passing
3937
5154
  * a shared or pre-populated `WeakMap` changes caching behavior and is not
3938
5155
  * supported usage
3939
- * @returns The built shape for `schema`, or {@link jsonShape} on any failure
5156
+ * @returns The built shape for `schema`, or {@link rawShape} on any failure
3940
5157
  *
3941
5158
  * @example
3942
5159
  * ```ts
@@ -3945,13 +5162,13 @@ function buildShapeFromNode(schema, depth, visited, memo) {
3945
5162
  * ```
3946
5163
  */
3947
5164
  function schemaNodeToShape(schema, depth, visited, memo) {
3948
- if (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return jsonShape();
5165
+ if (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return rawShape({});
3949
5166
  const cached = memo.get(schema)?.get(depth);
3950
5167
  if (cached) return cached;
3951
5168
  visited.add(schema);
3952
5169
  const outcome = attempt(() => buildShapeFromNode(schema, depth, visited, memo));
3953
5170
  visited.delete(schema);
3954
- const shape = outcome.success ? outcome.value : jsonShape();
5171
+ const shape = outcome.success ? outcome.value : rawShape({});
3955
5172
  let depths = memo.get(schema);
3956
5173
  if (!depths) {
3957
5174
  depths = /* @__PURE__ */ new Map();
@@ -3968,7 +5185,7 @@ function schemaNodeToShape(schema, depth, visited, memo) {
3968
5185
  * @remarks
3969
5186
  * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
3970
5187
  * outright hostile (throwing-getter Proxy) `schema` value all degrade to
3971
- * {@link jsonShape} rather than escaping as an error, so
5188
+ * {@link rawShape} rather than escaping as an error, so
3972
5189
  * `createContract(schemaToShape(x))` is safe to call for any `x`. See
3973
5190
  * {@link buildShapeFromNode} for the exact per-keyword precedence.
3974
5191
  *
@@ -3978,9 +5195,36 @@ function schemaNodeToShape(schema, depth, visited, memo) {
3978
5195
  * `RegExp` is a ReDoS vector; both keywords are read only far enough to be
3979
5196
  * ignored. Any node the walk cannot express — an empty `{}`, an
3980
5197
  * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a
3981
- * cyclic re-encounter — widens to {@link jsonShape} (accept any JSON), never
3982
- * narrows: the round trip `compileGuard(schemaToShape(valueToSchema(v)))(v)`
3983
- * holds for every `v`, with widening as the only source of looseness.
5198
+ * cyclic re-encounter — widens to {@link rawShape} (accept any defined
5199
+ * value), never narrows.
5200
+ *
5201
+ * ROUND TRIP: `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` for
5202
+ * every `v` — including the values no JSON Schema keyword describes (`NaN`,
5203
+ * `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a
5204
+ * bigint, a cyclic or hostile host), which infer `{}` and widen back to an
5205
+ * accept-anything {@link rawShape}. Widening is the only source of looseness.
5206
+ * The law has three explicit host limits:
5207
+ *
5208
+ * - **Absence.** `undefined` is not a value: no compiled guard accepts it
5209
+ * (`rawShape` reserves it as the parser failure sentinel). So `undefined`
5210
+ * itself, an array element holding it, and an array HOLE (`arrayOf` requires
5211
+ * every index to be an own property, the same rule `isJSONValue` applies)
5212
+ * all fall outside the law. An OBJECT property holding `undefined` does not:
5213
+ * `valueToSchema` drops the key and opens the object, so the source object
5214
+ * is still accepted.
5215
+ * - **`Date` serialization.** A `Date` infers the schema of its JSON form
5216
+ * (`{ type: 'string' }`, plus `format: 'date-time'` when `format` is on), so
5217
+ * the law applies to `date.toISOString()` rather than the runtime instance.
5218
+ * - **Stateful access.** A getter whose result changes between inference and
5219
+ * guard evaluation can invalidate the sampled fact. Likewise, an array that
5220
+ * overrides iteration behavior can present different elements to the two
5221
+ * phases. The law applies only while the sampled host's observable own
5222
+ * enumerable string properties and array iteration remain stable.
5223
+ *
5224
+ * A widened node cannot be auto-generated: `rawShape` embeds an arbitrary
5225
+ * schema fragment, so `createContract(schemaToShape(x)).generate()` throws
5226
+ * when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
5227
+ * stay total.
3984
5228
  *
3985
5229
  * @param schema - The JSON Schema value to convert
3986
5230
  * @returns The built {@link ContractShape}
@@ -3997,6 +5241,6 @@ function schemaToShape(schema) {
3997
5241
  return schemaNodeToShape(schema, 32, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap());
3998
5242
  }
3999
5243
  //#endregion
4000
- export { FAULT_LIMIT, FORMAT_MAX_LENGTH, FORMAT_PATTERNS, INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT, INFER_ENUM_LIMIT, JSON_SCHEMA_TYPES, PREVIEW_LIMIT, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, buildObjectShape, buildShapeFromNode, canonicalStringify, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, createContract, deriveLengthBounds, deriveRangeBounds, enumOf, enumerableSymbolCount, inferArray, inferObject, inferPrimitiveEnum, inferRecordSamples, inferSamples, inferValue, 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, isValidISOInstant, 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, samplesToFormat, samplesToSchema, sanitizeBudget, schemaNodeToShape, schemaToObject, schemaToParameters, schemaToShape, seededRandom, setOf, shapeToKind, stringOf, stringShape, stringToFormat, transformOf, tupleOf, unifySchemas, unionOf, unionShape, validateShape, valueToSchema, whereOf };
5244
+ export { COMPILE_DEPTH_LIMIT, ContractError, FAULT_LIMIT, FORMAT_MAX_LENGTH, FORMAT_PATTERNS, GENERATION_ATTEMPT_LIMIT, GUARD_DEPTH_LIMIT, INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT, INFER_ENUM_LIMIT, JSON_SCHEMA_TYPES, PREVIEW_LIMIT, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, buildObjectShape, buildShapeFromNode, canonicalStringify, canonicalizeValue, cloneJSONRecord, cloneJSONValue, cloneSchema, cloneShape, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, createContract, deriveLengthBounds, deriveRangeBounds, drawRandom, enumOf, enumerableKeys, enumerableSymbolCount, holds, inferArray, inferObject, inferPrimitiveEnum, inferRecordSamples, inferSamples, inferValue, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isConstructor, isContractError, 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, isValidISOInstant, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, jsonShape, keyOf, lazyOf, literalOf, literalShape, mapOf, matchOf, matchesJSONValue, notOf, nullShape, nullableOf, nullableShape, numberShape, objectShape, omitOf, oneOfShape, optionalOf, optionalShape, orOf, ownShape, 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, samplesToFormat, samplesToSchema, sanitizeBudget, schemaNodeToShape, schemaToObject, schemaToParameters, schemaToShape, seededRandom, setOf, shapeToKind, stringOf, stringShape, stringToFormat, transformOf, tupleOf, unifySchemas, unionOf, unionShape, validateShape, validateShapeDepth, valueToSchema, whereOf };
4001
5245
 
4002
5246
  //# sourceMappingURL=index.js.map