@orkestrel/contract 0.0.6 → 0.0.8

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.
@@ -62,6 +62,7 @@ export declare interface ArrayShape<S extends ContractShape = ContractShape> {
62
62
  * @param items - The element shape
63
63
  * @param options - Optional length bounds and `description`
64
64
  * @returns An array shape
65
+ * @throws {ContractError} When a present bound is not a non-negative safe integer
65
66
  *
66
67
  * @example
67
68
  * ```ts
@@ -82,13 +83,14 @@ export declare interface ArrayShapeOptions {
82
83
  * a throw escape.
83
84
  *
84
85
  * @remarks
85
- * The single sanctioned never-throw boundary for the guards (AGENTS §14). The
86
+ * The sanctioned never-throw boundary for the guards (AGENTS §14). The
86
87
  * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
87
88
  * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
88
89
  * `boolean`. This converts a throwing callback into a `Failure` so the
89
90
  * surrounding guard can treat it as a non-match instead of propagating the
90
91
  * exception, written once and shared rather than copy-pasted as ad-hoc
91
- * `try`/`catch`.
92
+ * `try`/`catch`. The sole hand-written exception is {@link isContractError},
93
+ * whose local boundary avoids an `errors` → `helpers` dependency inversion.
92
94
  *
93
95
  * @param callback - The callback to invoke with no arguments
94
96
  * @returns A `Success` carrying the return value, or a `Failure` carrying the
@@ -151,26 +153,268 @@ export declare interface BooleanShapeOptions {
151
153
  export declare function boundsOf(min?: number, max?: number): Guard<number>;
152
154
 
153
155
  /**
154
- * Render a value as a deterministic, key-sorted JSON string.
156
+ * Build an {@link ObjectShape} from a JSON Schema object node's `properties` /
157
+ * `required` / `additionalProperties` keywords — the object-specialized branch
158
+ * of {@link buildShapeFromNode}.
159
+ *
160
+ * @remarks
161
+ * `properties` (when a record) contributes one child shape per own key, capped
162
+ * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}
163
+ * unless it appears as a string entry of `required`. A property whose value is
164
+ * not itself a record widens to {@link rawShape}. `additionalProperties`:
165
+ * `false` closes the object; a record value recurses into it (`objectShape`
166
+ * validates extras against that shape); anything else — `true`, absent, or
167
+ * malformed — leaves the object OPEN (`true`), matching JSON Schema's own
168
+ * absent-means-open default and the fact that {@link valueToSchema} /
169
+ * {@link samplesToSchema} always emit the keyword explicitly, so an absent
170
+ * value only arises from a hand-written schema. When `properties` has MORE
171
+ * keys than {@link INFER_BREADTH_LIMIT}, the schema's own
172
+ * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —
173
+ * a dropped key's value could otherwise fail a `false` or record-valued rest
174
+ * shape it was never checked against — mirroring {@link inferObject}'s
175
+ * partial-key handling in `inferers.ts`. The accumulator uses a
176
+ * null-prototype record so a property literally named `__proto__` becomes an
177
+ * own data key rather than mutating the prototype, mirroring
178
+ * {@link inferObject} (inferers.ts).
179
+ *
180
+ * @param schema - The object schema node
181
+ * @param depth - Remaining descent budget passed to child properties
182
+ * @param visited - The ancestor set guarding against cycles — recursion
183
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
184
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
185
+ * supported usage
186
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
187
+ * recursion state owned by the {@link schemaToShape} entry point; passing
188
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
189
+ * supported usage
190
+ * @param description - The node's already-extracted `description`, if any
191
+ * @returns The built object shape
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * buildObjectShape(
196
+ * { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
197
+ * INFER_DEPTH_LIMIT,
198
+ * new WeakSet(),
199
+ * new WeakMap(),
200
+ * undefined,
201
+ * )
202
+ * // objectShape({ id: integerShape() }, { additionalProperties: true })
203
+ * ```
204
+ */
205
+ export declare function buildObjectShape(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>, description: string | undefined): ContractShape;
206
+
207
+ /**
208
+ * Build a {@link ContractShape} for one JSON Schema node — the recursive
209
+ * spine of {@link schemaToShape}, shared with per-child recursion via
210
+ * {@link schemaNodeToShape}.
211
+ *
212
+ * @remarks
213
+ * Every keyword is read defensively (the node's static `JSONSchema` type is
214
+ * NOT trusted at runtime — a caller-supplied node may be adversarial), so a
215
+ * malformed keyword falls through to the next rule instead of throwing.
216
+ * Precedence, top-down:
217
+ *
218
+ * 1. `enum` — an array with at least one string/number/boolean entry (finite
219
+ * numbers only) becomes a {@link literalShape} over the filtered entries.
220
+ * Non-primitive / non-finite entries are dropped; an empty result falls
221
+ * through.
222
+ * 2. `oneOf` — an array with at least one record entry becomes an
223
+ * {@link oneOfShape} over the recursively-built variants, provided the
224
+ * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the
225
+ * limit, building a subset union would be strictly narrower than the
226
+ * schema's full union (a value matching only a dropped variant would be
227
+ * wrongly rejected), so the whole node widens to {@link rawShape} instead
228
+ * of sampling a subset.
229
+ * 3. `anyOf` — identically, via {@link unionShape}.
230
+ * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —
231
+ * the matching primitive shape, with length/range bounds derived via
232
+ * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node
233
+ * additionally drops its bounds when they describe an EMPTY integer range
234
+ * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
235
+ * rejects — so the result is always a valid shape.
236
+ * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
237
+ * a record-valued `items` (widening to {@link rawShape} otherwise), with
238
+ * bounds from `minItems` / `maxItems`.
239
+ * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
240
+ * record-valued `properties` — delegates to {@link buildObjectShape}.
241
+ * 7. Everything else — an empty schema, an unrecognized/absent `type`,
242
+ * exhausted depth/breadth, or an attempt failure — widens to
243
+ * {@link rawShape}, whose guard accepts every defined value and whose
244
+ * emitted schema is the same `{}` (plus `description`) the node carried.
245
+ * This is the exact inverse of `{}`, JSON Schema's accept-anything schema,
246
+ * and where the inferers themselves bottom out at their own limits.
247
+ *
248
+ * `format` and `pattern` are NEVER read into the compiled shape — `format` is
249
+ * annotation-only and `pattern` compiling an attacker-supplied string into a
250
+ * `RegExp` is a ReDoS vector. `description`, when a string, carries through to
251
+ * the produced shape's `description` option.
252
+ *
253
+ * @param schema - The schema node to convert
254
+ * @param depth - Remaining descent budget (0 halts recursion with `rawShape({})`)
255
+ * @param visited - The ancestor set guarding against cycles — recursion
256
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
257
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
258
+ * supported usage
259
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache
260
+ * guarding against exponential re-conversion of a
261
+ * shared-reference schema DAG — recursion state owned by the
262
+ * {@link schemaToShape} entry point; passing a shared or
263
+ * pre-populated `WeakMap` changes caching behavior and is not
264
+ * supported usage
265
+ * @returns The built shape for `schema`
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * buildShapeFromNode({ type: 'string', minLength: 1 }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
270
+ * // stringShape({ min: 1 })
271
+ * ```
272
+ */
273
+ export declare function buildShapeFromNode(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>): ContractShape;
274
+
275
+ /**
276
+ * Encode one value as a deterministic, key-sorted JSON string — the recursive
277
+ * spine of {@link canonicalStringify}.
278
+ *
279
+ * @remarks
280
+ * Arrays keep their element order; records sort their own keys before encoding,
281
+ * recursively at every nesting level. Every other value is encoded by
282
+ * `JSON.stringify`, so `NaN` / `±Infinity` collapse to `'null'` and `-0`
283
+ * encodes as `'0'` — the same lossy-but-deterministic mapping real JSON makes.
284
+ *
285
+ * Returns `undefined` for anything JSON cannot encode: `undefined` itself, a
286
+ * function, a symbol, an array hole, or a cyclic back-edge to an ancestor. A
287
+ * container carrying such a member is itself un-encodable and returns
288
+ * `undefined` too, so the result is either a faithful encoding of the WHOLE
289
+ * value or nothing — a partially-encoded key is never emitted. Traversal is NOT
290
+ * contained here: a hostile getter or `Proxy` trap throws through to
291
+ * {@link canonicalStringify}, which owns the single {@link attempt} boundary
292
+ * for the walk.
293
+ *
294
+ * @param value - The value to encode
295
+ * @param ancestors - Objects on the active traversal path, guarding cycles
296
+ * @returns The deterministic encoding, or `undefined` when JSON cannot encode
297
+ * `value`
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * canonicalizeValue({ b: 1, a: 2 }, new WeakSet()) // '{"a":2,"b":1}'
302
+ * canonicalizeValue(undefined, new WeakSet()) // undefined
303
+ * ```
304
+ */
305
+ export declare function canonicalizeValue(value: unknown, ancestors: WeakSet<object>): string | undefined;
306
+
307
+ /**
308
+ * Render a value as a deterministic, key-sorted JSON string — or `undefined`
309
+ * when it has no faithful JSON encoding.
155
310
  *
156
311
  * @remarks
157
312
  * The stable-stringify backing {@link unifySchemas}'s de-duplication and
158
313
  * ordering: unlike `JSON.stringify`, object keys are sorted before encoding
159
314
  * (recursively, at every nesting level), so two structurally-equal
160
315
  * `JSONSchema` fragments built independently always canonicalize to the same
161
- * string. Pure ECMAScript — no `structuredClone`, no `node:*` import.
316
+ * string. Pure host-independent ECMAScript with no environment-specific imports.
317
+ *
318
+ * TOTAL: it NEVER throws, for any input. It returns `undefined` — never a
319
+ * partial or invalid encoding — for every value JSON cannot faithfully encode:
320
+ *
321
+ * - `undefined` itself, a function, a symbol, or an array hole (JSON encodes
322
+ * none of them), at the top level or anywhere inside a container;
323
+ * - a bigint (`JSON.stringify` throws on one);
324
+ * - cyclic input, tracked with the same ancestor-{@link WeakSet} discipline
325
+ * {@link inferArray} / {@link inferObject} use, so a shared (non-cyclic)
326
+ * reference reached twice through different paths still encodes;
327
+ * - hostile traversal — a throwing own-getter, a hostile `ownKeys` trap, or a
328
+ * revoked `Proxy` anywhere in the value — contained via {@link attempt}.
329
+ *
330
+ * A caller therefore treats `undefined` as "this value has no canonical key",
331
+ * never as an encoding: see {@link unifySchemas} (an un-keyed member cannot
332
+ * participate in de-duplication or ordering) and {@link inferPrimitiveEnum} (an
333
+ * un-keyed member makes the slot enum-ineligible).
162
334
  *
163
335
  * @param value - The value to canonicalize (a `JSONSchema` fragment, or any
164
336
  * nested piece of one)
165
- * @returns A deterministic string encoding of `value`
337
+ * @returns A deterministic string encoding of `value`, or `undefined` when JSON
338
+ * cannot encode it
166
339
  *
167
340
  * @example
168
341
  * ```ts
169
342
  * canonicalStringify({ type: 'object', properties: {} }) ===
170
343
  * canonicalStringify({ properties: {}, type: 'object' }) // true
344
+ * canonicalStringify(Number.NaN) // 'null' — JSON.stringify semantics
345
+ * canonicalStringify(undefined) // undefined
346
+ * canonicalStringify(cyclicValue) // undefined
347
+ * ```
348
+ */
349
+ export declare function canonicalStringify(value: unknown): string | undefined;
350
+
351
+ /**
352
+ * Deep-clone a JSON Schema graph into an owned frozen snapshot.
353
+ *
354
+ * @remarks
355
+ * Walks arrays and records iteratively with a memo, preserving shared
356
+ * references and closing cyclic edges onto their cloned nodes. Primitive
357
+ * values and own enumerable string-keyed edges are copied; record nodes use
358
+ * null prototypes, arrays retain only their intrinsic array prototype, and
359
+ * every produced object is frozen after its edges are wired. Hostile traversal
360
+ * throws a clone-coded {@link ContractError}, never a caller-owned raw error.
361
+ *
362
+ * @param schema - The JSON Schema graph to snapshot
363
+ * @returns A deeply cloned and frozen JSON Schema graph
364
+ * @throws {ContractError} When hostile schema traversal prevents ownership
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * const child = { type: 'string' }
369
+ * const clone = cloneSchema({ anyOf: [child, child] })
370
+ * clone.anyOf?.[0] === clone.anyOf?.[1] // true
371
+ * ```
372
+ */
373
+ export declare function cloneSchema(schema: JSONSchema): JSONSchema;
374
+
375
+ /**
376
+ * Deep-clone a contract shape graph into an owned frozen snapshot.
377
+ *
378
+ * @remarks
379
+ * Uses an explicit memo to preserve shared-child identity and close cyclic
380
+ * edges onto their cloned nodes. Shape-node shells are created iteratively,
381
+ * then their structural edges are wired and their copied collections frozen.
382
+ * String patterns are captured by source and flags behind an enumerable
383
+ * accessor that returns a fresh frozen zero-state `RegExp` on every read.
384
+ * A raw schema delegates to {@link cloneSchema}; every shape-graph read is
385
+ * contained, so hostile traversal throws only a clone-coded
386
+ * {@link ContractError}.
387
+ *
388
+ * @param shape - The contract shape graph to snapshot
389
+ * @returns A deeply cloned and frozen shape graph
390
+ * @throws {ContractError} When hostile shape or raw-schema traversal prevents ownership
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * const child = arrayShape(stringShape())
395
+ * const clone = cloneShape(objectShape({ first: child, second: child }))
396
+ * clone.type === 'object' && clone.properties.first === clone.properties.second // true
397
+ * ```
398
+ */
399
+ export declare function cloneShape(shape: StringShape): StringShape;
400
+
401
+ export declare function cloneShape(shape: ContractShape): ContractShape;
402
+
403
+ /**
404
+ * The maximum supported nesting depth of a compiled contract shape, frozen.
405
+ *
406
+ * @remarks
407
+ * {@link validateShape} rejects the next level with a depth-coded
408
+ * {@link ContractError} before recursive artifact compilation begins, so a
409
+ * finite but pathologically deep developer-authored shape fails predictably
410
+ * instead of reaching the JavaScript call-stack limit.
411
+ *
412
+ * @example
413
+ * ```ts
414
+ * COMPILE_DEPTH_LIMIT // 512
171
415
  * ```
172
416
  */
173
- export declare function canonicalStringify(value: unknown): string;
417
+ export declare const COMPILE_DEPTH_LIMIT = 512;
174
418
 
175
419
  /**
176
420
  * Compile a {@link ContractShape} into a deterministic seed value.
@@ -178,18 +422,25 @@ export declare function canonicalStringify(value: unknown): string;
178
422
  * @remarks
179
423
  * The same shape and the same `random` source always produce the same value, so
180
424
  * seed data is reproducible. Defaults to a {@link seededRandom} source seeded
181
- * from the wall clock when none is supplied. Throws on a degenerate empty
182
- * `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose
183
- * generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded
184
- * schema is arbitrary and cannot be auto-generated) — a programmer error that
185
- * cannot generate a value (AGENTS §12). `createContract` runs
425
+ * from the wall clock when none is supplied. Shape-generation failures throw a
426
+ * {@link ContractError} with code `'generate'`; {@link drawRandom} failures use
427
+ * code `'random'` and retain the consuming shape category in context.
428
+ * Failures include a degenerate empty `literalShape` / `unionShape`, a
429
+ * pattern-constrained `stringShape` whose generated sample cannot satisfy the
430
+ * pattern, an invalid random sample, and a `rawShape` whose arbitrary embedded
431
+ * schema cannot be auto-generated. {@link validateShapeDepth} iteratively
432
+ * rejects excessive nesting or cycles before recursive generation begins.
433
+ * `createContract` runs
186
434
  * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /
187
435
  * bounded shape is normally caught there; these throws remain here as defense
188
- * for standalone `compileGenerator` use.
436
+ * for standalone `compileGenerator` use. Union candidates are bounded by
437
+ * {@link GENERATION_ATTEMPT_LIMIT} and accepted only when they satisfy the
438
+ * union's compiled guard.
189
439
  *
190
440
  * @param shape - The shape to generate from
191
441
  * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)
192
442
  * @returns A value matching the shape
443
+ * @throws {ContractError} When the shape or random source cannot produce a valid value
193
444
  *
194
445
  * @example
195
446
  * ```ts
@@ -204,10 +455,14 @@ export declare function compileGenerator(shape: ContractShape, random?: RandomFu
204
455
  * Compile a {@link ContractShape} into a runtime type guard.
205
456
  *
206
457
  * @remarks
207
- * Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,
208
- * `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,
209
- * and `whereOf` for constraint refinement. Like every guard it is total — it
210
- * never throws (AGENTS §14).
458
+ * Reuses the combinators for structural and refined shapes, including
459
+ * {@link literalOf} for SameValueZero literal matching. Compiled object shapes
460
+ * observe own enumerable string keys through {@link enumerableKeys}, matching
461
+ * their parser, reporter, and inference view for both open and closed objects.
462
+ * Like every guard it is total — it never throws (AGENTS §14). The shape is
463
+ * taken through {@link ownShape} first, so an unfrozen caller-owned graph
464
+ * compiles from a snapshot. {@link validateShapeDepth} iteratively rejects
465
+ * excessive nesting or cycles before recursive guard compilation begins.
211
466
  *
212
467
  * @param shape - The shape to compile
213
468
  * @returns A guard narrowing to the shape's inferred type
@@ -232,11 +487,16 @@ export declare function compileGuard(shape: ContractShape): Guard<unknown>;
232
487
  * unchanged, otherwise the first variant that both parses and guards wins.
233
488
  *
234
489
  * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same
235
- * combinators `compileGuard` uses — `stringOf` for a string's length/pattern and
236
- * `boundsOf` for a number's value and an array's length — so a value that coerces
237
- * but violates a bound parses to `undefined`. The result is full parse↔guard
238
- * soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's
239
- * `is`, refinements included.
490
+ * combinators `compileGuard` uses — `stringOf` for a string's length/pattern,
491
+ * `boundsOf` for a number's value and an array's length, and {@link literalOf}
492
+ * for literal membership — so a value that coerces but violates a bound parses
493
+ * to `undefined`. The result is full parse↔guard soundness (AGENTS §14): a
494
+ * non-`undefined` parse always satisfies the contract's `is`, refinements
495
+ * included. Object presence and extra-key processing use the same
496
+ * own-enumerable-string snapshot as the guard, reporter, and inference. The
497
+ * shape is taken through {@link ownShape} first, so an unfrozen caller-owned
498
+ * graph compiles from a snapshot. {@link validateShapeDepth} iteratively
499
+ * rejects excessive nesting or cycles before recursive parser compilation.
240
500
  *
241
501
  * @param shape - The shape to compile
242
502
  * @returns A parser yielding the shape's inferred type or `undefined`
@@ -275,7 +535,8 @@ export declare function compileParser(shape: ContractShape): Parser<unknown>;
275
535
  * open object with a constraining `additionalProperties` shape recurses extras
276
536
  * against it instead. A hostile getter or throwing `Proxy` trap is contained
277
537
  * via {@link attempt} and surfaces as a single top-level type fault, never a
278
- * throw (AGENTS §14).
538
+ * throw (AGENTS §14). {@link validateShapeDepth} iteratively rejects excessive
539
+ * shape nesting or cycles before recursive reporting begins.
279
540
  *
280
541
  * @param shape - The shape to report against
281
542
  * @param value - The value to check
@@ -298,7 +559,10 @@ export declare function compileReporter(shape: ContractShape, value: unknown, pa
298
559
  * @remarks
299
560
  * Object shapes emit `additionalProperties: false` (unless opened) and list only
300
561
  * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
301
- * 'null' }`. Emission only — it never inspects a runtime value.
562
+ * 'null' }`. The result is an owned deeply frozen graph; raw schemas are cloned
563
+ * rather than retained by reference. Emission only — it never inspects a
564
+ * runtime value. {@link validateShapeDepth} iteratively rejects excessive
565
+ * nesting or cycles before recursive emission begins.
302
566
  *
303
567
  * @param shape - The shape to compile
304
568
  * @returns The emitted JSON Schema
@@ -323,14 +587,86 @@ export declare function compileSchema(shape: ContractShape): JSONSchema;
323
587
  */
324
588
  export declare function complementOf<TBase, TExcluded extends TBase>(base: Guard<TBase>, excluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded)): Guard<Exclude<TBase, TExcluded>>;
325
589
 
590
+ /** Machine-readable category carried by a {@link ContractError}. */
591
+ export declare type ContractCode =
592
+ /** Identifies a bound contract error. */
593
+ 'bound'
594
+ /** Identifies a range contract error. */
595
+ | 'range'
596
+ /** Identifies an empty-value contract error. */
597
+ | 'empty'
598
+ /** Identifies a placement contract error. */
599
+ | 'placement'
600
+ /** Identifies a literal contract error. */
601
+ | 'literal'
602
+ /** Identifies a cycle contract error. */
603
+ | 'cycle'
604
+ /** Identifies a pattern contract error. */
605
+ | 'pattern'
606
+ /** Identifies a generation contract error. */
607
+ | 'generate'
608
+ /** Identifies a random-source contract error. */
609
+ | 'random'
610
+ /** Identifies an owned-clone contract error. */
611
+ | 'clone'
612
+ /** Identifies a compilation-depth contract error. */
613
+ | 'depth';
614
+
615
+ /**
616
+ * Error carrying a machine-readable contract category and optional context.
617
+ *
618
+ * @example
619
+ * ```ts
620
+ * const error = new ContractError('Minimum exceeds maximum', {
621
+ * code: 'range',
622
+ * context: { path: ['properties', 'age'] },
623
+ * })
624
+ * ```
625
+ */
626
+ export declare class ContractError extends Error {
627
+ readonly name = "ContractError";
628
+ readonly code: ContractCode;
629
+ readonly context: ContractErrorContext | undefined;
630
+ /**
631
+ * Create a contract error.
632
+ *
633
+ * @param message - Human-readable error description
634
+ * @param options - Machine-readable category, optional context, and optional cause
635
+ */
636
+ constructor(message: string, options: ContractErrorOptions);
637
+ }
638
+
639
+ /** Optional structured details carried by a {@link ContractError}. */
640
+ export declare interface ContractErrorContext {
641
+ /** Location associated with the error. */
642
+ readonly path?: FieldPath;
643
+ /** Shape label associated with the error. */
644
+ readonly shape?: string;
645
+ /** Numeric or textual limit associated with the error. */
646
+ readonly limit?: number | string;
647
+ /** Received-value description associated with the error. */
648
+ readonly received?: string;
649
+ }
650
+
651
+ /** Construction options for a {@link ContractError}. */
652
+ export declare interface ContractErrorOptions {
653
+ /** Machine-readable error category. */
654
+ readonly code: ContractCode;
655
+ /** Optional structured error details. */
656
+ readonly context?: ContractErrorContext;
657
+ /** Optional originating thrown value. */
658
+ readonly cause?: unknown;
659
+ }
660
+
326
661
  /**
327
- * A compiled contract — the four lockstep outputs derived from one shape.
662
+ * A compiled contract — the five lockstep outputs derived from one shape.
328
663
  *
329
664
  * @remarks
330
665
  * Built by `createContract`: `is` narrows, `parse` coerces (returning the typed
331
- * value or `undefined`), `schema` is the emitted JSON Schema, and `generate`
332
- * produces deterministic seed data from a {@link RandomFunction} (defaulting to
333
- * a wall-clock-seeded source when none is supplied).
666
+ * value or `undefined`), `schema` is an owned deeply frozen emitted JSON
667
+ * Schema, `explain` reports the structured faults behind a failed `parse`, and
668
+ * `generate` produces deterministic seed data from a {@link RandomFunction}
669
+ * (defaulting to a wall-clock-seeded source when none is supplied).
334
670
  */
335
671
  export declare interface ContractInterface<T> {
336
672
  readonly schema: JSONSchema;
@@ -358,22 +694,25 @@ export declare interface ContractInterface<T> {
358
694
  *
359
695
  * @remarks
360
696
  * A discriminated union keyed on `type`. Shapes nest (an `ArrayShape` holds an
361
- * element shape, an `ObjectShape` a map of them), so a contract is a finite,
362
- * developer-authored tree — never cyclic.
697
+ * element shape, an `ObjectShape` a map of them). {@link validateShape}
698
+ * enforces an acyclic graph within {@link COMPILE_DEPTH_LIMIT}.
363
699
  */
364
700
  export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | RawShape;
365
701
 
366
702
  /**
367
- * Compile a {@link ContractShape} into a {@link ContractInterface} — the four
703
+ * Compile a {@link ContractShape} into a {@link ContractInterface} — the five
368
704
  * lockstep outputs from one declaration.
369
705
  *
370
706
  * @remarks
371
707
  * Runs {@link validateShape} first — a malformed shape throws immediately
372
- * rather than compiling into a silently-wrong contract (AGENTS §12). Then
373
- * precompiles the schema, guard, and parser once; `generate` walks the shape
374
- * per call with the supplied random source, and `explain` compiles the
708
+ * rather than compiling into a silently-wrong contract (AGENTS §12). It always
709
+ * takes its own {@link cloneShape} snapshot — never merely a frozen node's word
710
+ * — and hands that same graph to every artifact compiler.
711
+ * Then it precompiles the deeply frozen owned schema, guard, and parser once;
712
+ * `generate` walks the
713
+ * snapshot per call with the supplied random source, and `explain` compiles the
375
714
  * diagnostic report via {@link compileReporter} at zero added compile-time cost
376
- * (it re-walks the shape per call, exactly like `generate`).
715
+ * (it re-walks the snapshot per call, exactly like `generate`).
377
716
  *
378
717
  * @param shape - The shape to compile
379
718
  * @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`
@@ -390,6 +729,94 @@ export declare function createContract<S extends ContractShape>(shape: S): Contr
390
729
 
391
730
  export declare function createContract(shape: ContractShape): ContractInterface<unknown>;
392
731
 
732
+ /**
733
+ * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON
734
+ * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).
735
+ *
736
+ * @remarks
737
+ * Total and pure. Either keyword is used only when it is a non-negative
738
+ * safe integer (`Number.isSafeInteger` + `>= 0`); a malformed value (a string,
739
+ * a negative number, `NaN`, `Infinity`, a fraction, or an unsafe integer) is
740
+ * dropped as if absent. When both bounds are present and `min` exceeds `max`,
741
+ * the PAIR is dropped entirely (an unbounded shape is always a legal widening
742
+ * of a contradictory schema).
743
+ *
744
+ * @param min - The raw `minLength` / `minItems` keyword value
745
+ * @param max - The raw `maxLength` / `maxItems` keyword value
746
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
747
+ *
748
+ * @example
749
+ * ```ts
750
+ * deriveLengthBounds(1, 10) // { min: 1, max: 10 }
751
+ * deriveLengthBounds(10, 1) // {} — contradictory, dropped
752
+ * deriveLengthBounds(-1, 10) // { max: 10 } — negative min dropped
753
+ * ```
754
+ */
755
+ export declare function deriveLengthBounds(min: unknown, max: unknown): {
756
+ readonly min?: number;
757
+ readonly max?: number;
758
+ };
759
+
760
+ /**
761
+ * Derive `min`/`max` shape bounds from a pair of finite-number JSON Schema
762
+ * range keywords (`minimum`/`maximum`).
763
+ *
764
+ * @remarks
765
+ * Total and pure. Either keyword is used only when it is a finite number
766
+ * ({@link isFiniteNumber} — rejects `NaN` / `±Infinity` / non-numbers); when
767
+ * both bounds are present and `min` exceeds `max`, the PAIR is dropped
768
+ * entirely, the same contradiction rule {@link deriveLengthBounds} applies.
769
+ *
770
+ * @param min - The raw `minimum` keyword value
771
+ * @param max - The raw `maximum` keyword value
772
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
773
+ *
774
+ * @example
775
+ * ```ts
776
+ * deriveRangeBounds(0, 120) // { min: 0, max: 120 }
777
+ * deriveRangeBounds(5, 1) // {} — contradictory, dropped
778
+ * ```
779
+ */
780
+ export declare function deriveRangeBounds(min: unknown, max: unknown): {
781
+ readonly min?: number;
782
+ readonly max?: number;
783
+ };
784
+
785
+ /**
786
+ * Draw and validate one generator random sample.
787
+ *
788
+ * @param random - The caller-supplied random source
789
+ * @param shape - The shape category consuming the sample
790
+ * @returns A finite sample in `[0, 1)`
791
+ * @throws {ContractError} When the source throws or returns outside `[0, 1)`
792
+ *
793
+ * @example
794
+ * ```ts
795
+ * drawRandom(() => 0.5, 'number') // 0.5
796
+ * ```
797
+ */
798
+ export declare function drawRandom(random: RandomFunction, shape: string): number;
799
+
800
+ /**
801
+ * Snapshot an object's own enumerable string keys through a total boundary.
802
+ *
803
+ * @remarks
804
+ * This is the package-wide runtime property view used by compiled object
805
+ * guards, parsers, reporters, schema inference, and owned schema cloning. It
806
+ * matches the object-key view serialized by `JSON.stringify`: inherited,
807
+ * symbol, and non-enumerable properties are excluded. A hostile Proxy trap
808
+ * returns `undefined` rather than escaping.
809
+ *
810
+ * @param value - The object whose keys to snapshot
811
+ * @returns A frozen owned key list, or `undefined` when enumeration throws
812
+ *
813
+ * @example
814
+ * ```ts
815
+ * enumerableKeys({ visible: 1 }) // ['visible']
816
+ * ```
817
+ */
818
+ export declare function enumerableKeys(value: object): readonly string[] | undefined;
819
+
393
820
  /**
394
821
  * Count the enumerable own-symbol keys on a value.
395
822
  *
@@ -536,9 +963,40 @@ export declare type FromGuards<G extends GuardsShape> = Readonly<{
536
963
  [K in keyof G]: GuardType<G[K]>;
537
964
  }>;
538
965
 
966
+ /**
967
+ * The maximum number of candidate-generation attempts for a constrained
968
+ * generated value, frozen.
969
+ *
970
+ * @remarks
971
+ * Provides one deterministic work bound for generators that must retry a
972
+ * candidate against a contract constraint.
973
+ *
974
+ * @example
975
+ * ```ts
976
+ * GENERATION_ATTEMPT_LIMIT // 32
977
+ * ```
978
+ */
979
+ export declare const GENERATION_ATTEMPT_LIMIT = 32;
980
+
539
981
  /** A runtime type guard: returns `true` when `value` satisfies `T` and narrows it. */
540
982
  export declare type Guard<T> = (value: unknown) => value is T;
541
983
 
984
+ /**
985
+ * The maximum number of active {@link lazyOf} invocations for one lazy guard,
986
+ * frozen.
987
+ *
988
+ * @remarks
989
+ * Bounds explicitly recursive guards before the JavaScript call stack becomes
990
+ * the limiting mechanism. An invocation beyond this depth returns `false`, and
991
+ * the counter unwinds after every contained guard call.
992
+ *
993
+ * @example
994
+ * ```ts
995
+ * GUARD_DEPTH_LIMIT // 512
996
+ * ```
997
+ */
998
+ export declare const GUARD_DEPTH_LIMIT = 512;
999
+
542
1000
  /**
543
1001
  * A mapping of string keys to guards.
544
1002
  *
@@ -550,6 +1008,19 @@ export declare type GuardsShape = Readonly<Record<string, Guard<unknown>>>;
550
1008
  /** Extract the guarded type `T` from a `Guard<T>`. */
551
1009
  export declare type GuardType<G> = G extends Guard<infer T> ? T : never;
552
1010
 
1011
+ /**
1012
+ * Invoke a predicate through the sanctioned never-throw boundary.
1013
+ *
1014
+ * @param callback - The predicate to invoke with no arguments
1015
+ * @returns `true` only when the callback returns the boolean value `true`
1016
+ *
1017
+ * @example
1018
+ * ```ts
1019
+ * holds(() => value instanceof Widget) // false when inspection throws
1020
+ * ```
1021
+ */
1022
+ export declare function holds(callback: () => boolean): boolean;
1023
+
553
1024
  /**
554
1025
  * Infer the static TypeScript type a {@link ContractShape} describes.
555
1026
  *
@@ -734,22 +1205,28 @@ export declare type InferObject<P extends Readonly<Record<string, ContractShape>
734
1205
  * properties.
735
1206
  *
736
1207
  * @remarks
737
- * Own enumerable string keys via `Object.keys`, sorted lexicographically for
738
- * deterministic output, capped at `breadth`. Each property value is read
739
- * through {@link attempt} so a hostile getter cannot escape as a thrown
740
- * error; a property whose value is `undefined` (hostile-getter failure
741
- * included) is treated as ABSENT — it contributes neither a `properties`
742
- * entry nor a `required` entry. Every other present key is required (single-
743
- * value mode). Emits `additionalProperties: false` when `closed`, `true`
744
- * otherwise — mirroring {@link compileSchema}'s object-emission convention —
745
- * EXCEPT when the own-key list exceeds `breadth`: a truncated key list means
746
- * the sampled schema no longer describes every property `value` actually
747
- * carries, so `additionalProperties` is forced to `true` regardless of
748
- * `closed` (a closed schema built from a truncated sample would otherwise
749
- * reject the very object it was inferred from). Depth exhaustion or a cyclic
750
- * re-encounter of `value` both yield `{}`. A same-object re-inference at the
751
- * same remaining `depth` is served from `memo` instead of recomputing
752
- * (guards a shared-reference DAG against exponential blowup).
1208
+ * Own enumerable string keys via {@link enumerableKeys}, sorted
1209
+ * lexicographically for deterministic output, capped at `breadth`. This is the
1210
+ * same property view compiled object guards, parsers, and reporters use. Each
1211
+ * property value is read through {@link attempt} so a hostile getter cannot
1212
+ * escape as a thrown error; a property whose value is `undefined` is DROPPED
1213
+ * — JSON encodes no such property (`JSON.stringify({ a: undefined })` is
1214
+ * `'{}'`), so it contributes neither a `properties` entry nor a `required`
1215
+ * entry. Every other present key is required (single-value mode).
1216
+ *
1217
+ * Emits `additionalProperties: false` when `closed`, `true` otherwise —
1218
+ * mirroring {@link compileSchema}'s object-emission convention — EXCEPT when
1219
+ * the sampled key list no longer describes every key `value` actually carries,
1220
+ * which happens two ways: the own-key list exceeds `breadth` (truncation), or
1221
+ * a key was dropped for holding `undefined`. Either way `additionalProperties`
1222
+ * is forced to `true` regardless of `closed`, because a CLOSED schema built
1223
+ * from an incomplete key list would reject the very object it was inferred
1224
+ * from (`recordOf` rejects any own key the shape does not declare).
1225
+ *
1226
+ * Depth exhaustion or a cyclic re-encounter of `value` both yield `{}`. A
1227
+ * same-object re-inference at the same remaining `depth` is served from `memo`
1228
+ * instead of recomputing (guards a shared-reference DAG against exponential
1229
+ * blowup).
753
1230
  *
754
1231
  * @param value - The record to infer from
755
1232
  * @param depth - Remaining descent budget
@@ -814,6 +1291,12 @@ export declare type InferOpenIndex<A extends boolean | ContractShape> = [A] exte
814
1291
  * `literalShape` emission. Members are sorted by canonical key for
815
1292
  * deterministic output.
816
1293
  *
1294
+ * A member {@link canonicalStringify} cannot key has no identity to
1295
+ * de-duplicate against, so the whole slot is enum-INELIGIBLE and returns
1296
+ * `undefined` — widening to the caller's bare `type` rather than emitting an
1297
+ * `enum` that might silently omit a value. (A string or finite number always
1298
+ * canonicalizes, so this only guards the total contract.)
1299
+ *
817
1300
  * @param values - The collected slot values
818
1301
  * @param limit - The maximum distinct-value count before giving up
819
1302
  * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
@@ -843,14 +1326,20 @@ export declare function inferPrimitiveEnum(values: readonly unknown[], limit: nu
843
1326
  * {@link inferArray}, this path carries no `visited` `WeakSet` — a value
844
1327
  * shared by reference across multiple sample rows is legitimate (not a
845
1328
  * cycle back to an ancestor), so termination on cyclic row data relies on
846
- * the decrementing `depth` budget alone. When the union of sample keys
847
- * exceeds `breadth`, the key list is truncated and `additionalProperties` is
848
- * forced to `true` regardless of `closed` — the same truncation-opens-the-
849
- * schema rule {@link inferObject} applies, so a closed schema built from a
850
- * truncated key union never rejects the very rows it was inferred from. A
851
- * hostile getter on ONE sample row drops that key for ALL rows (the whole
852
- * per-key value collection is a single {@link attempt}-contained walk) —
853
- * this is a deliberate all-or-nothing scope, not a per-row partial failure.
1329
+ * the decrementing `depth` budget alone.
1330
+ *
1331
+ * `additionalProperties` is forced to `true` regardless of `closed` whenever
1332
+ * the declared key list stops describing every key the rows carry — the same
1333
+ * incomplete-sample-opens-the-schema rule {@link inferObject} applies, so a
1334
+ * closed schema never rejects the very rows it was inferred from. That happens
1335
+ * three ways: the union of sample keys exceeds `breadth` (truncation); a
1336
+ * hostile getter defeats a key's value walk (which drops that key for ALL
1337
+ * rows — a deliberate all-or-nothing scope, not a per-row partial failure);
1338
+ * or some row carries the key as an own property holding `undefined`, which
1339
+ * JSON encodes as no property at all, so the key is dropped rather than
1340
+ * declared with a shape that row would fail. When the KEY walk itself fails
1341
+ * (a hostile `ownKeys` trap on any row), nothing is known and the whole slot
1342
+ * widens to `{}`.
854
1343
  *
855
1344
  * @param samples - The plain-record samples
856
1345
  * @param depth - Remaining descent budget
@@ -913,13 +1402,21 @@ export declare type InferUnion<V extends readonly ContractShape[]> = V extends r
913
1402
  * @remarks
914
1403
  * Total: never throws, and terminates on cyclic input via `visited`. Leaf
915
1404
  * classification order: `null`, boolean, integer (`Number.isInteger`
916
- * semantics — `-0` counts), finite non-integer number, non-finite number
917
- * (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
1405
+ * semantics — `-0` counts), finite non-integer number, string (gaining a
918
1406
  * `format` keyword when `format` is on and {@link stringToFormat} matches),
919
1407
  * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
920
- * plus `format: 'date-time'` when `format` is on); everything else
921
- * (function, symbol, bigint, `undefined`, and other non-plain objects such as
922
- * `Map` / `Set`) is the empty accept-anything schema `{}`.
1408
+ * plus `format: 'date-time'` when `format` is on); everything else — a
1409
+ * NON-FINITE number (`NaN` / `±Infinity`), a function, a symbol, a bigint,
1410
+ * `undefined`, and other non-plain objects such as `Map` / `Set` — is the
1411
+ * empty accept-anything schema `{}`.
1412
+ *
1413
+ * A non-finite number bottoms out with the other JSON-inexpressible values on
1414
+ * purpose: JSON carries no `NaN` / `±Infinity` (`JSON.stringify(Number.NaN)`
1415
+ * is `'null'`), so `{ type: 'number' }` would ASSERT something a JSON Schema
1416
+ * validator rejects — and the shape {@link schemaToShape} builds from it would
1417
+ * reject the very sample it was inferred from. `{}` is the truthful
1418
+ * description, and it inverts to an accept-anything shape, keeping
1419
+ * `compileGuard(schemaToShape(valueToSchema(v)))(v)` true.
923
1420
  *
924
1421
  * @param value - The value to classify
925
1422
  * @param depth - Remaining descent budget (0 halts recursion with `{}`)
@@ -963,6 +1460,7 @@ export declare function instanceOf<C extends abstract new (...args: never) => ob
963
1460
  *
964
1461
  * @param options - Optional bounds and `description` (no `integer` key)
965
1462
  * @returns An integer number shape
1463
+ * @throws {ContractError} When a present bound is not finite
966
1464
  */
967
1465
  export declare function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape;
968
1466
 
@@ -1114,6 +1612,20 @@ export declare function isBoolean(value: unknown): value is boolean;
1114
1612
  */
1115
1613
  export declare function isConstructor(value: unknown): value is AnyConstructor<object>;
1116
1614
 
1615
+ /**
1616
+ * Determine whether an unknown value is a {@link ContractError}.
1617
+ *
1618
+ * @param value - The value to inspect
1619
+ * @returns `true` only when the value is a `ContractError`
1620
+ *
1621
+ * @example
1622
+ * ```ts
1623
+ * isContractError(new ContractError('Invalid shape', { code: 'placement' })) // true
1624
+ * isContractError(new Error('Invalid shape')) // false
1625
+ * ```
1626
+ */
1627
+ export declare function isContractError(value: unknown): value is ContractError;
1628
+
1117
1629
  /** Determine whether a value is a `DataView`.
1118
1630
  *
1119
1631
  * @example
@@ -1276,7 +1788,7 @@ export declare function isGeneratorFunction(value: unknown): value is (...args:
1276
1788
  * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
1277
1789
  * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
1278
1790
  * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
1279
- * wraps the check in {@link attempt} (see ./helpers.js) so any such throw
1791
+ * wraps the check in {@link holds} (see ./helpers.js) so any such throw
1280
1792
  * yields `false` instead of escaping.
1281
1793
  *
1282
1794
  * @param value - The value to test
@@ -1382,7 +1894,7 @@ export declare function isJSONPrimitive(value: unknown): value is JSONPrimitive;
1382
1894
  * Total guard: never throws, returns `false` for cycles, functions, `Date`
1383
1895
  * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records
1384
1896
  * are walked with an ancestor set so recursive input fails instead of hanging.
1385
- * The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a
1897
+ * The whole walk runs inside `holds` (AGENTS §14): a hostile getter on a
1386
1898
  * record property, or a revoked `Proxy` anywhere in the structure, is caught
1387
1899
  * and yields `false` instead of escaping as a thrown error.
1388
1900
  *
@@ -1576,7 +2088,7 @@ export declare function isPromiseLike<T = unknown>(value: unknown): value is Pro
1576
2088
  * above `null`. Arrays and class instances are still rejected: an array's
1577
2089
  * prototype chain runs through `Array.prototype` before `null`, and a class
1578
2090
  * instance's runs through the class's own prototype. The whole body runs
1579
- * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
2091
+ * inside `holds` (AGENTS §14) so a revoked `Proxy` or a hostile
1580
2092
  * `getPrototypeOf` trap cannot escape as a thrown error.
1581
2093
  *
1582
2094
  * @example
@@ -1785,22 +2297,6 @@ export declare function isZeroArgAsyncGenerator(value: unknown): value is () =>
1785
2297
  */
1786
2298
  export declare function isZeroArgGenerator(value: unknown): value is () => Generator<unknown, unknown, unknown>;
1787
2299
 
1788
- /**
1789
- * Build a guard that accepts any iterable whose every element satisfies
1790
- * `elementGuard`.
1791
- *
1792
- * @example
1793
- * ```ts
1794
- * const isNumberIterable = iterableOf(isNumber)
1795
- * isNumberIterable([1, 2, 3]) // true
1796
- * isNumberIterable(new Set([1, 2])) // true
1797
- * isNumberIterable([1, 'two']) // false
1798
- * ```
1799
- */
1800
- export declare function iterableOf<T>(elementGuard: Guard<T>): Guard<Iterable<T>>;
1801
-
1802
- export declare function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>>;
1803
-
1804
2300
  /**
1805
2301
  * The seven standard JSON Schema `type` names, frozen.
1806
2302
  *
@@ -1842,8 +2338,9 @@ export declare type JSONPrimitive = string | number | boolean | null;
1842
2338
  * emitted by the {@link stringToFormat} / {@link samplesToFormat} inference
1843
2339
  * heuristics (`valueToSchema` / `samplesToSchema`), never by `compileSchema`.
1844
2340
  * Recursive via `items` / `properties` / `additionalProperties` / `anyOf` /
1845
- * `oneOf`, but every walk is over a finite, developer-authored shape — there
1846
- * is no cycle/depth risk.
2341
+ * `oneOf`. {@link createContract} owns and validates developer-authored shape
2342
+ * graphs; cycles and nesting past {@link COMPILE_DEPTH_LIMIT} fail with a coded
2343
+ * {@link ContractError} before artifact compilation.
1847
2344
  */
1848
2345
  export declare interface JSONSchema {
1849
2346
  readonly type?: JSONSchemaType;
@@ -1876,7 +2373,7 @@ export declare type JSONSchemaType = 'null' | 'boolean' | 'object' | 'array' | '
1876
2373
  * functions, `NaN`, and `±Infinity`); the parser gates through that guard; the
1877
2374
  * schema is the empty schema `{}` (matches any JSON instance); the generator
1878
2375
  * emits a small deterministic {@link JSONValue}. Unlike {@link RawShape}, whose
1879
- * guard accepts anything, this shape validates that a value is real JSON.
2376
+ * guard accepts every defined value, this shape validates that a value is real JSON.
1880
2377
  */
1881
2378
  export declare interface JSONShape {
1882
2379
  readonly type: 'json';
@@ -1888,8 +2385,8 @@ export declare interface JSONShape {
1888
2385
  *
1889
2386
  * @remarks
1890
2387
  * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
1891
- * schema fragment and accepts anything at runtime, while `jsonShape` validates
1892
- * that a value is real JSON (via {@link isJSONValue}).
2388
+ * schema fragment and accepts every defined value at runtime, while `jsonShape`
2389
+ * validates that a value is real JSON (via {@link isJSONValue}).
1893
2390
  *
1894
2391
  * @param options - Optional `description`
1895
2392
  * @returns A JSON passthrough shape
@@ -1952,10 +2449,10 @@ export declare function keyOf<const O extends Readonly<Record<PropertyKey, unkno
1952
2449
  * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard
1953
2450
  * it resolves to) is contained and reported as a non-match.
1954
2451
  *
1955
- * A recursive guard built this way has no cycle/depth detection: a cyclic or
1956
- * pathologically deep input is stack-bounded — the overflow is contained and the
1957
- * guard returns `false` rather than throwing, but it is not validated correctly
1958
- * past that bound.
2452
+ * Each lazy guard tracks its active invocation depth. An invocation that would
2453
+ * exceed {@link GUARD_DEPTH_LIMIT} returns `false` before resolving `thunk`; the
2454
+ * counter always unwinds after the contained call, so one deep or cyclic input
2455
+ * cannot poison later guard calls.
1959
2456
  *
1960
2457
  * @example
1961
2458
  * ```ts
@@ -1967,16 +2464,32 @@ export declare function keyOf<const O extends Readonly<Record<PropertyKey, unkno
1967
2464
  export declare function lazyOf<T>(thunk: () => Guard<T>): Guard<T>;
1968
2465
 
1969
2466
  /**
1970
- * Build a guard that accepts values identical (via `Object.is`) to one of the
1971
- * provided literal primitives.
2467
+ * Build a guard that accepts a provided literal primitive using SameValueZero
2468
+ * comparison.
2469
+ *
2470
+ * @remarks
2471
+ * Signed zero compares equal, while `NaN` compares equal to `NaN`. Two call
2472
+ * forms, one meaning: list the literals inline, or hand in one array of them.
2473
+ * The array form exists for a vocabulary that is machine-generated rather than
2474
+ * hand-written — a `literalShape` built from an untrusted schema's `enum`, say
2475
+ * — where spreading a list of tens of thousands of entries would exhaust the
2476
+ * engine's argument limit. `compileGuard` / `compileParser` / `compileReporter`
2477
+ * take the array form for exactly that reason.
2478
+ *
2479
+ * @param literals - The permitted literal primitives, listed inline or as one array
2480
+ * @returns A guard narrowing to the provided literal union
1972
2481
  *
1973
2482
  * @example
1974
2483
  * ```ts
1975
2484
  * const isRole = literalOf('admin', 'member', 'guest')
1976
2485
  * isRole('admin') // true
1977
2486
  * isRole('owner') // false
2487
+ *
2488
+ * const isSameRole = literalOf(['admin', 'member', 'guest']) // the same guard, from an array
1978
2489
  * ```
1979
2490
  */
2491
+ export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(literals: Literals): Guard<Literals[number]>;
2492
+
1980
2493
  export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(...literals: Literals): Guard<Literals[number]>;
1981
2494
 
1982
2495
  /** A literal shape — accepts exactly one of a fixed set of primitive values. */
@@ -2001,7 +2514,7 @@ export declare interface LiteralShape<T extends readonly (string | number | bool
2001
2514
  * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
2002
2515
  * ```
2003
2516
  */
2004
- export declare function literalShape<const T extends readonly (string | number | boolean)[]>(values: T, options?: LiteralShapeOptions): LiteralShape<T>;
2517
+ export declare function literalShape<const T extends readonly (string | number | boolean)[]>(values: T, options?: LiteralShapeOptions): LiteralShape<Readonly<T>>;
2005
2518
 
2006
2519
  /** Options for {@link LiteralShape} (via `literalShape`). */
2007
2520
  export declare interface LiteralShapeOptions {
@@ -2023,9 +2536,38 @@ export declare function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): G
2023
2536
 
2024
2537
  export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePredicate: (value: unknown) => boolean): Guard<ReadonlyMap<unknown, unknown>>;
2025
2538
 
2539
+ /**
2540
+ * Match an unknown value against the recursive JSON value structure.
2541
+ *
2542
+ * @remarks
2543
+ * The caller-owned ancestor set tracks only the active traversal path, so
2544
+ * cycles fail while shared references across sibling branches remain valid.
2545
+ * The set belongs to one traversal from one entry point; passing a shared or
2546
+ * pre-populated set is unsupported. Arrays and plain records recurse through
2547
+ * this helper; class instances and non-finite numbers are rejected.
2548
+ *
2549
+ * @param entry - The value to inspect
2550
+ * @param ancestors - Objects on the active traversal path
2551
+ * @returns `true` when the value is a cycle-free JSON value
2552
+ *
2553
+ * @example
2554
+ * ```ts
2555
+ * matchesJSONValue({ nested: [1, 'x', null] }, new WeakSet()) // true
2556
+ * matchesJSONValue(Number.NaN, new WeakSet()) // false
2557
+ * ```
2558
+ */
2559
+ export declare function matchesJSONValue(entry: unknown, ancestors: WeakSet<object>): boolean;
2560
+
2026
2561
  /**
2027
2562
  * Build a guard that accepts strings matching a regular expression.
2028
2563
  *
2564
+ * @remarks
2565
+ * Clones the pattern for the guard and strips the stateful `g` / `y` flags, so
2566
+ * repeated checks are stable and never change the caller's `lastIndex`.
2567
+ *
2568
+ * @param pattern - The regular expression to own and apply
2569
+ * @returns A stateless string guard
2570
+ *
2029
2571
  * @example
2030
2572
  * ```ts
2031
2573
  * const isHex = matchOf(/^[0-9a-f]+$/)
@@ -2120,6 +2662,7 @@ export declare interface NumberShape {
2120
2662
  *
2121
2663
  * @param options - Optional bounds (`min` / `max`), `integer`, and `description`
2122
2664
  * @returns A number shape
2665
+ * @throws {ContractError} When a present bound is not finite
2123
2666
  *
2124
2667
  * @example
2125
2668
  * ```ts
@@ -2226,7 +2769,7 @@ export declare function omitOf<S extends GuardsShape, K extends ReadonlyArray<ke
2226
2769
  * // 3.5 passes — matches numberShape only
2227
2770
  * ```
2228
2771
  */
2229
- export declare function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V>;
2772
+ export declare function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<Readonly<V>>;
2230
2773
 
2231
2774
  /**
2232
2775
  * Like {@link FromGuards}, but every key listed in `K` becomes a true optional
@@ -2291,6 +2834,38 @@ export declare function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B
2291
2834
 
2292
2835
  export declare function orOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard<unknown>;
2293
2836
 
2837
+ /**
2838
+ * Take ownership of a contract shape node — the node itself when it is already
2839
+ * frozen, otherwise a {@link cloneShape} snapshot of its graph.
2840
+ *
2841
+ * @remarks
2842
+ * Builder- and `cloneShape`-produced frozen means owned: those nodes have frozen
2843
+ * `properties` / `variants` / `values` collections and pattern accessors that
2844
+ * return fresh frozen snapshots, so they cannot drift under a caller who still
2845
+ * holds an input reference or a previously read pattern. `Object.freeze` on a
2846
+ * hand-authored pattern shape is not an ownership marker because it cannot
2847
+ * protect `RegExp` internal slots; leave that shape unfrozen for this function
2848
+ * to snapshot, or pass it through {@link cloneShape} first.
2849
+ *
2850
+ * Every compiler entry point (`compileSchema` / `compileGuard` /
2851
+ * `compileParser` / `compileGenerator` / `compileReporter`) opens with this
2852
+ * call, and the check applies per node as the recursion descends: a frozen
2853
+ * parent is trusted for its own fields while each child is owned again at its
2854
+ * own level, so a hand-assembled graph that froze only part of itself is still
2855
+ * compiled from owned data.
2856
+ *
2857
+ * @param shape - The contract shape to own
2858
+ * @returns The shape itself when frozen, otherwise a deeply cloned frozen snapshot
2859
+ *
2860
+ * @example
2861
+ * ```ts
2862
+ * const authored = stringShape() // builders freeze
2863
+ * ownShape(authored) === authored // true
2864
+ * ownShape({ type: 'string' }) // a frozen snapshot — the literal is caller-owned
2865
+ * ```
2866
+ */
2867
+ export declare function ownShape(shape: ContractShape): ContractShape;
2868
+
2294
2869
  /**
2295
2870
  * Parse an unknown value to an array — the input reference, never cloned —
2296
2871
  * optionally guarding every element.
@@ -2367,14 +2942,16 @@ export declare function parseBooleanField(record: Record<string, unknown>, path:
2367
2942
  * Parse an unknown value as one of the allowed literal primitives.
2368
2943
  *
2369
2944
  * @remarks
2370
- * Pairs with {@link literalOf} — both match by `Object.is`, so the
2945
+ * Pairs with {@link literalOf} — both match by SameValueZero, so the
2371
2946
  * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
2372
2947
  * (string, number, or boolean), not only strings. Matching is identity, never
2373
- * cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
2948
+ * cross-type coercion: `parseEnum('1', [1])` stays `undefined`. The allowed
2949
+ * values are copied into an owned frozen `Set`; hostile iteration returns
2950
+ * `undefined` rather than escaping.
2374
2951
  *
2375
2952
  * @param value - The value to parse
2376
2953
  * @param allowed - The permitted literal values
2377
- * @returns The matched literal (by identity), or `undefined`
2954
+ * @returns The input when it matches an allowed literal by SameValueZero, or `undefined`
2378
2955
  *
2379
2956
  * @example
2380
2957
  * ```ts
@@ -2384,6 +2961,8 @@ export declare function parseBooleanField(record: Record<string, unknown>, path:
2384
2961
  */
2385
2962
  export declare function parseEnum<const T extends string | number | boolean>(value: unknown, allowed: readonly T[]): T | undefined;
2386
2963
 
2964
+ export declare function parseEnum(value: unknown, allowed: readonly (string | number | boolean)[]): string | number | boolean | undefined;
2965
+
2387
2966
  /**
2388
2967
  * Read and parse an enum field from a record by key or nested key path.
2389
2968
  *
@@ -2687,8 +3266,11 @@ export declare type RandomFunction = () => number;
2687
3266
  * A raw JSON Schema passthrough — embeds a schema fragment directly.
2688
3267
  *
2689
3268
  * @remarks
2690
- * For values the shape DSL can't express. The compiled guard accepts any value
2691
- * and the parser passes it through unchanged; the schema is emitted verbatim.
3269
+ * For values the shape DSL can't express. The compiled guard accepts every
3270
+ * top-level value except `undefined`, which is reserved as the parser failure
3271
+ * sentinel. Wrap the shape with {@link OptionalShape} to admit absence. Defined
3272
+ * values pass through unchanged, and the schema is emitted structurally
3273
+ * verbatim as an owned deeply frozen copy.
2692
3274
  */
2693
3275
  export declare interface RawShape {
2694
3276
  readonly type: 'raw';
@@ -2699,11 +3281,18 @@ export declare interface RawShape {
2699
3281
  * Build a {@link RawShape} from a JSON Schema fragment.
2700
3282
  *
2701
3283
  * @remarks
2702
- * For values the shape DSL can't express. The compiled guard accepts any value;
2703
- * the parser passes it through; the schema is emitted verbatim.
3284
+ * For values the shape DSL can't express. The compiled guard accepts every
3285
+ * DEFINED value — `undefined` alone fails, because it is the parser's failure
3286
+ * sentinel; wrap the shape in {@link optionalShape} to admit absence. The
3287
+ * parser passes a defined value through unchanged, and the fragment is
3288
+ * deep-cloned into an owned frozen snapshot ({@link cloneSchema}), so
3289
+ * `rawShape(fragment).schema !== fragment` and later edits to the caller's
3290
+ * fragment cannot reach the shape. `compileSchema` re-emits that snapshot
3291
+ * structurally verbatim; `compileGenerator` throws, since an arbitrary embedded
3292
+ * schema has no auto-generatable sample.
2704
3293
  *
2705
3294
  * @param schema - The JSON Schema fragment to embed
2706
- * @returns A raw shape
3295
+ * @returns A raw shape owning a frozen copy of the fragment
2707
3296
  *
2708
3297
  * @example
2709
3298
  * ```ts
@@ -2869,6 +3458,46 @@ export declare function sanitizeBudget(value: number | undefined, fallback: numb
2869
3458
  */
2870
3459
  export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'email' | 'uri';
2871
3460
 
3461
+ /**
3462
+ * Convert one JSON Schema node into a {@link ContractShape} — the recursion
3463
+ * entry point {@link schemaToShape} and {@link buildShapeFromNode} share for
3464
+ * every child (`items`, `properties` values, `additionalProperties`,
3465
+ * `oneOf` / `anyOf` variants).
3466
+ *
3467
+ * @remarks
3468
+ * Total: never throws. Guards depth exhaustion, a non-record node (the
3469
+ * node's static `JSONSchema` type is not trusted at runtime), and a cyclic
3470
+ * re-encounter of `schema` — all three widen to {@link rawShape}. The
3471
+ * ancestor set is added to and removed from around the WHOLE subtree
3472
+ * conversion (not permanently), so a DAG-shaped schema reached twice via two
3473
+ * different, non-cyclic paths does not false-positive as a cycle. The
3474
+ * subtree conversion itself runs inside {@link attempt}, so a hostile
3475
+ * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
3476
+ * — it degrades to {@link rawShape} instead. A same-node re-conversion at
3477
+ * the same remaining `depth` is served from `memo` (guards a
3478
+ * shared-reference schema DAG against exponential blowup), mirroring
3479
+ * {@link inferObject} / {@link inferArray} (inferers.ts).
3480
+ *
3481
+ * @param schema - The schema node to convert
3482
+ * @param depth - Remaining descent budget
3483
+ * @param visited - The ancestor set guarding against cycles — recursion
3484
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3485
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3486
+ * supported usage
3487
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
3488
+ * recursion state owned by the {@link schemaToShape} entry point; passing
3489
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
3490
+ * supported usage
3491
+ * @returns The built shape for `schema`, or {@link rawShape} on any failure
3492
+ *
3493
+ * @example
3494
+ * ```ts
3495
+ * schemaNodeToShape({ type: 'boolean' }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
3496
+ * // booleanShape()
3497
+ * ```
3498
+ */
3499
+ export declare function schemaNodeToShape(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>): ContractShape;
3500
+
2872
3501
  /**
2873
3502
  * Wrap a non-object `JSONSchema` root in a single-property object schema, so
2874
3503
  * an inferred primitive/array/union schema can flow into {@link schemaToParameters}
@@ -2921,6 +3550,68 @@ export declare function schemaToObject(schema: JSONSchema): JSONSchema;
2921
3550
  */
2922
3551
  export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<string, unknown>> | undefined;
2923
3552
 
3553
+ /**
3554
+ * Convert a runtime `JSONSchema` value into a validating {@link ContractShape}
3555
+ * — the inverse of {@link compileSchema}, and the validating sibling of
3556
+ * {@link rawShape} (which embeds a schema fragment WITHOUT validating it).
3557
+ *
3558
+ * @remarks
3559
+ * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
3560
+ * outright hostile (throwing-getter Proxy) `schema` value all degrade to
3561
+ * {@link rawShape} rather than escaping as an error, so
3562
+ * `createContract(schemaToShape(x))` is safe to call for any `x`. See
3563
+ * {@link buildShapeFromNode} for the exact per-keyword precedence.
3564
+ *
3565
+ * `format` and `pattern` are NEVER asserted by the compiled shape — `format`
3566
+ * is annotation-only (per the JSON Schema spec, it never narrows validation
3567
+ * on its own) and compiling an attacker-controlled `pattern` string into a
3568
+ * `RegExp` is a ReDoS vector; both keywords are read only far enough to be
3569
+ * ignored. Any node the walk cannot express — an empty `{}`, an
3570
+ * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a
3571
+ * cyclic re-encounter — widens to {@link rawShape} (accept any defined
3572
+ * value), never narrows.
3573
+ *
3574
+ * ROUND TRIP: `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` for
3575
+ * every `v` — including the values no JSON Schema keyword describes (`NaN`,
3576
+ * `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a
3577
+ * bigint, a cyclic or hostile host), which infer `{}` and widen back to an
3578
+ * accept-anything {@link rawShape}. Widening is the only source of looseness.
3579
+ * The law has three explicit host limits:
3580
+ *
3581
+ * - **Absence.** `undefined` is not a value: no compiled guard accepts it
3582
+ * (`rawShape` reserves it as the parser failure sentinel). So `undefined`
3583
+ * itself, an array element holding it, and an array HOLE (`arrayOf` requires
3584
+ * every index to be an own property, the same rule `isJSONValue` applies)
3585
+ * all fall outside the law. An OBJECT property holding `undefined` does not:
3586
+ * `valueToSchema` drops the key and opens the object, so the source object
3587
+ * is still accepted.
3588
+ * - **`Date` serialization.** A `Date` infers the schema of its JSON form
3589
+ * (`{ type: 'string' }`, plus `format: 'date-time'` when `format` is on), so
3590
+ * the law applies to `date.toISOString()` rather than the runtime instance.
3591
+ * - **Stateful access.** A getter whose result changes between inference and
3592
+ * guard evaluation can invalidate the sampled fact. Likewise, an array that
3593
+ * overrides iteration behavior can present different elements to the two
3594
+ * phases. The law applies only while the sampled host's observable own
3595
+ * enumerable string properties and array iteration remain stable.
3596
+ *
3597
+ * A widened node cannot be auto-generated: `rawShape` embeds an arbitrary
3598
+ * schema fragment, so `createContract(schemaToShape(x)).generate()` throws
3599
+ * when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
3600
+ * stay total.
3601
+ *
3602
+ * @param schema - The JSON Schema value to convert
3603
+ * @returns The built {@link ContractShape}
3604
+ *
3605
+ * @example
3606
+ * ```ts
3607
+ * const schema = samplesToSchema([{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }])
3608
+ * const contract = createContract(schemaToShape(schema))
3609
+ * contract.parse({ id: 3, name: 'Alan' }) // { id: 3, name: 'Alan' }
3610
+ * contract.parse({ id: 'nope' }) // undefined
3611
+ * ```
3612
+ */
3613
+ export declare function schemaToShape(schema: JSONSchema): ContractShape;
3614
+
2924
3615
  /**
2925
3616
  * Build a deterministic pseudo-random source seeded from a single number.
2926
3617
  *
@@ -2984,10 +3675,14 @@ export declare function shapeToKind(shape: ContractShape): FaultKind;
2984
3675
  *
2985
3676
  * @remarks
2986
3677
  * Composes {@link isString} with {@link boundsOf} on the string's `.length` and
2987
- * an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns
2988
- * the bare {@link isString} guard (the unconstrained fast path), so an
2989
- * unrefined string leaf pays no wrapping cost. The single source of the string
2990
- * refinement shared by the compiled guard and parser (compilers.ts).
3678
+ * an owned stateless pattern (the same refinement {@link matchOf} performs).
3679
+ * When all three options are absent it returns the bare {@link isString} guard
3680
+ * (the unconstrained fast path), so an unrefined string leaf pays no wrapping
3681
+ * cost. The single source of the string refinement shared by the compiled guard
3682
+ * and parser (compilers.ts).
3683
+ *
3684
+ * @param options - Optional length bounds and regular expression refinement
3685
+ * @returns A string guard enforcing the requested refinements
2991
3686
  *
2992
3687
  * @example
2993
3688
  * ```ts
@@ -3010,6 +3705,7 @@ export declare interface StringShape {
3010
3705
  readonly type: 'string';
3011
3706
  readonly min?: number;
3012
3707
  readonly max?: number;
3708
+ /** A pattern constraint; builders and cloners expose an owned fresh frozen zero-state copy per read. */
3013
3709
  readonly pattern?: RegExp;
3014
3710
  readonly description?: string;
3015
3711
  }
@@ -3017,8 +3713,14 @@ export declare interface StringShape {
3017
3713
  /**
3018
3714
  * Build a string {@link StringShape}.
3019
3715
  *
3716
+ * @remarks
3717
+ * A supplied pattern is captured by source and flags. The shape exposes a fresh
3718
+ * frozen zero-state `RegExp` on every `pattern` read, so neither the caller's
3719
+ * original nor a value read from the shape can drift later compiled artifacts.
3720
+ *
3020
3721
  * @param options - Optional length (`min` / `max`), `pattern`, and `description`
3021
3722
  * @returns A string shape
3723
+ * @throws {ContractError} When a present bound is invalid or `pattern` has flags
3022
3724
  *
3023
3725
  * @example
3024
3726
  * ```ts
@@ -3079,9 +3781,8 @@ export declare interface Success<T> {
3079
3781
  *
3080
3782
  * @remarks
3081
3783
  * `project` is a plain `(value: T) => U`. Per §14 the returned guard never
3082
- * throws: a throw from `project` is contained and reported as a non-match.
3083
- * `target` is itself a Guard (already §14-bound), so it stays outside the
3084
- * contained region. (Unlike the reference implementation, there is no
3784
+ * throws: a throw from `project` or `target` is contained and reported as a
3785
+ * non-match. (Unlike the reference implementation, there is no
3085
3786
  * "curried projector" branch — a projection that legitimately returns a function
3086
3787
  * would be double-invoked under that scheme. Compose explicitly if you need it.)
3087
3788
  *
@@ -3132,6 +3833,14 @@ export declare function tupleOf(...predicates: ReadonlyArray<(value: unknown) =>
3132
3833
  * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
3133
3834
  * An empty input list returns the empty accept-anything schema `{}`.
3134
3835
  *
3836
+ * A member {@link canonicalStringify} cannot key — a cyclic, hostile, or
3837
+ * otherwise JSON-inexpressible fragment, which only a direct caller can supply
3838
+ * since the inferers always build plain encodable fragments — has NO
3839
+ * de-duplication key, so it can participate in neither de-duplication nor the
3840
+ * canonical-key ordering. It is KEPT (dropping a variant would narrow the
3841
+ * union, and unification only ever widens), appended in input order after the
3842
+ * sorted keyed members, so the result stays total and deterministic.
3843
+ *
3135
3844
  * @param schemas - The schemas to unify
3136
3845
  * @returns The unified schema
3137
3846
  *
@@ -3161,8 +3870,9 @@ export declare function unionOf(...predicates: ReadonlyArray<(value: unknown) =>
3161
3870
  * A union shape — accepts a value matching any one variant (first match wins).
3162
3871
  *
3163
3872
  * @remarks
3164
- * `mode` selects the emitted JSON Schema keyword: `'anyOf'` (default) or
3165
- * `'oneOf'`. Runtime behavior is identical.
3873
+ * `mode` selects the emitted JSON Schema keyword and runtime matching rule:
3874
+ * `'anyOf'` (default) accepts the first matching variant, while `'oneOf'`
3875
+ * requires exactly one variant to match.
3166
3876
  */
3167
3877
  export declare interface UnionShape<V extends readonly ContractShape[] = readonly ContractShape[]> {
3168
3878
  readonly type: 'union';
@@ -3183,19 +3893,21 @@ export declare interface UnionShape<V extends readonly ContractShape[] = readonl
3183
3893
  * // Infer<typeof id> = string | number
3184
3894
  * ```
3185
3895
  */
3186
- export declare function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V>;
3896
+ export declare function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<Readonly<V>>;
3187
3897
 
3188
3898
  /** Convert a union type to an intersection type. */
3189
3899
  export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
3190
3900
 
3191
3901
  /**
3192
- * Validate that a {@link ContractShape} tree is well-formed — a pure recursive
3193
- * prepass run before compilation.
3902
+ * Validate that a {@link ContractShape} graph is well-formed before
3903
+ * compilation.
3194
3904
  *
3195
3905
  * @remarks
3196
3906
  * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
3197
- * throws a plain `Error` immediately rather than surfacing as a silently-wrong
3198
- * guard, parser, schema, or generator later. Checks, recursively:
3907
+ * throws a coded {@link ContractError} immediately rather than surfacing as a
3908
+ * silently-wrong guard, parser, schema, or generator later. The iterative walk
3909
+ * tracks active ancestors, so a structural cycle reports its precise path while
3910
+ * a shared child reached through separate paths remains legal. Checks:
3199
3911
  *
3200
3912
  * - An {@link OptionalShape} is only legal as a direct object-property value —
3201
3913
  * `optionalShape` wrapping an array item, a union variant, another
@@ -3208,14 +3920,19 @@ export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void
3208
3920
  * `-Infinity`) number values.
3209
3921
  * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
3210
3922
  * needs `min <= max` when both are set.
3923
+ * - Every present number bound is finite.
3211
3924
  * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
3212
3925
  * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
3926
+ * - Shape nesting may not exceed {@link COMPILE_DEPTH_LIMIT}; excessive depth
3927
+ * fails before recursive artifact compilation begins. Because the depth check
3928
+ * runs before the active-ancestor check, a back-edge first reached beyond the
3929
+ * limit reports `depth`; a cycle reached within the limit reports `cycle`.
3213
3930
  * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
3214
3931
  * continues into array items, object properties (and `additionalProperties`
3215
3932
  * when it is a shape), union variants, and optional/nullable inner shapes.
3216
3933
  *
3217
3934
  * @param shape - The shape to validate
3218
- * @throws {Error} When the shape is malformed
3935
+ * @throws {ContractError} When the shape is malformed or cyclic
3219
3936
  *
3220
3937
  * @example
3221
3938
  * ```ts
@@ -3225,6 +3942,23 @@ export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void
3225
3942
  */
3226
3943
  export declare function validateShape(shape: ContractShape): void;
3227
3944
 
3945
+ /**
3946
+ * Gate recursive compiler work on shape depth and structural cycles.
3947
+ *
3948
+ * @remarks
3949
+ * Walks the shape graph iteratively in linear time and stack space, tracking
3950
+ * active ancestors so shared children remain legal. Every standalone compiler
3951
+ * calls this gate before its recursive branch begins. The depth check runs
3952
+ * before the active-ancestor check, so a back-edge first reached beyond
3953
+ * {@link COMPILE_DEPTH_LIMIT} reports `depth`; a shallower cycle reports
3954
+ * `cycle`.
3955
+ *
3956
+ * @param shape - The shape graph to gate
3957
+ * @returns Nothing; successful return means recursive compilation is depth-safe
3958
+ * @throws {ContractError} When the shape is cyclic or exceeds the compilation depth limit
3959
+ */
3960
+ export declare function validateShapeDepth(shape: ContractShape): void;
3961
+
3228
3962
  /**
3229
3963
  * Infer a `JSONSchema` for one unknown value — the reverse direction of
3230
3964
  * {@link compileSchema}.