@orkestrel/contract 0.0.4 → 0.0.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/combinators.ts","../../../src/core/parsers.ts","../../../src/core/compilers.ts","../../../src/core/shapers.ts"],"sourcesContent":["import type { JSONSchemaType } from './types.js'\n\n// JSON-related constants. Kept as plain frozen data so the shipped combinators\n// and parsers operate on them directly — there is deliberately no bespoke\n// JSON-Schema guard (AGENTS §14 — the deep recursive validators stay out by\n// design).\n\n/**\n * The seven standard JSON Schema `type` names, frozen.\n *\n * @remarks\n * The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose\n * it with the shipped primitives instead of reaching for a bespoke guard:\n * `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and\n * `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`\n * is the parser.\n *\n * @example\n * ```ts\n * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'\n *\n * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>\n * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined\n * ```\n */\nexport const JSON_SCHEMA_TYPES: readonly JSONSchemaType[] = Object.freeze([\n\t'null',\n\t'boolean',\n\t'object',\n\t'array',\n\t'number',\n\t'integer',\n\t'string',\n])\n","import type {\n\tAnyAsyncFunction,\n\tAnyConstructor,\n\tAnyFunction,\n\tJSONPrimitive,\n\tJSONValue,\n\tZeroArgAsyncFunction,\n\tZeroArgFunction,\n} from './types.js'\nimport { attempt, enumerableSymbolCount } from './helpers.js'\n\n// AGENTS §14: guards are total functions — a guard NEVER throws. Adversarial\n// input (hostile getters, exotic objects, cycles) returns `false`, never an\n// error. Guards built from a single `typeof` / strict-equality test are\n// immediately total — no probe of the value's internals can throw. Every\n// OTHER guard here probes the value in some way — a property read through\n// `Reflect.get`, a structural walk (`isPromiseLike`, `isIterable`,\n// `isAsyncIterable`, `isJSONValue`, `isRecord`), an `instanceof` check (which\n// invokes the target's `[Symbol.hasInstance]` / triggers a `getPrototypeOf`\n// trap), or an own-key enumeration (`isEmptyObject` / `isNonEmptyObject`) —\n// so a hostile getter, a revoked `Proxy`, or an exotic trap can throw\n// mid-probe. Totality is NOT automatic for these: each contains its\n// probe/walk in `attempt` (see ./helpers.js) and returns `false` on a caught\n// throw. Every `instanceof`-based guard in this file routes through the\n// shared {@link isInstance} helper, which is the one place that containment\n// lives for that family.\n\n// === Primitive guards\n\n/** Determine whether a value is `null`.\n *\n * @example\n * ```ts\n * isNull(null) // true\n * isNull(undefined) // false\n * ```\n */\nexport function isNull(value: unknown): value is null {\n\treturn value === null\n}\n\n/** Determine whether a value is `undefined`.\n *\n * @example\n * ```ts\n * isUndefined(undefined) // true\n * isUndefined(null) // false\n * ```\n */\nexport function isUndefined(value: unknown): value is undefined {\n\treturn value === undefined\n}\n\n/** Determine whether a value is defined (neither `null` nor `undefined`).\n *\n * @example\n * ```ts\n * isDefined('hi') // true\n * isDefined(null) // false\n * isDefined(undefined) // false\n * ```\n */\nexport function isDefined<T>(value: T | null | undefined): value is T {\n\treturn value !== null && value !== undefined\n}\n\n/** Determine whether a value is a string.\n *\n * @example\n * ```ts\n * isString('hi') // true\n * isString(42) // false\n * ```\n */\nexport function isString(value: unknown): value is string {\n\treturn typeof value === 'string'\n}\n\n/**\n * Determine whether a value is a number.\n *\n * @remarks\n * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.\n *\n * @example\n * ```ts\n * isNumber(42) // true\n * isNumber(Number.NaN) // true — NaN is still a number\n * isNumber('42') // false\n * ```\n */\nexport function isNumber(value: unknown): value is number {\n\treturn typeof value === 'number'\n}\n\n/** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).\n *\n * @example\n * ```ts\n * isFiniteNumber(42) // true\n * isFiniteNumber(Number.NaN) // false\n * isFiniteNumber(Infinity) // false\n * ```\n */\nexport function isFiniteNumber(value: unknown): value is number {\n\treturn typeof value === 'number' && Number.isFinite(value)\n}\n\n/** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).\n *\n * @example\n * ```ts\n * isInteger(3) // true\n * isInteger(3.5) // false\n * ```\n */\nexport function isInteger(value: unknown): value is number {\n\treturn Number.isInteger(value)\n}\n\n/** Determine whether a value is a boolean.\n *\n * @example\n * ```ts\n * isBoolean(true) // true\n * isBoolean(1) // false\n * ```\n */\nexport function isBoolean(value: unknown): value is boolean {\n\treturn typeof value === 'boolean'\n}\n\n/** Determine whether a value is exactly `true`.\n *\n * @example\n * ```ts\n * isTrue(true) // true\n * isTrue(false) // false\n * ```\n */\nexport function isTrue(value: unknown): value is true {\n\treturn value === true\n}\n\n/** Determine whether a value is exactly `false`.\n *\n * @example\n * ```ts\n * isFalse(false) // true\n * isFalse(true) // false\n * ```\n */\nexport function isFalse(value: unknown): value is false {\n\treturn value === false\n}\n\n/** Determine whether a value is a bigint.\n *\n * @example\n * ```ts\n * isBigInt(1n) // true\n * isBigInt(1) // false\n * ```\n */\nexport function isBigInt(value: unknown): value is bigint {\n\treturn typeof value === 'bigint'\n}\n\n/** Determine whether a value is a symbol.\n *\n * @example\n * ```ts\n * isSymbol(Symbol('x')) // true\n * isSymbol('x') // false\n * ```\n */\nexport function isSymbol(value: unknown): value is symbol {\n\treturn typeof value === 'symbol'\n}\n\n/** Determine whether a value is callable.\n *\n * @example\n * ```ts\n * isFunction(() => {}) // true\n * isFunction({}) // false\n * ```\n */\nexport function isFunction(value: unknown): value is AnyFunction {\n\treturn typeof value === 'function'\n}\n\n/** Determine whether a value is a string or `null`.\n *\n * @example\n * ```ts\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function isNullableString(value: unknown): value is string | null {\n\treturn value === null || isString(value)\n}\n\n/** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`).\n *\n * @example\n * ```ts\n * isNullableNumber(42) // true\n * isNullableNumber(null) // true\n * isNullableNumber('hi') // false\n * ```\n */\nexport function isNullableNumber(value: unknown): value is number | null {\n\treturn value === null || isNumber(value)\n}\n\n/** Determine whether a value is a boolean or `null`.\n *\n * @example\n * ```ts\n * isNullableBoolean(true) // true\n * isNullableBoolean(null) // true\n * isNullableBoolean(1) // false\n * ```\n */\nexport function isNullableBoolean(value: unknown): value is boolean | null {\n\treturn value === null || isBoolean(value)\n}\n\n// === Built-in guards\n//\n// The `instanceof`-based guard families below (Date/RegExp/Error/Promise,\n// Map/Set/WeakMap/WeakSet, the typed-array guards) are same-realm checks:\n// `instanceof` compares against the constructor's prototype in the CURRENT\n// realm, so a value built by another realm (a different `vm.Context`, iframe,\n// or worker global) fails even when it is structurally identical. This is a\n// known, accepted limitation — cross-realm identity would require duck-typing\n// every built-in, which trades soundness for portability.\n\n/**\n * Determine whether a value is an instance of a constructor, contained against\n * a throwing `instanceof` check.\n *\n * @remarks\n * The low-level total helper every `instanceof`-based guard in this file (and\n * the `instanceOf` combinator) routes through. A bare `value instanceof X` is\n * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a\n * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when\n * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This\n * wraps the check in {@link attempt} (see ./helpers.js) so any such throw\n * yields `false` instead of escaping.\n *\n * @param value - The value to test\n * @param ctor - The constructor to test against\n * @returns `true` when `value instanceof ctor`, `false` on a non-match or a\n * contained throw\n *\n * @example\n * ```ts\n * isInstance(new Date(), Date) // true\n * isInstance({}, Date) // false\n * ```\n */\nexport function isInstance<C>(\n\tvalue: unknown,\n\tctor: C,\n): value is InstanceType<C & AnyConstructor<object>> {\n\t// `ctor` is narrowed to a function through `isFunction` before the `instanceof`\n\t// check — an unconstrained generic RHS loses TS's built-in instanceof leniency\n\t// once nested inside another generic call (the `attempt` callback), so the\n\t// narrowing keeps this call legal without a constraint that would reject\n\t// combinators.ts's `instanceOf`, which validates `ctor` separately.\n\tconst target: unknown = ctor\n\tconst outcome = attempt(() => isFunction(target) && value instanceof target)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a `Date`.\n *\n * @example\n * ```ts\n * isDate(new Date()) // true\n * isDate('2024-01-01') // false\n * ```\n */\nexport function isDate(value: unknown): value is Date {\n\treturn isInstance(value, Date)\n}\n\n/** Determine whether a value is a `RegExp`.\n *\n * @example\n * ```ts\n * isRegExp(/a/) // true\n * isRegExp('a') // false\n * ```\n */\nexport function isRegExp(value: unknown): value is RegExp {\n\treturn isInstance(value, RegExp)\n}\n\n/** Determine whether a value is an `Error`.\n *\n * @example\n * ```ts\n * isError(new Error('boom')) // true\n * isError('boom') // false\n * ```\n */\nexport function isError(value: unknown): value is Error {\n\treturn isInstance(value, Error)\n}\n\n/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve()) // true\n * isPromise({ then() {} }) // false\n * ```\n */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n\treturn isInstance(value, Promise)\n}\n\n/**\n * Determine whether a value is promise-like — an object exposing callable\n * `then`, `catch`, and `finally` methods.\n *\n * @remarks\n * Accepts any object with all three methods, not only native `Promise`\n * instances. Use {@link isPromise} when you specifically need `instanceof Promise`.\n *\n * @example\n * ```ts\n * isPromiseLike(Promise.resolve()) // true\n * isPromiseLike({ then() {}, catch() {}, finally() {} }) // true\n * isPromiseLike({ then() {} }) // false\n * ```\n */\nexport function isPromiseLike<T = unknown>(\n\tvalue: unknown,\n): value is Promise<T> | (PromiseLike<T> & { catch: unknown; finally: unknown }) {\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => {\n\t\tconst thenValue = Reflect.get(value, 'then')\n\t\tconst catchValue = Reflect.get(value, 'catch')\n\t\tconst finallyValue = Reflect.get(value, 'finally')\n\t\treturn isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue)\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is an `ArrayBuffer`.\n *\n * @example\n * ```ts\n * isArrayBuffer(new ArrayBuffer(8)) // true\n * isArrayBuffer([]) // false\n * ```\n */\nexport function isArrayBuffer(value: unknown): value is ArrayBuffer {\n\treturn isInstance(value, ArrayBuffer)\n}\n\n/**\n * Determine whether a value is a `SharedArrayBuffer`.\n *\n * @remarks\n * Guards the global existence of `SharedArrayBuffer` first — safe where it is\n * absent or disabled (e.g. a context that is not cross-origin isolated).\n *\n * @example\n * ```ts\n * isSharedArrayBuffer(new SharedArrayBuffer(8)) // true\n * isSharedArrayBuffer(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n\treturn typeof SharedArrayBuffer !== 'undefined' && isInstance(value, SharedArrayBuffer)\n}\n\n// === Protocol guards\n\n/**\n * Determine whether a value implements the iterable protocol (`Symbol.iterator`).\n *\n * @remarks\n * Strings are explicitly included: a string has a callable `Symbol.iterator`\n * but is not an object, so the generic object path alone would miss it.\n *\n * @example\n * ```ts\n * isIterable([1, 2]) // true\n * isIterable('abc') // true\n * isIterable({ a: 1 }) // false\n * ```\n */\nexport function isIterable<T = unknown>(value: unknown): value is Iterable<T> {\n\tif (isString(value)) {\n\t\treturn true\n\t}\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.iterator)))\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).\n *\n * @example\n * ```ts\n * isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true\n * isAsyncIterable([1, 2]) // false\n * ```\n */\nexport function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T> {\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)))\n\treturn outcome.success && outcome.value\n}\n\n// === Object & collection guards\n\n/**\n * Determine whether a value is a non-null object.\n *\n * @remarks\n * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use\n * {@link isRecord} when you need a plain-record check.\n *\n * @example\n * ```ts\n * isObject({}) // true\n * isObject([]) // true\n * isObject(null) // false\n * ```\n */\nexport function isObject(value: unknown): value is object {\n\treturn typeof value === 'object' && value !== null\n}\n\n/**\n * Determine whether a value is a plain record (object literal or null-prototype),\n * not an array or class instance.\n *\n * @remarks\n * Use instead of {@link isObject} to distinguish a plain `{}` /\n * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain\n * test is realm-agnostic: rather than comparing against the current realm's\n * `Object.prototype` (which a plain object from another `vm.Context`, iframe,\n * or worker would fail), it accepts any value whose prototype is `null`, OR\n * whose prototype's own prototype is `null` — the shape every plain object\n * has in every realm, since `Object.prototype` itself always sits one step\n * above `null`. Arrays and class instances are still rejected: an array's\n * prototype chain runs through `Array.prototype` before `null`, and a class\n * instance's runs through the class's own prototype. The whole body runs\n * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile\n * `getPrototypeOf` trap cannot escape as a thrown error.\n *\n * @example\n * ```ts\n * isRecord({ a: 1 }) // true\n * isRecord(Object.create(null)) // true\n * isRecord([]) // false\n * isRecord(new Date()) // false\n * ```\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\tconst outcome = attempt(() => {\n\t\tif (!isObject(value) || isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\treturn prototype === null || Object.getPrototypeOf(prototype) === null\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a `Map`.\n *\n * @example\n * ```ts\n * isMap(new Map()) // true\n * isMap({}) // false\n * ```\n */\nexport function isMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V> {\n\treturn isInstance(value, Map)\n}\n\n/** Determine whether a value is a `Set`.\n *\n * @example\n * ```ts\n * isSet(new Set()) // true\n * isSet([]) // false\n * ```\n */\nexport function isSet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn isInstance(value, Set)\n}\n\n/** Determine whether a value is a `WeakMap`.\n *\n * @example\n * ```ts\n * isWeakMap(new WeakMap()) // true\n * isWeakMap({}) // false\n * ```\n */\nexport function isWeakMap(value: unknown): value is WeakMap<object, unknown> {\n\treturn isInstance(value, WeakMap)\n}\n\n/** Determine whether a value is a `WeakSet`.\n *\n * @example\n * ```ts\n * isWeakSet(new WeakSet()) // true\n * isWeakSet({}) // false\n * ```\n */\nexport function isWeakSet(value: unknown): value is WeakSet<object> {\n\treturn isInstance(value, WeakSet)\n}\n\n// === Array & typed-array guards\n\n/** Determine whether a value is an array.\n *\n * @example\n * ```ts\n * isArray([1, 2]) // true\n * isArray('12') // false\n * ```\n */\nexport function isArray<T = unknown>(value: unknown): value is readonly T[] {\n\treturn Array.isArray(value)\n}\n\n/** Determine whether a value is a `DataView`.\n *\n * @example\n * ```ts\n * isDataView(new DataView(new ArrayBuffer(8))) // true\n * isDataView(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isDataView(value: unknown): value is DataView<ArrayBufferLike> {\n\treturn isInstance(value, DataView)\n}\n\n/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).\n *\n * @example\n * ```ts\n * isArrayBufferView(new Uint8Array(4)) // true\n * isArrayBufferView([1, 2, 3, 4]) // false\n * ```\n */\nexport function isArrayBufferView(value: unknown): value is ArrayBufferView {\n\treturn ArrayBuffer.isView(value)\n}\n\n/** Determine whether a value is an `Int8Array`.\n *\n * @example\n * ```ts\n * isInt8Array(new Int8Array(2)) // true\n * isInt8Array(new Uint8Array(2)) // false\n * ```\n */\nexport function isInt8Array(value: unknown): value is Int8Array {\n\treturn isInstance(value, Int8Array)\n}\n\n/** Determine whether a value is a `Uint8Array`.\n *\n * @example\n * ```ts\n * isUint8Array(new Uint8Array(2)) // true\n * isUint8Array(new Int8Array(2)) // false\n * ```\n */\nexport function isUint8Array(value: unknown): value is Uint8Array {\n\treturn isInstance(value, Uint8Array)\n}\n\n/** Determine whether a value is a `Uint8ClampedArray`.\n *\n * @example\n * ```ts\n * isUint8ClampedArray(new Uint8ClampedArray(2)) // true\n * isUint8ClampedArray(new Uint8Array(2)) // false\n * ```\n */\nexport function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray {\n\treturn isInstance(value, Uint8ClampedArray)\n}\n\n/** Determine whether a value is an `Int16Array`.\n *\n * @example\n * ```ts\n * isInt16Array(new Int16Array(2)) // true\n * isInt16Array(new Int8Array(2)) // false\n * ```\n */\nexport function isInt16Array(value: unknown): value is Int16Array {\n\treturn isInstance(value, Int16Array)\n}\n\n/** Determine whether a value is a `Uint16Array`.\n *\n * @example\n * ```ts\n * isUint16Array(new Uint16Array(2)) // true\n * isUint16Array(new Int16Array(2)) // false\n * ```\n */\nexport function isUint16Array(value: unknown): value is Uint16Array {\n\treturn isInstance(value, Uint16Array)\n}\n\n/** Determine whether a value is an `Int32Array`.\n *\n * @example\n * ```ts\n * isInt32Array(new Int32Array(2)) // true\n * isInt32Array(new Int16Array(2)) // false\n * ```\n */\nexport function isInt32Array(value: unknown): value is Int32Array {\n\treturn isInstance(value, Int32Array)\n}\n\n/** Determine whether a value is a `Uint32Array`.\n *\n * @example\n * ```ts\n * isUint32Array(new Uint32Array(2)) // true\n * isUint32Array(new Int32Array(2)) // false\n * ```\n */\nexport function isUint32Array(value: unknown): value is Uint32Array {\n\treturn isInstance(value, Uint32Array)\n}\n\n/** Determine whether a value is a `Float32Array`.\n *\n * @example\n * ```ts\n * isFloat32Array(new Float32Array(2)) // true\n * isFloat32Array(new Float64Array(2)) // false\n * ```\n */\nexport function isFloat32Array(value: unknown): value is Float32Array {\n\treturn isInstance(value, Float32Array)\n}\n\n/** Determine whether a value is a `Float64Array`.\n *\n * @example\n * ```ts\n * isFloat64Array(new Float64Array(2)) // true\n * isFloat64Array(new Float32Array(2)) // false\n * ```\n */\nexport function isFloat64Array(value: unknown): value is Float64Array {\n\treturn isInstance(value, Float64Array)\n}\n\n/**\n * Determine whether a value is a `BigInt64Array`.\n *\n * @remarks\n * Guards the global existence of `BigInt64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigInt64Array(new BigInt64Array(2)) // true\n * isBigInt64Array(new Float64Array(2)) // false\n * ```\n */\nexport function isBigInt64Array(value: unknown): value is BigInt64Array {\n\treturn typeof BigInt64Array !== 'undefined' && isInstance(value, BigInt64Array)\n}\n\n/**\n * Determine whether a value is a `BigUint64Array`.\n *\n * @remarks\n * Guards the global existence of `BigUint64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigUint64Array(new BigUint64Array(2)) // true\n * isBigUint64Array(new BigInt64Array(2)) // false\n * ```\n */\nexport function isBigUint64Array(value: unknown): value is BigUint64Array {\n\treturn typeof BigUint64Array !== 'undefined' && isInstance(value, BigUint64Array)\n}\n\n// === Emptiness guards\n\n/** Determine whether a value is the empty string `''`.\n *\n * @example\n * ```ts\n * isEmptyString('') // true\n * isEmptyString('a') // false\n * ```\n */\nexport function isEmptyString(value: unknown): value is '' {\n\treturn isString(value) && value.length === 0\n}\n\n/** Determine whether a value is an empty array.\n *\n * @example\n * ```ts\n * isEmptyArray([]) // true\n * isEmptyArray([1]) // false\n * ```\n */\nexport function isEmptyArray(value: unknown): value is readonly [] {\n\treturn isArray(value) && value.length === 0\n}\n\n/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).\n *\n * @example\n * ```ts\n * isEmptyObject({}) // true\n * isEmptyObject({ a: 1 }) // false\n * ```\n */\nexport function isEmptyObject(value: unknown): value is Record<string | symbol, never> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\t// Object.keys / getOwnPropertySymbols read the object's own-key list, which\n\t// an `ownKeys` Proxy trap can throw from — contained via `attempt` (AGENTS §14).\n\tconst outcome = attempt(\n\t\t() => Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0,\n\t)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is an empty `Map`.\n *\n * @example\n * ```ts\n * isEmptyMap(new Map()) // true\n * isEmptyMap(new Map([['a', 1]])) // false\n * ```\n */\nexport function isEmptyMap(value: unknown): value is ReadonlyMap<never, never> {\n\treturn isMap(value) && value.size === 0\n}\n\n/** Determine whether a value is an empty `Set`.\n *\n * @example\n * ```ts\n * isEmptySet(new Set()) // true\n * isEmptySet(new Set([1])) // false\n * ```\n */\nexport function isEmptySet(value: unknown): value is ReadonlySet<never> {\n\treturn isSet(value) && value.size === 0\n}\n\n/** Determine whether a value is a non-empty string (at least one character).\n *\n * @example\n * ```ts\n * isNonEmptyString('a') // true\n * isNonEmptyString('') // false\n * ```\n */\nexport function isNonEmptyString(value: unknown): value is string {\n\treturn isString(value) && value.length > 0\n}\n\n/** Determine whether a value is a non-empty array (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptyArray([1]) // true\n * isNonEmptyArray([]) // false\n * ```\n */\nexport function isNonEmptyArray<T = unknown>(value: unknown): value is readonly [T, ...T[]] {\n\treturn isArray(value) && value.length > 0\n}\n\n/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).\n *\n * @example\n * ```ts\n * isNonEmptyObject({ a: 1 }) // true\n * isNonEmptyObject({}) // false\n * ```\n */\nexport function isNonEmptyObject(value: unknown): value is Record<string | symbol, unknown> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\t// Same containment as isEmptyObject — an `ownKeys` Proxy trap can throw.\n\tconst outcome = attempt(() => Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a non-empty `Map` (at least one entry).\n *\n * @example\n * ```ts\n * isNonEmptyMap(new Map([['a', 1]])) // true\n * isNonEmptyMap(new Map()) // false\n * ```\n */\nexport function isNonEmptyMap<K = unknown, V = unknown>(\n\tvalue: unknown,\n): value is ReadonlyMap<K, V> {\n\treturn isMap(value) && value.size > 0\n}\n\n/** Determine whether a value is a non-empty `Set` (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptySet(new Set([1])) // true\n * isNonEmptySet(new Set()) // false\n * ```\n */\nexport function isNonEmptySet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn isSet(value) && value.size > 0\n}\n\n// === Function guards\n\n/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).\n *\n * @example\n * ```ts\n * isZeroArg(() => {}) // true\n * isZeroArg((a) => a) // false\n * ```\n */\nexport function isZeroArg(value: unknown): value is ZeroArgFunction {\n\treturn isFunction(value) && value.length === 0\n}\n\n/**\n * Determine whether a value is a native `async function`.\n *\n * @remarks\n * Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is\n * unreliable across realms. The `?.` keeps the guard total (§14): a function\n * whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.\n *\n * @example\n * ```ts\n * isAsyncFunction(async () => {}) // true\n * isAsyncFunction(() => {}) // false\n * ```\n */\nexport function isAsyncFunction(value: unknown): value is AnyAsyncFunction {\n\treturn isFunction(value) && value.constructor?.name === 'AsyncFunction'\n}\n\n/** Determine whether a value is a generator function (`function*`).\n *\n * @example\n * ```ts\n * isGeneratorFunction(function* () {}) // true\n * isGeneratorFunction(() => {}) // false\n * ```\n */\nexport function isGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => Generator<unknown, unknown, unknown> {\n\treturn isFunction(value) && value.constructor?.name === 'GeneratorFunction'\n}\n\n/** Determine whether a value is an async generator function (`async function*`).\n *\n * @example\n * ```ts\n * isAsyncGeneratorFunction(async function* () {}) // true\n * isAsyncGeneratorFunction(function* () {}) // false\n * ```\n */\nexport function isAsyncGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => AsyncGenerator<unknown, unknown, unknown> {\n\treturn isFunction(value) && value.constructor?.name === 'AsyncGeneratorFunction'\n}\n\n/** Determine whether a value is a zero-argument async function.\n *\n * @example\n * ```ts\n * isZeroArgAsync(async () => {}) // true\n * isZeroArgAsync(async (a) => a) // false\n * ```\n */\nexport function isZeroArgAsync(value: unknown): value is ZeroArgAsyncFunction {\n\treturn isZeroArg(value) && isAsyncFunction(value)\n}\n\n/** Determine whether a value is a zero-argument generator function.\n *\n * @example\n * ```ts\n * isZeroArgGenerator(function* () {}) // true\n * isZeroArgGenerator(function* (a) {}) // false\n * ```\n */\nexport function isZeroArgGenerator(\n\tvalue: unknown,\n): value is () => Generator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isGeneratorFunction(value)\n}\n\n/** Determine whether a value is a zero-argument async generator function.\n *\n * @example\n * ```ts\n * isZeroArgAsyncGenerator(async function* () {}) // true\n * isZeroArgAsyncGenerator(async function* (a) {}) // false\n * ```\n */\nexport function isZeroArgAsyncGenerator(\n\tvalue: unknown,\n): value is () => AsyncGenerator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isAsyncGeneratorFunction(value)\n}\n\n/**\n * Determine whether a value can be used as a `new`-target constructor.\n *\n * @remarks\n * Probes with `Reflect.construct(String, [], value)`: a real constructor\n * succeeds, while arrow functions, plain functions, and non-functions throw\n * and yield `false`. Never throws. Backs the `instanceOf` combinator.\n *\n * @example\n * ```ts\n * isConstructor(class X {}) // true\n * isConstructor(() => {}) // false\n * ```\n */\nexport function isConstructor(value: unknown): value is AnyConstructor<object> {\n\tif (!isFunction(value)) {\n\t\treturn false\n\t}\n\ttry {\n\t\tReflect.construct(String, [], value)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n// === JSON\n\n/**\n * Determine whether a value is a cycle-safe JSON value.\n *\n * @remarks\n * Total guard: never throws, returns `false` for cycles, functions, `Date`\n * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records\n * are walked with an ancestor set so recursive input fails instead of hanging.\n * The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a\n * record property, or a revoked `Proxy` anywhere in the structure, is caught\n * and yields `false` instead of escaping as a thrown error.\n *\n * @param value - The value to test\n * @returns `true` when the value has a JSON representation\n *\n * @example\n * ```ts\n * isJSONValue({ nested: [1, 'x', null] }) // true\n * isJSONValue(Number.NaN) // false\n * ```\n */\nexport function isJSONValue(value: unknown): value is JSONValue {\n\tconst ancestors = new WeakSet<object>()\n\tconst check = (entry: unknown): entry is JSONValue => {\n\t\tif (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true\n\t\tif (Array.isArray(entry)) {\n\t\t\tif (ancestors.has(entry)) return false\n\t\t\tancestors.add(entry)\n\t\t\tconst valid = entry.every(check)\n\t\t\tancestors.delete(entry)\n\t\t\treturn valid\n\t\t}\n\t\tif (!isRecord(entry)) return false\n\t\tif (ancestors.has(entry)) return false\n\t\tancestors.add(entry)\n\t\tconst valid = Object.values(entry).every(check)\n\t\tancestors.delete(entry)\n\t\treturn valid\n\t}\n\tconst outcome = attempt(() => check(value))\n\treturn outcome.success && outcome.value\n}\n\n/**\n * Determine whether a value is a primitive JSON value.\n *\n * @remarks\n * The flat leaf of any JSON document: `null`, a string, a **finite** number, or\n * a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON\n * carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.\n *\n * The recursive {@link isJSONValue} guard is shipped and stays total with\n * cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and\n * the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with\n * the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.\n *\n * @param value - The value to test\n * @returns `true` when `value` is `null`, a string, a finite number, or a boolean\n *\n * @example\n * ```ts\n * isJSONPrimitive(null) // true\n * isJSONPrimitive('hi') // true\n * isJSONPrimitive(42) // true\n * isJSONPrimitive(Number.NaN) // false — not representable in JSON\n * isJSONPrimitive({}) // false\n * ```\n */\nexport function isJSONPrimitive(value: unknown): value is JSONPrimitive {\n\treturn isNull(value) || isString(value) || isFiniteNumber(value) || isBoolean(value)\n}\n","import type { FieldPath, JSONSchema, RandomFunction, Result } from './types.js'\nimport { isObject, isRecord, isString } from './validators.js'\n\n// === Result helpers\n\n/**\n * Invoke a callback and capture its outcome as a {@link Result}, never letting\n * a throw escape.\n *\n * @remarks\n * The single sanctioned never-throw boundary for the guards (AGENTS §14). The\n * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied\n * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a\n * `boolean`. This converts a throwing callback into a `Failure` so the\n * surrounding guard can treat it as a non-match instead of propagating the\n * exception, written once and shared rather than copy-pasted as ad-hoc\n * `try`/`catch`.\n *\n * @param callback - The callback to invoke with no arguments\n * @returns A `Success` carrying the return value, or a `Failure` carrying the\n * thrown reason normalised to an `Error`\n *\n * @example\n * ```ts\n * const outcome = attempt(() => predicate(value))\n * return outcome.success && outcome.value\n * ```\n */\nexport function attempt<T>(callback: () => T): Result<T> {\n\ttry {\n\t\treturn { success: true, value: callback() }\n\t} catch (reason) {\n\t\tif (reason instanceof Error) {\n\t\t\treturn { success: false, error: reason }\n\t\t}\n\t\t// A thrown non-Error value's own `toString` may itself throw (a hostile\n\t\t// object) — contain that conversion too so normalization never escapes.\n\t\tlet message = 'Unknown thrown value'\n\t\ttry {\n\t\t\tmessage = String(reason)\n\t\t} catch {\n\t\t\t// keep the fallback message\n\t\t}\n\t\treturn { success: false, error: new Error(message) }\n\t}\n}\n\n// === Record-field access\n\n/**\n * Resolve a (possibly nested) field value from a record by a key or key path.\n *\n * @remarks\n * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a\n * string array descends left-to-right through nested objects. Intermediates may\n * be any object — records, class instances, or arrays indexed by string. Returns\n * `undefined` the moment a segment is missing or lands on a non-object, so the\n * lookup is total — even against a hostile getter or Proxy trap that throws on\n * read, contained via {@link attempt} so the throw never escapes.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The resolved value, or `undefined`\n *\n * @example\n * ```ts\n * resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'\n * resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)\n * resolveField({ a: 1 }, ['a', 'b']) // undefined\n * ```\n */\nexport function resolveField(record: Readonly<Record<string, unknown>>, path: FieldPath): unknown {\n\tconst keys = isString(path) ? [path] : path\n\tlet current: unknown = record\n\tfor (const key of keys) {\n\t\tif (!isObject(current)) return undefined\n\t\tconst container = current\n\t\tconst outcome = attempt(() => Reflect.get(container, key))\n\t\tif (!outcome.success) return undefined\n\t\tcurrent = outcome.value\n\t}\n\treturn current\n}\n\n// === Random\n\n/**\n * Build a deterministic pseudo-random source seeded from a single number.\n *\n * @remarks\n * A mulberry32 generator — the same seed always yields the same sequence, so\n * generated seed data is reproducible across runs. Used as the default random\n * source for {@link compileGenerator}, seeded from the wall clock so casual\n * callers still get varied output without passing a source themselves.\n *\n * @param seed - The seed for the sequence\n * @returns A {@link RandomFunction} returning values in `[0, 1)`\n *\n * @example\n * ```ts\n * const random = seededRandom(42)\n * random() // always the same first value for seed 42\n * ```\n */\nexport function seededRandom(seed: number): RandomFunction {\n\tlet state = seed >>> 0\n\treturn () => {\n\t\tstate = (state + 0x6d2b79f5) >>> 0\n\t\tlet t = state\n\t\tt = Math.imul(t ^ (t >>> 15), t | 1)\n\t\tt ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n\t\treturn ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296\n\t}\n}\n\n/**\n * Count the enumerable own-symbol keys on a value.\n *\n * @remarks\n * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose\n * descriptor is `enumerable` are counted. Backs the object-emptiness guards\n * (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an\n * enumerable symbol is not mistaken for empty.\n *\n * @param value - The object to inspect\n * @returns The number of enumerable own-symbol keys\n *\n * @example\n * ```ts\n * const flag = Symbol('flag')\n * enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1\n * enumerableSymbolCount({}) // 0\n * ```\n */\nexport function enumerableSymbolCount(value: object): number {\n\tlet count = 0\n\tfor (const symbol of Object.getOwnPropertySymbols(value)) {\n\t\tif (Object.getOwnPropertyDescriptor(value, symbol)?.enumerable) {\n\t\t\tcount += 1\n\t\t}\n\t}\n\treturn count\n}\n\n/**\n * Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape\n * tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never\n * an assertion (AGENTS §14).\n *\n * @remarks\n * A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a\n * tool advertises its `parameters` as an open record. The two are structurally compatible but not\n * assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema\n * is always a record, so the guard passes; the `undefined` fallback only satisfies the type's\n * optionality. This is the single sanctioned narrowing from a compiled contract schema to the open\n * tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.\n *\n * @param schema - The compiled JSON Schema (a contract's `schema`)\n * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record\n *\n * @example\n * ```ts\n * import { createContract, schemaToParameters } from '@src/core'\n *\n * const contract = createContract(shape)\n * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises\n * ```\n */\nexport function schemaToParameters(\n\tschema: JSONSchema,\n): Readonly<Record<string, unknown>> | undefined {\n\treturn isRecord(schema) ? schema : undefined\n}\n","import type {\n\tFromGuards,\n\tGuard,\n\tGuardsShape,\n\tGuardType,\n\tIntersectionFromGuards,\n\tOptionalFromGuards,\n\tTupleFromGuards,\n} from './types.js'\nimport {\n\tisArray,\n\tisConstructor,\n\tisFiniteNumber,\n\tisInstance,\n\tisIterable,\n\tisMap,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisSet,\n\tisString,\n\tisSymbol,\n} from './validators.js'\nimport { attempt } from './helpers.js'\n\n// Every combinator returns a `Guard<T>` — a total function (AGENTS §14). The\n// three combinators that invoke a caller-supplied callback inside the guard\n// body (`whereOf`, `lazyOf`, `transformOf`) contain any throw via `attempt`, so\n// the produced guard reports a non-match instead of propagating. The container\n// combinators (`arrayOf`, `tupleOf`, `setOf`, `mapOf`, `iterableOf`, `recordOf`)\n// likewise wrap their element/entry/key-read walk in `attempt` after the cheap\n// structural check — a hostile Proxy trap, a throwing getter, a throwing\n// iterator, or a throwing caller-supplied predicate yields a non-match, never a\n// propagated throw.\n\n/**\n * Build a guard that accepts arrays whose every element satisfies `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringArray = arrayOf(isString)\n * isStringArray(['a', 'b']) // true\n * isStringArray(['a', 1]) // false\n * ```\n */\nexport function arrayOf<T>(elementGuard: Guard<T>): Guard<readonly T[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] => {\n\t\tif (!isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => value.every(elementGuard))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts fixed-arity tuples, testing each index with the\n * corresponding guard.\n *\n * @example\n * ```ts\n * const isPair = tupleOf(isString, isNumber)\n * isPair(['hello', 42]) // true\n * isPair(['hello']) // false — wrong arity\n * ```\n */\nexport function tupleOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<TupleFromGuards<Gs>>\nexport function tupleOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]>\nexport function tupleOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] => {\n\t\tif (!isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// Arity comparison reads `.length`, which — like the element reads below —\n\t\t// can hit a hostile Proxy trap, so it stays inside the contained region too.\n\t\tconst outcome = attempt(() => {\n\t\t\tif (value.length !== guards.length) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let index = 0; index < guards.length; index += 1) {\n\t\t\t\tconst guard = guards[index]\n\t\t\t\tif (!guard?.(value[index])) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts values identical (via `Object.is`) to one of the\n * provided literal primitives.\n *\n * @example\n * ```ts\n * const isRole = literalOf('admin', 'member', 'guest')\n * isRole('admin') // true\n * isRole('owner') // false\n * ```\n */\nexport function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(\n\t...literals: Literals\n): Guard<Literals[number]> {\n\treturn (value: unknown): value is Literals[number] =>\n\t\tliterals.some((literal) => Object.is(literal, value))\n}\n\n/**\n * Build a guard that accepts instances of the provided constructor.\n *\n * @remarks\n * Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,\n * so passing an arrow function does not silently produce a broken guard.\n *\n * @example\n * ```ts\n * const isDateValue = instanceOf(Date)\n * isDateValue(new Date()) // true\n * isDateValue({}) // false\n * ```\n */\nexport function instanceOf<C extends abstract new (...args: never) => object>(\n\tctor: C,\n): Guard<InstanceType<C>> {\n\treturn (value: unknown): value is InstanceType<C> =>\n\t\tisConstructor(ctor) && isObject(value) && isInstance(value, ctor)\n}\n\n/**\n * Build a guard from a native `enum` or any object whose values are strings or\n * numbers.\n *\n * @example\n * ```ts\n * enum Direction { Up = 'up', Down = 'down' }\n * const isDirection = enumOf(Direction)\n * isDirection('up') // true\n * isDirection('left') // false\n * ```\n */\nexport function enumOf<const E extends Record<string, string | number>>(\n\tenumeration: E,\n): Guard<E[keyof E]> {\n\tconst values = new Set(Object.values(enumeration))\n\treturn (value: unknown): value is E[keyof E] =>\n\t\t(isString(value) || isNumber(value)) && values.has(value)\n}\n\n/**\n * Build a guard that accepts `Set` instances whose every element satisfies\n * `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringSet = setOf(isString)\n * isStringSet(new Set(['a', 'b'])) // true\n * isStringSet(new Set(['a', 1])) // false\n * ```\n */\nexport function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>> {\n\treturn (value: unknown): value is ReadonlySet<unknown> => {\n\t\tif (!isSet(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (!elementGuard(entry)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts `Map` instances where every key satisfies\n * `keyGuard` and every value satisfies `valueGuard`.\n *\n * @example\n * ```ts\n * const isStringNumberMap = mapOf(isString, isNumber)\n * isStringNumberMap(new Map([['a', 1]])) // true\n * isStringNumberMap(new Map([[1, 'a']])) // false\n * ```\n */\nexport function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): Guard<ReadonlyMap<K, V>>\nexport function mapOf(\n\tkeyPredicate: (value: unknown) => boolean,\n\tvaluePredicate: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>>\nexport function mapOf(\n\tkeyGuard: (value: unknown) => boolean,\n\tvalueGuard: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>> {\n\treturn (value: unknown): value is ReadonlyMap<unknown, unknown> => {\n\t\tif (!isMap(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const [key, entryValue] of value) {\n\t\t\t\tif (!keyGuard(key) || !valueGuard(entryValue)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\nexport function recordOf<S extends GuardsShape>(shape: S): Guard<FromGuards<S>>\nexport function recordOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\toptional: K,\n): Guard<OptionalFromGuards<S, K>>\nexport function recordOf<S extends GuardsShape>(\n\tshape: S,\n\toptional: true,\n): Guard<Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>>\n\n/**\n * Build a guard that accepts plain records matching a guard shape.\n *\n * @remarks\n * Three calling modes depending on the `optional` argument:\n * - **No `optional`** — all shape keys required; extra keys rejected.\n * - **`optional: K[]`** — the listed keys are optional; all others required.\n * - **`optional: true`** — every shape key is optional.\n *\n * Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by\n * an inherited prototype member (`toString`, `constructor`, …) counts as absent.\n * A non-object / `null` / array input returns `false` rather than throwing. The\n * extra-key check only inspects `Object.keys` (string keys), so an extra\n * enumerable SYMBOL key is never rejected — intentional, for JSON fidelity, and\n * matches the compiled guard.\n *\n * @example\n * ```ts\n * const isUser = recordOf({ name: isString, age: isNumber })\n * isUser({ name: 'Ada', age: 36 }) // true\n * isUser({ name: 'Ada' }) // false — age missing\n *\n * const isPartial = recordOf({ name: isString, age: isNumber }, ['age'])\n * isPartial({ name: 'Ada' }) // true\n * ```\n */\nexport function recordOf<\n\tS extends GuardsShape,\n\tK extends ReadonlyArray<keyof S & string> | true | undefined,\n>(\n\tshape: S,\n\toptional?: K,\n): Guard<\n\tK extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S>\n> {\n\tconst allowed = new Set<string>()\n\tfor (const key in shape) {\n\t\tif (Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tallowed.add(key)\n\t\t}\n\t}\n\tconst optionalSet = new Set<string>(\n\t\toptional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : [],\n\t)\n\n\treturn (\n\t\tvalue: unknown,\n\t): value is K extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S> => {\n\t\tif (!isRecord(value)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\tif (!allowed.has(key)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const key in shape) {\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst present = Object.hasOwn(value, key)\n\t\t\t\tif (!optionalSet.has(key) && !present) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif (present) {\n\t\t\t\t\tconst guard = shape[key]\n\t\t\t\t\tif (!guard(value[key])) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts any iterable whose every element satisfies\n * `elementGuard`.\n *\n * @example\n * ```ts\n * const isNumberIterable = iterableOf(isNumber)\n * isNumberIterable([1, 2, 3]) // true\n * isNumberIterable(new Set([1, 2])) // true\n * isNumberIterable([1, 'two']) // false\n * ```\n */\nexport function iterableOf<T>(elementGuard: Guard<T>): Guard<Iterable<T>>\nexport function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>>\nexport function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>> {\n\treturn (value: unknown): value is Iterable<unknown> => {\n\t\tif (!isIterable(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (!elementGuard(entry)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts values that are own keys of the provided object.\n *\n * @remarks\n * Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys\n * (`toString`, `constructor`, …) are rejected. An own property that shadows a\n * prototype name is accepted.\n *\n * @example\n * ```ts\n * const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const\n * const isColorKey = keyOf(COLORS)\n * isColorKey('red') // true\n * isColorKey('purple') // false\n * isColorKey('toString') // false — inherited, not an own key\n * ```\n */\nexport function keyOf<const O extends Readonly<Record<PropertyKey, unknown>>>(\n\tvalue: O,\n): Guard<keyof O> {\n\treturn (entry: unknown): entry is keyof O =>\n\t\t(isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry)\n}\n\n/**\n * Build a new guard shape by keeping only the listed keys — the structural\n * equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isName = recordOf(pickOf(full, ['name']))\n * isName({ name: 'Ada' }) // true\n * ```\n */\nexport function pickOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Pick<S, K[number]> {\n\t// Honest typing: the accumulator IS the picked-shape type, so every write is\n\t// checked against `S[P]` — no `as` / `!` / `asserts`. The seed is a genuine\n\t// null-prototype empty object, filled before any read.\n\tconst result: { [P in K[number]]: S[P] } = Object.create(null)\n\tfor (const key of keys) {\n\t\tif (Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Build a new guard shape by removing the listed keys — the structural\n * equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isPublic = recordOf(omitOf(full, ['role']))\n * isPublic({ name: 'Ada', age: 36 }) // true\n * ```\n */\nexport function omitOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Omit<S, K[number]> {\n\tconst skipped = new Set<PropertyKey>()\n\tfor (const key of keys) {\n\t\tskipped.add(key)\n\t}\n\t// Sound over-approximation: only kept keys are written, so the value\n\t// structurally satisfies `Omit<S, K[number]>`. Same honest typing as\n\t// `pickOf` — no `as` / `!` / `asserts`.\n\tconst result: { [P in keyof S]: S[P] } = Object.create(null)\n\tfor (const key in shape) {\n\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!skipped.has(key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Combine two guards with logical AND — passes only when both pass.\n *\n * @remarks\n * Use {@link whereOf} when the right side refines an already-narrowed type; use\n * `andOf` to combine two independent guards.\n *\n * @example\n * ```ts\n * const isShortString = andOf(isString, isNonEmptyString)\n * ```\n */\nexport function andOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A & B>\nexport function andOf<T, U extends T>(left: Guard<T>, right: (value: T) => value is U): Guard<U>\nexport function andOf<T>(left: Guard<T>, right: (value: T) => boolean): Guard<T>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => left(value) && right(value)\n}\n\n/**\n * Combine two guards with logical OR — passes when at least one passes. For more\n * than two variants prefer {@link unionOf}.\n *\n * @example\n * ```ts\n * const isStringOrNumber = orOf(isString, isNumber)\n * ```\n */\nexport function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => left(value) || right(value)\n}\n\n/**\n * Negate a guard or predicate — passes when `guard` returns `false`.\n *\n * @remarks\n * Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use\n * {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.\n *\n * @example\n * ```ts\n * const isNotNull = notOf(isNull)\n * ```\n */\nexport function notOf(guard: (value: unknown) => boolean): Guard<unknown> {\n\treturn (value: unknown): value is unknown => !guard(value)\n}\n\n/**\n * Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass\n * `base` but not `excluded`.\n *\n * @example\n * ```ts\n * const isNonEmpty = complementOf(isString, isEmptyString)\n * isNonEmpty('hi') // true\n * isNonEmpty('') // false\n * ```\n */\nexport function complementOf<TBase, TExcluded extends TBase>(\n\tbase: Guard<TBase>,\n\texcluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded),\n): Guard<Exclude<TBase, TExcluded>> {\n\treturn (value: unknown): value is Exclude<TBase, TExcluded> => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\treturn !excluded(value)\n\t}\n}\n\n/**\n * Build a guard that accepts values matching at least one of the provided\n * guards — the variadic form of {@link orOf}.\n *\n * @example\n * ```ts\n * const isStringOrBoolean = unionOf(isString, isBoolean)\n * ```\n */\nexport function unionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<GuardType<Gs[number]>>\nexport function unionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>\nexport function unionOf(...guards: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown> {\n\treturn (value: unknown): value is unknown => guards.some((guard) => guard(value))\n}\n\n/**\n * Build a guard that accepts values matching ALL of the provided guards — the\n * variadic form of {@link andOf}.\n *\n * @example\n * ```ts\n * const isNonEmpty = intersectionOf(isString, isNonEmptyString)\n * ```\n */\nexport function intersectionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<IntersectionFromGuards<Gs>>\nexport function intersectionOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown>\nexport function intersectionOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => guards.every((guard) => guard(value))\n}\n\n/**\n * Refine a base guard with an additional predicate that runs only when the base\n * passes.\n *\n * @remarks\n * The predicate receives a value already narrowed to `T`. When the predicate is\n * itself a type guard (`value is U`), the result narrows to `Guard<U>` — it\n * passes only when the value is genuinely a `U`, so the narrowing is sound. Per\n * §14 the returned guard never throws: if `predicate` throws, the throw is\n * contained and the guard reports a non-match.\n *\n * @example\n * ```ts\n * const isPositive = whereOf(isNumber, (n) => n > 0)\n * isPositive(5) // true\n * isPositive(-1) // false\n *\n * // A narrowing predicate refines the result type to Guard<5>\n * const isFive = whereOf(isNumber, (n): n is 5 => n === 5)\n * ```\n */\nexport function whereOf<T, U extends T>(\n\tbase: Guard<T>,\n\tpredicate: (value: T) => value is U,\n): Guard<U>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// `predicate` is user-supplied with no never-throw contract; §14 forbids\n\t\t// the guard from propagating its throw.\n\t\tconst outcome = attempt(() => predicate(value))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Defer guard creation until first use by calling `thunk()` on every\n * invocation.\n *\n * @remarks\n * `thunk` is called on every guard call, not cached — this lets it close over a\n * binding assigned *after* `lazyOf` is called, the primary use case for\n * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard\n * it resolves to) is contained and reported as a non-match.\n *\n * A recursive guard built this way has no cycle/depth detection: a cyclic or\n * pathologically deep input is stack-bounded — the overflow is contained and the\n * guard returns `false` rather than throwing, but it is not validated correctly\n * past that bound.\n *\n * @example\n * ```ts\n * type Tree = { value: number; children: Tree[] }\n * let isTree: Guard<Tree>\n * isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })\n * ```\n */\nexport function lazyOf<T>(thunk: () => Guard<T>): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\t// `thunk` and the guard it returns are user-supplied; §14 forbids\n\t\t// propagating either throw.\n\t\tconst outcome = attempt(() => thunk()(value))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that passes when the base passes AND the projection of the value\n * satisfies the target guard. Still narrows to `T` (the base type) — the target\n * check is a validity constraint on a derived view, not a type transformation.\n *\n * @remarks\n * `project` is a plain `(value: T) => U`. Per §14 the returned guard never\n * throws: a throw from `project` is contained and reported as a non-match.\n * `target` is itself a Guard (already §14-bound), so it stays outside the\n * contained region. (Unlike the reference implementation, there is no\n * \"curried projector\" branch — a projection that legitimately returns a function\n * would be double-invoked under that scheme. Compose explicitly if you need it.)\n *\n * @example\n * ```ts\n * const isBounded = transformOf(\n * isString,\n * (s) => s.trim().length,\n * whereOf(isNumber, (n) => n >= 1 && n <= 50),\n * )\n * isBounded('hello') // true\n * isBounded('') // false\n * ```\n */\nexport function transformOf<T, U>(\n\tbase: Guard<T>,\n\tproject: (value: T) => U,\n\ttarget: Guard<U>,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// `project` is user-supplied with no never-throw contract; §14 forbids the\n\t\t// guard from propagating its throw.\n\t\tconst outcome = attempt(() => project(value))\n\t\treturn outcome.success && target(outcome.value)\n\t}\n}\n\n/**\n * Build a guard that accepts finite numbers within an inclusive `[min, max]`\n * range.\n *\n * @remarks\n * Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /\n * `±Infinity` are rejected before any comparison runs. An absent bound never\n * constrains that side. Reused for a number's own value AND, applied to a\n * `.length`, for string and array length refinements — the single source of the\n * bound logic shared by the compiled guard and parser (compilers.ts).\n *\n * @example\n * ```ts\n * const inRange = boundsOf(1, 5)\n * inRange(3) // true\n * inRange(0) // false — below min\n * inRange(6) // false — above max\n *\n * const atLeastTwo = boundsOf(2)\n * atLeastTwo(2) // true — unbounded above\n * ```\n */\nexport function boundsOf(min?: number, max?: number): Guard<number> {\n\treturn whereOf(\n\t\tisFiniteNumber,\n\t\t(value) => (min === undefined || value >= min) && (max === undefined || value <= max),\n\t)\n}\n\n/**\n * Build a guard that accepts strings matching a regular expression.\n *\n * @example\n * ```ts\n * const isHex = matchOf(/^[0-9a-f]+$/)\n * isHex('1a2f') // true\n * isHex('xyz') // false\n * ```\n */\nexport function matchOf(pattern: RegExp): Guard<string> {\n\treturn whereOf(isString, (value) => pattern.test(value))\n}\n\n/**\n * Build a guard that accepts strings satisfying optional length and pattern\n * refinements — `min` / `max` length and a `pattern`.\n *\n * @remarks\n * Composes {@link isString} with {@link boundsOf} on the string's `.length` and\n * an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns\n * the bare {@link isString} guard (the unconstrained fast path), so an\n * unrefined string leaf pays no wrapping cost. The single source of the string\n * refinement shared by the compiled guard and parser (compilers.ts).\n *\n * @example\n * ```ts\n * const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })\n * isSlug('hello-world') // true\n * isSlug('') // false — below min\n * isSlug('Hello') // false — pattern miss\n *\n * stringOf() // identical to isString\n * ```\n */\nexport function stringOf(options?: {\n\tmin?: number\n\tmax?: number\n\tpattern?: RegExp\n}): Guard<string> {\n\tconst min = options?.min\n\tconst max = options?.max\n\tconst pattern = options?.pattern\n\tif (min === undefined && max === undefined && pattern === undefined) {\n\t\treturn isString\n\t}\n\tconst withinLength = boundsOf(min, max)\n\treturn whereOf(\n\t\tisString,\n\t\t(value) => withinLength(value.length) && (pattern === undefined || pattern.test(value)),\n\t)\n}\n\n/**\n * Extend a guard to also allow `null`.\n *\n * @example\n * ```ts\n * const isNullableString = nullableOf(isString)\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function nullableOf<T>(guard: Guard<T>): Guard<T | null> {\n\treturn (value: unknown): value is T | null => value === null || guard(value)\n}\n\n/**\n * Extend a guard to also allow `undefined` — the optional counterpart of\n * {@link nullableOf}.\n *\n * @example\n * ```ts\n * const isOptionalString = optionalOf(isString)\n * isOptionalString('hi') // true\n * isOptionalString(undefined) // true\n * isOptionalString(null) // false\n * ```\n */\nexport function optionalOf<T>(guard: Guard<T>): Guard<T | undefined> {\n\treturn (value: unknown): value is T | undefined => value === undefined || guard(value)\n}\n","import type { Guard, JSONValue } from './types.js'\nimport type { FieldPath } from './types.js'\nimport { isArray, isFiniteNumber, isJSONValue, isNull, isRecord, isString } from './validators.js'\nimport { resolveField } from './helpers.js'\n\n// AGENTS §14: a parser answers \"give me a `T` or nothing\" — it returns the\n// typed value or `undefined`, and it never throws. Each leaf parser here forms a\n// SOUND pair with the guard for its output TYPE: a guard-valid input is returned\n// UNCHANGED (by identity, never rejected), and every non-`undefined` output\n// satisfies that type guard. The pairings (verified in parsers.test.ts):\n//\n// parseString ↔ isString parseRecord ↔ isRecord\n// parseNumber ↔ isFiniteNumber parseArray ↔ arrayOf(guard) / isArray\n// parseInteger ↔ isInteger parseEnum ↔ literalOf(...allowed)\n// parseBoolean ↔ isBoolean parseNull ↔ isNull\n// parseJSONValue ↔ isJSONValue\n//\n// Coercion of NON-valid inputs (e.g. numeric strings → numbers) is a bonus on\n// top of soundness, not a violation of it — clause A only constrains inputs the\n// guard already accepts.\n//\n// These leaf parsers are deliberately TYPE-only: they know nothing about a\n// shape's `min` / `max` / `pattern` refinements. Those refinements are enforced\n// one layer up, by the compiled parser (compilers.ts `compileParser`), which\n// re-applies the shared refinement combinators (`stringOf` / `boundsOf`,\n// combinators.ts) after coercion — the same source the compiled guard uses. So `createContract(...).parse` IS sound against the FULL\n// guard (refinements included); the split keeps each leaf parser small while the\n// compiler composes the full soundness.\n//\n// Coercion policy — which types cross into which:\n// - number <-> string is BIDIRECTIONAL by design: parseNumber accepts a\n// numeric string ('42' -> 42) and parseString accepts a finite number,\n// stringifying it (42 -> '42'). Use isString / isFiniteNumber directly\n// (never the parser) when you need STRICT type rejection with no coercion.\n// - boolean is a coercion SINK, never a source: parseBoolean accepts\n// 'true'/'false'/'1'/'0' and 1/0 and coerces them TO a boolean, but\n// parseNumber and parseString both reject booleans outright — a boolean\n// never coerces INTO a number or string. This is intentional asymmetry:\n// '1' meaning \"the number one\" and '1' meaning \"true\" are genuinely\n// different domains, so only the boolean parser treats the numeric/string\n// forms as booleans.\n\n// === Primitive parsers\n\n/**\n * Parse an unknown value to a string.\n *\n * @remarks\n * A string is returned unchanged; a finite number is coerced to its decimal\n * string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A string, or `undefined`\n *\n * @example\n * ```ts\n * parseString('hi') // 'hi'\n * parseString(42) // '42'\n * parseString(true) // undefined\n * ```\n */\nexport function parseString(value: unknown): string | undefined {\n\tif (isString(value)) return value\n\tif (isFiniteNumber(value)) return String(value)\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite number.\n *\n * @remarks\n * A finite number is returned unchanged; a non-blank numeric string is parsed\n * via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every\n * other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumber(42) // 42\n * parseNumber('42') // 42\n * parseNumber('abc') // undefined\n * ```\n */\nexport function parseNumber(value: unknown): number | undefined {\n\tif (typeof value === 'number') {\n\t\treturn Number.isFinite(value) ? value : undefined\n\t}\n\tif (isString(value)) {\n\t\tif (value.trim() === '') return undefined\n\t\tconst parsed = Number(value)\n\t\treturn Number.isFinite(parsed) ? parsed : undefined\n\t}\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite integer.\n *\n * @remarks\n * Accepts whatever {@link parseNumber} accepts, then requires the result to have\n * no fractional part. `3.14` / `'3.14'` → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite integer, or `undefined`\n *\n * @example\n * ```ts\n * parseInteger(42) // 42\n * parseInteger(3.14) // undefined\n * ```\n */\nexport function parseInteger(value: unknown): number | undefined {\n\tconst parsed = parseNumber(value)\n\tif (parsed === undefined) return undefined\n\treturn Number.isInteger(parsed) ? parsed : undefined\n}\n\n/**\n * Parse an unknown value to a boolean.\n *\n * @remarks\n * A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /\n * `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything\n * else → `undefined`.\n *\n * @param value - The value to parse\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBoolean(true) // true\n * parseBoolean('1') // true\n * parseBoolean('nope') // undefined\n * ```\n */\nexport function parseBoolean(value: unknown): boolean | undefined {\n\tif (typeof value === 'boolean') return value\n\tif (value === 'true' || value === '1' || value === 1) return true\n\tif (value === 'false' || value === '0' || value === 0) return false\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to `null`.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel every other parser in this file uses. Only `null` passes;\n * every other value (including `undefined`) → `undefined`.\n *\n * @param value - The value to parse\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNull(null) // null\n * parseNull(undefined) // undefined\n * ```\n */\nexport function parseNull(value: unknown): null | undefined {\n\treturn isNull(value) ? value : undefined\n}\n\n// === Structural parsers\n\n/**\n * Parse an unknown value to a plain record — the input reference, never cloned.\n *\n * @param value - The value to parse\n * @returns The record, or `undefined`\n */\nexport function parseRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined\n}\n\n/**\n * Parse an unknown value to an array — the input reference, never cloned —\n * optionally guarding every element.\n *\n * @remarks\n * Without a `guard`, element types are NOT verified; let `T` default to\n * `unknown` rather than asserting a specific element type.\n *\n * @param value - The value to parse\n * @param guard - Optional element guard\n * @returns The array, or `undefined`\n *\n * @example\n * ```ts\n * parseArray([1, 2]) // [1, 2]\n * parseArray([1, 'x'], isNumber) // undefined\n * ```\n */\nexport function parseArray<T = unknown>(\n\tvalue: unknown,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\tif (!isArray<T>(value)) return undefined\n\tif (guard !== undefined && !value.every(guard)) return undefined\n\treturn value\n}\n\n/**\n * Parse an unknown value to a cycle-safe JSON value — the input reference,\n * never cloned.\n *\n * @remarks\n * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it\n * walks the entire tree via {@link isJSONValue} rather than checking only the\n * top-level shape. That walk is cycle-safe and total (never throws) because\n * `isJSONValue` runs its own probe inside a guard, so an adversarial\n * structure (a cycle, a hostile getter) yields `undefined` instead of hanging\n * or throwing.\n *\n * @param value - The value to parse\n * @returns The value, or `undefined` when it is not a valid JSON value\n *\n * @example\n * ```ts\n * parseJSONValue({ a: 1 }) // { a: 1 }\n * parseJSONValue(Number.NaN) // undefined\n * ```\n */\nexport function parseJSONValue(value: unknown): JSONValue | undefined {\n\treturn isJSONValue(value) ? value : undefined\n}\n\n// === Enum parser\n\n/**\n * Parse an unknown value as one of the allowed literal primitives.\n *\n * @remarks\n * Pairs with {@link literalOf} — both match by `Object.is`, so the\n * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive\n * (string, number, or boolean), not only strings. Matching is identity, never\n * cross-type coercion: `parseEnum('1', [1])` stays `undefined`.\n *\n * @param value - The value to parse\n * @param allowed - The permitted literal values\n * @returns The matched literal (by identity), or `undefined`\n *\n * @example\n * ```ts\n * parseEnum('b', ['a', 'b', 'c']) // 'b'\n * parseEnum('z', ['a', 'b', 'c']) // undefined\n * ```\n */\nexport function parseEnum<const T extends string | number | boolean>(\n\tvalue: unknown,\n\tallowed: readonly T[],\n): T | undefined {\n\tfor (const option of allowed) {\n\t\tif (Object.is(value, option)) return option\n\t}\n\treturn undefined\n}\n\n// === Record-field parsers\n\n/**\n * Read and parse a string field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A string, or `undefined`\n */\nexport function parseStringField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): string | undefined {\n\treturn parseString(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-number field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumberField({ age: '42' }, 'age') // 42\n * parseNumberField({}, 'age') // undefined\n * ```\n */\nexport function parseNumberField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseNumber(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-integer field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite integer, or `undefined`\n */\nexport function parseIntegerField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseInteger(resolveField(record, path))\n}\n\n/**\n * Read and parse a boolean field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBooleanField({ on: 'true' }, 'on') // true\n * parseBooleanField({}, 'on') // undefined\n * ```\n */\nexport function parseBooleanField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): boolean | undefined {\n\treturn parseBoolean(resolveField(record, path))\n}\n\n/**\n * Read and parse a `null` field from a record by key or nested key path.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel, which also covers a missing field.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNullField({ value: null }, 'value') // null\n * parseNullField({}, 'value') // undefined\n * ```\n */\nexport function parseNullField(record: Record<string, unknown>, path: FieldPath): null | undefined {\n\treturn parseNull(resolveField(record, path))\n}\n\n/**\n * Read and parse a nested record field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A plain record, or `undefined`\n */\nexport function parseRecordField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): Record<string, unknown> | undefined {\n\treturn parseRecord(resolveField(record, path))\n}\n\n/**\n * Read and parse an array field from a record by key or nested key path,\n * optionally guarding elements.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param guard - Optional element guard\n * @returns An array, or `undefined`\n *\n * @example\n * ```ts\n * parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2]\n * parseArrayField({}, 'tags') // undefined\n * ```\n */\nexport function parseArrayField<T = unknown>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\treturn parseArray(resolveField(record, path), guard)\n}\n\n/**\n * Read and parse an enum field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param allowed - The permitted literal values\n * @returns The matched literal, or `undefined`\n */\nexport function parseEnumField<const T extends string | number | boolean>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tallowed: readonly T[],\n): T | undefined {\n\treturn parseEnum(resolveField(record, path), allowed)\n}\n\n/**\n * Read and parse a JSON-value field from a record by key or nested key path.\n *\n * @remarks\n * Deep-gates the field's whole subtree via {@link parseJSONValue} — see that\n * function's remarks for why this differs from the shallow\n * {@link parseRecordField} / {@link parseArrayField}.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The value, or `undefined`\n *\n * @example\n * ```ts\n * parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 }\n * parseJSONValueField({}, 'data') // undefined\n * ```\n */\nexport function parseJSONValueField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): JSONValue | undefined {\n\treturn parseJSONValue(resolveField(record, path))\n}\n\n// === JSON\n\n/**\n * Parse a JSON string, returning `undefined` instead of throwing.\n *\n * @remarks\n * The safe boundary for untrusted JSON text: a malformed string yields\n * `undefined`, never an exception. Returns `unknown` — a successful parse proves\n * nothing about shape, so narrow the result with a guard (or use\n * {@link parseJSONAs}). A large document is not walked here; parsing is shallow\n * and lazy validation is the caller's to compose.\n *\n * @param value - The JSON string to parse\n * @returns The parsed value, or `undefined` when `value` is not valid JSON\n */\nexport function parseJSON(value: string): unknown {\n\ttry {\n\t\treturn JSON.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Parse a JSON string and validate the result against a guard.\n *\n * @remarks\n * The lazy, safe path from an untrusted string to a typed `T`: parse, then check\n * the parsed value with the guard you bring — typically one composed from the\n * combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is\n * validated, so a large document is never walked in full unless the guard does.\n *\n * @param value - The JSON string to parse\n * @param guard - The guard for the expected shape\n * @returns The parsed value when it satisfies `guard`, otherwise `undefined`\n *\n * @example\n * ```ts\n * const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })\n * parseJSONAs('{\"host\":\"localhost\",\"tags\":[\"a\"]}', isConfig) // { host: 'localhost', tags: ['a'] }\n * parseJSONAs('{\"host\":\"localhost\"}', isConfig) // undefined — guard fails\n * parseJSONAs('not json', isConfig) // undefined — never throws\n * ```\n */\nexport function parseJSONAs<T>(value: string, guard: Guard<T>): T | undefined {\n\tconst parsed = parseJSON(value)\n\tif (parsed === undefined) return undefined\n\treturn guard(parsed) ? parsed : undefined\n}\n","import type {\n\tContractInterface,\n\tContractShape,\n\tGuard,\n\tInfer,\n\tJSONSchema,\n\tParser,\n\tRandomFunction,\n} from './types.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisInteger,\n\tisJSONValue,\n\tisNull,\n\tisRecord,\n\tisString,\n\tisUndefined,\n} from './validators.js'\nimport { attempt, seededRandom } from './helpers.js'\nimport {\n\tarrayOf,\n\tboundsOf,\n\tintersectionOf,\n\tliteralOf,\n\tnullableOf,\n\torOf,\n\trecordOf,\n\tstringOf,\n\tunionOf,\n\twhereOf,\n} from './combinators.js'\nimport { parseBoolean, parseInteger, parseNumber, parseRecord, parseString } from './parsers.js'\n\n// The compilers walk a finite, developer-authored shape tree (never cyclic) and\n// recurse on themselves — branches are kept inline and public per AGENTS §5,\n// never hidden behind private helpers. `compileGuard` / `compileParser` reuse the\n// existing combinators and parsers rather than re-implementing them.\n\n// === Validation\n\n/**\n * Validate that a {@link ContractShape} tree is well-formed — a pure recursive\n * prepass run before compilation.\n *\n * @remarks\n * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this\n * throws a plain `Error` immediately rather than surfacing as a silently-wrong\n * guard, parser, schema, or generator later. Checks, recursively:\n *\n * - An {@link OptionalShape} is only legal as a direct object-property value —\n * `optionalShape` wrapping an array item, a union variant, another\n * optional/nullable's inner shape, `additionalProperties`, or the top-level\n * shape all throw. An object property IS the one legal placement: its value\n * is unwrapped to `.inner` before recursing, so `.inner` itself is validated\n * as a normal (non-optional-wrapping) shape.\n * - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}\n * needs at least one value and rejects non-finite (`NaN` / `Infinity` /\n * `-Infinity`) number values.\n * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}\n * needs `min <= max` when both are set.\n * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer\n * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.\n * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion\n * continues into array items, object properties (and `additionalProperties`\n * when it is a shape), union variants, and optional/nullable inner shapes.\n *\n * @param shape - The shape to validate\n * @throws {Error} When the shape is malformed\n *\n * @example\n * ```ts\n * validateShape(stringShape({ min: 1, max: 10 })) // does not throw\n * validateShape(stringShape({ min: 10, max: 1 })) // throws\n * ```\n */\nexport function validateShape(shape: ContractShape): void {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: a string shape has min greater than max')\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase 'number': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: a number shape has min greater than max')\n\t\t\t}\n\t\t\tif (shape.integer === true) {\n\t\t\t\tconst lo = Math.ceil(shape.min ?? Number.NEGATIVE_INFINITY)\n\t\t\t\tconst hi = Math.floor(shape.max ?? Number.POSITIVE_INFINITY)\n\t\t\t\tif (lo > hi) {\n\t\t\t\t\tthrow new Error('validateShape: an integer number shape has an empty integer range')\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase 'boolean':\n\t\tcase 'null':\n\t\tcase 'json':\n\t\tcase 'raw':\n\t\t\treturn\n\t\tcase 'literal':\n\t\t\tif (shape.values.length === 0) {\n\t\t\t\tthrow new Error('validateShape: a literal shape needs at least one value')\n\t\t\t}\n\t\t\tfor (const value of shape.values) {\n\t\t\t\tif (typeof value === 'number' && !Number.isFinite(value)) {\n\t\t\t\t\tthrow new Error('validateShape: a literal shape may not contain non-finite number values')\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\tcase 'array': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: an array shape has min greater than max')\n\t\t\t}\n\t\t\tvalidateShape(shape.items)\n\t\t\treturn\n\t\t}\n\t\tcase 'object': {\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tvalidateShape(child.type === 'optional' ? child.inner : child)\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tif (extra !== undefined && extra !== true && extra !== false) validateShape(extra)\n\t\t\treturn\n\t\t}\n\t\tcase 'union':\n\t\t\tif (shape.variants.length === 0) {\n\t\t\t\tthrow new Error('validateShape: a union shape needs at least one variant')\n\t\t\t}\n\t\t\tfor (const variant of shape.variants) validateShape(variant)\n\t\t\treturn\n\t\tcase 'optional':\n\t\t\tthrow new Error(\n\t\t\t\t'validateShape: an optional shape may only appear as a direct object-property value',\n\t\t\t)\n\t\tcase 'nullable':\n\t\t\tvalidateShape(shape.inner)\n\t\t\treturn\n\t}\n}\n\n// === Schema\n\n/**\n * Compile a {@link ContractShape} into a JSON Schema document.\n *\n * @remarks\n * Object shapes emit `additionalProperties: false` (unless opened) and list only\n * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:\n * 'null' }`. Emission only — it never inspects a runtime value.\n *\n * @param shape - The shape to compile\n * @returns The emitted JSON Schema\n *\n * @example\n * ```ts\n * compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 }\n * ```\n */\nexport function compileSchema(shape: ContractShape): JSONSchema {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\treturn {\n\t\t\t\ttype: 'string',\n\t\t\t\t...(shape.min !== undefined ? { minLength: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maxLength: shape.max } : {}),\n\t\t\t\t...(shape.pattern !== undefined ? { pattern: shape.pattern.source } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'number':\n\t\t\treturn {\n\t\t\t\ttype: shape.integer === true ? 'integer' : 'number',\n\t\t\t\t...(shape.min !== undefined ? { minimum: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maximum: shape.max } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'boolean':\n\t\t\treturn {\n\t\t\t\ttype: 'boolean',\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'null':\n\t\t\treturn {\n\t\t\t\ttype: 'null',\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'json':\n\t\t\treturn {\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'literal':\n\t\t\treturn {\n\t\t\t\tenum: [...shape.values],\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'array':\n\t\t\treturn {\n\t\t\t\ttype: 'array',\n\t\t\t\titems: compileSchema(shape.items),\n\t\t\t\t...(shape.min !== undefined ? { minItems: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maxItems: shape.max } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'object': {\n\t\t\tconst properties: Record<string, JSONSchema> = {}\n\t\t\tconst required: string[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tproperties[key] = compileSchema(child)\n\t\t\t\tif (child.type !== 'optional') required.push(key)\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tconst additionalProperties: boolean | JSONSchema =\n\t\t\t\textra === true\n\t\t\t\t\t? true\n\t\t\t\t\t: extra !== undefined && extra !== false\n\t\t\t\t\t\t? compileSchema(extra)\n\t\t\t\t\t\t: false\n\t\t\treturn {\n\t\t\t\ttype: 'object',\n\t\t\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t\t\t...(required.length > 0 ? { required } : {}),\n\t\t\t\tadditionalProperties,\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\t}\n\t\tcase 'union':\n\t\t\treturn {\n\t\t\t\t...(shape.mode === 'oneOf'\n\t\t\t\t\t? { oneOf: shape.variants.map((variant) => compileSchema(variant)) }\n\t\t\t\t\t: { anyOf: shape.variants.map((variant) => compileSchema(variant)) }),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'optional':\n\t\t\treturn compileSchema(shape.inner)\n\t\tcase 'nullable':\n\t\t\treturn { anyOf: [compileSchema(shape.inner), { type: 'null' }] }\n\t\tcase 'raw':\n\t\t\treturn shape.schema\n\t}\n}\n\n// === Guard\n\n/**\n * Compile a {@link ContractShape} into a runtime type guard.\n *\n * @remarks\n * Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,\n * `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,\n * and `whereOf` for constraint refinement. Like every guard it is total — it\n * never throws (AGENTS §14).\n *\n * @param shape - The shape to compile\n * @returns A guard narrowing to the shape's inferred type\n *\n * @example\n * ```ts\n * const isUser = compileGuard(objectShape({ name: stringShape() }))\n * isUser({ name: 'Ada' }) // true\n * ```\n */\nexport function compileGuard<S extends ContractShape>(shape: S): Guard<Infer<S>>\nexport function compileGuard(shape: ContractShape): Guard<unknown>\nexport function compileGuard(shape: ContractShape): Guard<unknown> {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\t// `stringOf` returns bare `isString` when unrefined, else composes the\n\t\t\t// length-bounds + pattern refinement — the same guard the parser re-applies.\n\t\t\treturn stringOf({ min: shape.min, max: shape.max, pattern: shape.pattern })\n\t\tcase 'number': {\n\t\t\tconst base = shape.integer === true ? isInteger : isFiniteNumber\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\t// `boundsOf` already refines `isFiniteNumber`; intersect with `isInteger`\n\t\t\t// when the leaf is an integer so both the integrality and the bounds hold.\n\t\t\treturn shape.integer === true\n\t\t\t\t? intersectionOf(isInteger, boundsOf(shape.min, shape.max))\n\t\t\t\t: boundsOf(shape.min, shape.max)\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn isBoolean\n\t\tcase 'null':\n\t\t\treturn isNull\n\t\tcase 'json':\n\t\t\treturn isJSONValue\n\t\tcase 'literal':\n\t\t\treturn literalOf(...shape.values)\n\t\tcase 'array': {\n\t\t\tconst base = arrayOf(compileGuard(shape.items))\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max)\n\t\t\treturn whereOf(base, (value) => withinLength(value.length))\n\t\t}\n\t\tcase 'object': {\n\t\t\t// Honest typing: a null-prototype accumulator so a property literally\n\t\t\t// named '__proto__' becomes an own data key instead of mutating the\n\t\t\t// prototype — the same pattern `pickOf` uses (combinators.ts).\n\t\t\tconst map: Record<string, Guard<unknown>> = Object.create(null)\n\t\t\tconst optionalKeys: string[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional') {\n\t\t\t\t\tmap[key] = compileGuard(child.inner)\n\t\t\t\t\toptionalKeys.push(key)\n\t\t\t\t} else {\n\t\t\t\t\tmap[key] = compileGuard<ContractShape>(child)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\t// Closed object → the exact, optional-key-aware `recordOf`.\n\t\t\tif (extra === undefined || extra === false) {\n\t\t\t\treturn optionalKeys.length > 0 ? recordOf(map, optionalKeys) : recordOf(map)\n\t\t\t}\n\t\t\t// Open object → validate known keys, then accept (`true`) or guard extras.\n\t\t\tconst additional = extra === true ? undefined : compileGuard(extra)\n\t\t\tconst required = Object.keys(map).filter((key) => !optionalKeys.includes(key))\n\t\t\treturn (value: unknown): value is unknown => {\n\t\t\t\tif (!isRecord(value)) return false\n\t\t\t\tfor (const key of required) {\n\t\t\t\t\tif (!Object.hasOwn(value, key)) return false\n\t\t\t\t}\n\t\t\t\t// Contain the whole key-enumeration + value-read walk — a hostile\n\t\t\t\t// getter on `value` must yield `false`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\t\t\tconst guard = Object.hasOwn(map, key) ? map[key] : undefined\n\t\t\t\t\t\tif (guard !== undefined) {\n\t\t\t\t\t\t\tif (!guard(value[key])) return false\n\t\t\t\t\t\t} else if (additional !== undefined && !additional(value[key])) {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\treturn outcome.success && outcome.value\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst guards = shape.variants.map((variant) => compileGuard(variant))\n\t\t\t// A `oneOf`-mode union matches the emitted JSON Schema `oneOf` keyword —\n\t\t\t// EXACTLY one variant must guard-accept the value, not \"at least one\"\n\t\t\t// (unionOf's anyOf semantics). A value matching two-or-more variants is\n\t\t\t// rejected, since it would violate the compiled schema.\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\treturn (value: unknown): value is unknown =>\n\t\t\t\t\tguards.filter((guard) => guard(value)).length === 1\n\t\t\t}\n\t\t\treturn unionOf(...guards)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn orOf(isUndefined, compileGuard(shape.inner))\n\t\tcase 'nullable':\n\t\t\treturn nullableOf(compileGuard(shape.inner))\n\t\tcase 'raw':\n\t\t\t// The tautological always-true guard for `raw` — accepts anything, so `_value` is\n\t\t\t// genuinely unused (the `_` suppresses the unused-arg lint; AGENTS §4.8).\n\t\t\treturn (_value: unknown): _value is unknown => true\n\t}\n}\n\n// === Parser\n\n/**\n * Compile a {@link ContractShape} into an input parser.\n *\n * @remarks\n * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /\n * `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a\n * whole on any required-field failure; a union returns a guard-valid value\n * unchanged, otherwise the first variant that both parses and guards wins.\n *\n * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same\n * combinators `compileGuard` uses — `stringOf` for a string's length/pattern and\n * `boundsOf` for a number's value and an array's length — so a value that coerces\n * but violates a bound parses to `undefined`. The result is full parse↔guard\n * soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's\n * `is`, refinements included.\n *\n * @param shape - The shape to compile\n * @returns A parser yielding the shape's inferred type or `undefined`\n *\n * @example\n * ```ts\n * const parseUser = compileParser(objectShape({ name: stringShape() }))\n * parseUser({ name: 'Ada' }) // { name: 'Ada' }\n * ```\n */\nexport function compileParser<S extends ContractShape>(shape: S): Parser<Infer<S>>\nexport function compileParser(shape: ContractShape): Parser<unknown>\nexport function compileParser(shape: ContractShape): Parser<unknown> {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tif (shape.min === undefined && shape.max === undefined && shape.pattern === undefined) {\n\t\t\t\treturn parseString\n\t\t\t}\n\t\t\t// Coerce by type, then re-apply the SAME refinement the guard enforces (the\n\t\t\t// identical `stringOf`) — a value that parses but violates a bound or the\n\t\t\t// pattern fails the parse (returns `undefined`).\n\t\t\tconst guard = stringOf({ min: shape.min, max: shape.max, pattern: shape.pattern })\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = parseString(value)\n\t\t\t\treturn parsed !== undefined && guard(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst base = shape.integer === true ? parseInteger : parseNumber\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\t// The same bound check the guard applies (integrality is already enforced by\n\t\t\t// `parseInteger`, so only the bounds need re-checking after coercion).\n\t\t\tconst within = boundsOf(shape.min, shape.max)\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = base(value)\n\t\t\t\treturn parsed !== undefined && within(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean\n\t\tcase 'null':\n\t\t\treturn (value) => (value === null ? null : undefined)\n\t\tcase 'json':\n\t\t\treturn (value) => (isJSONValue(value) ? value : undefined)\n\t\t// The literal parser trims a matching string but never numeric-coerces —\n\t\t// `'42'` never parses to the literal `42`; only an exact (post-trim) match\n\t\t// of one of `shape.values` succeeds. This is an intended leniency, not a\n\t\t// soundness gap: a coerced value is always re-checked against `allowed`.\n\t\tcase 'literal': {\n\t\t\tconst allowed = new Set<unknown>(shape.values)\n\t\t\treturn (value) => {\n\t\t\t\tif (allowed.has(value)) return value\n\t\t\t\tif (isString(value)) {\n\t\t\t\t\tconst trimmed = value.trim()\n\t\t\t\t\tif (allowed.has(trimmed)) return trimmed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst item = compileParser(shape.items)\n\t\t\tconst unbounded = shape.min === undefined && shape.max === undefined\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max)\n\t\t\treturn (value) => {\n\t\t\t\tif (!isArray(value)) return undefined\n\t\t\t\tconst result: unknown[] = []\n\t\t\t\tfor (const entry of value) {\n\t\t\t\t\tconst parsed = item(entry)\n\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\tresult.push(parsed)\n\t\t\t\t}\n\t\t\t\t// Enforce the SAME length bounds the guard does (coercion never changes\n\t\t\t\t// length, so this is checked once on the assembled result).\n\t\t\t\treturn unbounded || withinLength(result.length) ? result : undefined\n\t\t\t}\n\t\t}\n\t\t// A closed object (no `additionalProperties`) silently drops unknown keys\n\t\t// present on the input rather than failing the parse — an intended\n\t\t// coercion leniency (the compiled guard still rejects them; this only\n\t\t// matters for guard-invalid inputs handed to `parse`).\n\t\tcase 'object': {\n\t\t\tconst entries: { key: string; parse: Parser<unknown>; optional: boolean }[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tconst optional = child.type === 'optional'\n\t\t\t\tentries.push({ key, parse: compileParser(optional ? child.inner : child), optional })\n\t\t\t}\n\t\t\tconst known = new Set(entries.map((entry) => entry.key))\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tconst additional =\n\t\t\t\textra === undefined || extra === false || extra === true ? undefined : compileParser(extra)\n\t\t\tconst open = extra === true || additional !== undefined\n\t\t\treturn (value) => {\n\t\t\t\tconst record = parseRecord(value)\n\t\t\t\tif (record === undefined) return undefined\n\t\t\t\t// Contain the whole record walk — a hostile getter on `record` must\n\t\t\t\t// yield `undefined`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\t// Honest typing: a null-prototype accumulator so an input own key\n\t\t\t\t\t// literally named '__proto__' lands as an own data key instead of\n\t\t\t\t\t// mutating the prototype (same pattern as `pickOf`).\n\t\t\t\t\tconst result: Record<string, unknown> = Object.create(null)\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst raw = record[entry.key]\n\t\t\t\t\t\tif (raw === undefined) {\n\t\t\t\t\t\t\tif (entry.optional) continue\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst parsed = entry.parse(raw)\n\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\tresult[entry.key] = parsed\n\t\t\t\t\t}\n\t\t\t\t\tif (open) {\n\t\t\t\t\t\tfor (const key of Object.keys(record)) {\n\t\t\t\t\t\t\tif (known.has(key)) continue\n\t\t\t\t\t\t\tif (additional === undefined) {\n\t\t\t\t\t\t\t\tresult[key] = record[key]\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst parsed = additional(record[key])\n\t\t\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\t\t\tresult[key] = parsed\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn result\n\t\t\t\t})\n\t\t\t\treturn outcome.success ? outcome.value : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst variants = shape.variants.map((variant) => ({\n\t\t\t\tparse: compileParser(variant),\n\t\t\t\tguard: compileGuard(variant),\n\t\t\t}))\n\t\t\t// `oneOf` exactly-one semantics (documented on `oneOfShape`): judged on\n\t\t\t// the RAW input's guard matches only — no coercion fallback. Exactly one\n\t\t\t// variant's guard must accept the raw value; that variant's parser then\n\t\t\t// runs (its parse must equal the already guard-valid input by clause A).\n\t\t\t// Zero matches (no variant fits) or two-or-more matches (ambiguous —\n\t\t\t// which variant the value belongs to isn't well-defined) both fail the\n\t\t\t// parse, deliberately simpler than attempting a coercion-then-recheck\n\t\t\t// resolution for ambiguous input.\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\treturn (value) => {\n\t\t\t\t\tconst matches = variants.filter((variant) => variant.guard(value))\n\t\t\t\t\tconst [only] = matches\n\t\t\t\t\treturn matches.length === 1 && only !== undefined ? only.parse(value) : undefined\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn (value) => {\n\t\t\t\t// Identity pass first (AGENTS §14 clause A): a value already valid\n\t\t\t\t// against ANY variant's guard is returned unchanged, so an earlier\n\t\t\t\t// variant's coercion never overwrites a guard-valid input.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tif (variant.guard(value)) return value\n\t\t\t\t}\n\t\t\t\t// Coercion pass: no variant matched as-is, so parse-then-guard,\n\t\t\t\t// first variant that both parses and guards wins.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tconst parsed = variant.parse(value)\n\t\t\t\t\tif (parsed !== undefined && variant.guard(parsed)) return parsed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'optional': {\n\t\t\tconst inner = compileParser(shape.inner)\n\t\t\treturn (value) => (value === undefined ? undefined : inner(value))\n\t\t}\n\t\tcase 'nullable': {\n\t\t\tconst inner = compileParser(shape.inner)\n\t\t\treturn (value) => (value === null ? null : inner(value))\n\t\t}\n\t\tcase 'raw':\n\t\t\treturn (value) => value\n\t}\n}\n\n// === Generator\n\n/**\n * Compile a {@link ContractShape} into a deterministic seed value.\n *\n * @remarks\n * The same shape and the same `random` source always produce the same value, so\n * seed data is reproducible. Defaults to a {@link seededRandom} source seeded\n * from the wall clock when none is supplied. Throws on a degenerate empty\n * `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose\n * generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded\n * schema is arbitrary and cannot be auto-generated) — a programmer error that\n * cannot generate a value (AGENTS §12). `createContract` runs\n * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /\n * bounded shape is normally caught there; these throws remain here as defense\n * for standalone `compileGenerator` use.\n *\n * @param shape - The shape to generate from\n * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)\n * @returns A value matching the shape\n *\n * @example\n * ```ts\n * compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism)\n * ```\n */\nexport function compileGenerator<S extends ContractShape>(\n\tshape: S,\n\trandom?: RandomFunction,\n): Infer<S>\nexport function compileGenerator(shape: ContractShape, random?: RandomFunction): unknown\nexport function compileGenerator(\n\tshape: ContractShape,\n\trandom: RandomFunction = seededRandom(Date.now()),\n): unknown {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tconst min = shape.min ?? 0\n\t\t\tconst max = shape.max ?? Math.max(min, 12)\n\t\t\tconst length = Math.max(min, Math.min(max, 8))\n\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n\t\t\tlet value = ''\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tvalue += alphabet[Math.floor(random() * alphabet.length)]\n\t\t\t}\n\t\t\tif (shape.pattern !== undefined && !shape.pattern.test(value)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way',\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst min = shape.min ?? 0\n\t\t\tconst max = shape.max ?? 100\n\t\t\tif (shape.integer === true) {\n\t\t\t\tconst lo = Math.ceil(min)\n\t\t\t\tconst hi = Math.floor(max)\n\t\t\t\treturn Math.floor(random() * (hi - lo + 1)) + lo\n\t\t\t}\n\t\t\treturn random() * (max - min) + min\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn random() >= 0.5\n\t\tcase 'null':\n\t\t\treturn null\n\t\tcase 'json': {\n\t\t\tconst pick = Math.floor(random() * 5)\n\t\t\tif (pick === 0) return null\n\t\t\tif (pick === 1) return random() >= 0.5\n\t\t\tif (pick === 2) return Math.floor(random() * 1000)\n\t\t\tif (pick === 3) {\n\t\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\t\t\t\tlet value = ''\n\t\t\t\tfor (let index = 0; index < 6; index += 1) {\n\t\t\t\t\tvalue += alphabet[Math.floor(random() * alphabet.length)]\n\t\t\t\t}\n\t\t\t\treturn value\n\t\t\t}\n\t\t\treturn { value: Math.floor(random() * 1000) }\n\t\t}\n\t\tcase 'literal': {\n\t\t\tif (shape.values.length === 0) {\n\t\t\t\tthrow new Error('compileGenerator: a literal shape needs at least one value')\n\t\t\t}\n\t\t\treturn shape.values[Math.floor(random() * shape.values.length)]\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst lo = shape.min ?? Math.min(1, shape.max ?? 1)\n\t\t\tconst hi = shape.max ?? Math.max(lo, 3)\n\t\t\tconst length = Math.floor(random() * (hi - lo + 1)) + lo\n\t\t\tconst result: unknown[] = []\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tresult.push(compileGenerator(shape.items, random))\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'object': {\n\t\t\tconst result: Record<string, unknown> = {}\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional' && random() < 0.3) continue\n\t\t\t\tresult[key] = compileGenerator(child, random)\n\t\t\t}\n\t\t\t// An open object (additionalProperties is a shape, not a boolean) also\n\t\t\t// generates synthetic extra entries so the shape does not trivially\n\t\t\t// generate as `{}` — skip any collision with a declared property name.\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\tconst count = 1 + Math.floor(random() * 2)\n\t\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\t\tconst key = `key${index}`\n\t\t\t\t\tif (Object.hasOwn(result, key)) continue\n\t\t\t\t\tresult[key] = compileGenerator(extra, random)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'union': {\n\t\t\tif (shape.variants.length === 0) {\n\t\t\t\tthrow new Error('compileGenerator: a union shape needs at least one variant')\n\t\t\t}\n\t\t\treturn compileGenerator(shape.variants[Math.floor(random() * shape.variants.length)], random)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn compileGenerator(shape.inner, random)\n\t\tcase 'nullable':\n\t\t\treturn random() < 0.2 ? null : compileGenerator(shape.inner, random)\n\t\tcase 'raw':\n\t\t\tthrow new Error(\n\t\t\t\t'compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way',\n\t\t\t)\n\t}\n}\n\n// === Contract\n\n/**\n * Compile a {@link ContractShape} into a {@link ContractInterface} — the four\n * lockstep outputs from one declaration.\n *\n * @remarks\n * Runs {@link validateShape} first — a malformed shape throws immediately\n * rather than compiling into a silently-wrong contract (AGENTS §12). Then\n * precompiles the schema, guard, and parser once; `generate` walks the shape\n * per call with the supplied random source.\n *\n * @param shape - The shape to compile\n * @returns A contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * const user = createContract(objectShape({ name: stringShape(), age: integerShape() }))\n * user.is({ name: 'Ada', age: 36 }) // true\n * user.parse({ name: 'Ada', age: '36' }) // { name: 'Ada', age: 36 }\n * user.schema // { type: 'object', properties: { … }, … }\n * ```\n */\nexport function createContract<S extends ContractShape>(shape: S): ContractInterface<Infer<S>>\nexport function createContract(shape: ContractShape): ContractInterface<unknown>\nexport function createContract(shape: ContractShape): ContractInterface<unknown> {\n\tvalidateShape(shape)\n\tconst schema = compileSchema(shape)\n\tconst guard = compileGuard(shape)\n\tconst parser = compileParser(shape)\n\treturn {\n\t\tschema,\n\t\tis: guard,\n\t\tparse(value: unknown): unknown {\n\t\t\treturn parser(value)\n\t\t},\n\t\tgenerate(random?: RandomFunction): unknown {\n\t\t\treturn compileGenerator(shape, random)\n\t\t},\n\t}\n}\n","import type {\n\tArrayShape,\n\tArrayShapeOptions,\n\tBooleanShape,\n\tBooleanShapeOptions,\n\tContractShape,\n\tJSONSchema,\n\tJSONShape,\n\tJSONShapeOptions,\n\tLiteralShape,\n\tLiteralShapeOptions,\n\tNullableShape,\n\tNullShape,\n\tNullShapeOptions,\n\tNumberShape,\n\tNumberShapeOptions,\n\tObjectShape,\n\tObjectShapeOptions,\n\tOptionalShape,\n\tRawShape,\n\tRecordShapeOptions,\n\tStringShape,\n\tStringShapeOptions,\n\tUnionShape,\n} from './types.js'\n\n// The builders return the parameterized types.ts interfaces (e.g. `ArrayShape<S>`,\n// `ObjectShape<P>`), never inline object literals — the generic parameter keeps\n// `Infer<typeof shape>` exact while the return type still enforces conformance to\n// the shared shape interface.\n\n// Shape builders — pure constructors for the `ContractShape` union. Each returns\n// a plain descriptor; the compilers (compilers.ts) turn it into a guard, parser,\n// schema, and generator. The precise return types (e.g. literal tuples, generic\n// `items` / `properties`) are preserved so `Infer<typeof shape>` stays exact.\n\n// === Primitives\n\n/**\n * Build a string {@link StringShape}.\n *\n * @param options - Optional length (`min` / `max`), `pattern`, and `description`\n * @returns A string shape\n *\n * @example\n * ```ts\n * const name = stringShape({ min: 1, max: 80, description: 'Display name' })\n * ```\n */\nexport function stringShape(options?: StringShapeOptions): StringShape {\n\treturn {\n\t\ttype: 'string',\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tpattern: options?.pattern,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a numeric {@link NumberShape}.\n *\n * @param options - Optional bounds (`min` / `max`), `integer`, and `description`\n * @returns A number shape\n *\n * @example\n * ```ts\n * const age = numberShape({ min: 0, max: 120 })\n * ```\n */\nexport function numberShape(options?: NumberShapeOptions): NumberShape {\n\treturn {\n\t\ttype: 'number',\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tinteger: options?.integer,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an integer {@link NumberShape} — forces `integer: true`.\n *\n * @remarks\n * The emitted JSON Schema uses `\"type\": \"integer\"` and the guard rejects\n * fractional numbers.\n *\n * @param options - Optional bounds and `description` (no `integer` key)\n * @returns An integer number shape\n */\nexport function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape {\n\treturn {\n\t\ttype: 'number',\n\t\tinteger: true,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a {@link BooleanShape}.\n *\n * @param options - Optional `description`\n * @returns A boolean shape\n *\n * @example\n * ```ts\n * const active = booleanShape({ description: 'Whether the record is active' })\n * ```\n */\nexport function booleanShape(options?: BooleanShapeOptions): BooleanShape {\n\treturn {\n\t\ttype: 'boolean',\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a {@link NullShape}.\n *\n * @param options - Optional `description`\n * @returns A null shape\n *\n * @example\n * ```ts\n * const empty = nullShape()\n * ```\n */\nexport function nullShape(options?: NullShapeOptions): NullShape {\n\treturn { type: 'null', description: options?.description }\n}\n\n/**\n * Build a literal shape from a fixed set of primitive values.\n *\n * @param values - The permitted literals\n * @param options - Optional `description`\n * @returns A literal shape whose `Infer` is the union of `values`\n *\n * @example\n * ```ts\n * const role = literalShape(['admin', 'member', 'guest'])\n * // Infer<typeof role> = 'admin' | 'member' | 'guest'\n *\n * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })\n * ```\n */\nexport function literalShape<const T extends readonly (string | number | boolean)[]>(\n\tvalues: T,\n\toptions?: LiteralShapeOptions,\n): LiteralShape<T> {\n\treturn { type: 'literal', values, description: options?.description }\n}\n\n// === Collections\n\n/**\n * Build an {@link ArrayShape} from an element shape.\n *\n * @param items - The element shape\n * @param options - Optional length bounds and `description`\n * @returns An array shape\n *\n * @example\n * ```ts\n * const tags = arrayShape(stringShape(), { max: 10 })\n * ```\n */\nexport function arrayShape<S extends ContractShape>(\n\titems: S,\n\toptions?: ArrayShapeOptions,\n): ArrayShape<S> {\n\treturn {\n\t\ttype: 'array',\n\t\titems,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an {@link ObjectShape} from a property map.\n *\n * @remarks\n * Wrap any property in {@link optionalShape} to allow its absence. By default\n * the compiled guard rejects unknown keys; pass `additionalProperties` to open\n * the object.\n *\n * @param properties - Map of property names to child shapes\n * @param options - Optional `additionalProperties` and `description`\n * @returns An object shape\n *\n * @example\n * ```ts\n * const user = objectShape({\n * \tname: stringShape({ min: 1 }),\n * \tage: integerShape({ min: 0, max: 120 }),\n * \tbio: optionalShape(stringShape()),\n * })\n * ```\n */\nexport function objectShape<\n\tP extends Readonly<Record<string, ContractShape>>,\n\tconst A extends boolean | ContractShape = false,\n>(properties: P, options?: ObjectShapeOptions<A>): ObjectShape<P, A> {\n\treturn {\n\t\ttype: 'object',\n\t\tproperties,\n\t\tadditionalProperties: options?.additionalProperties,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an open {@link ObjectShape} with no fixed properties — a dictionary.\n *\n * @remarks\n * Every value is validated against `values`; keys are unconstrained. Equivalent\n * to `objectShape({}, { additionalProperties: values })`.\n *\n * @param values - The shape every value must match\n * @param options - Optional `description`\n * @returns An open object shape\n *\n * @example\n * ```ts\n * const bindings = recordShape(numberShape()) // ~ Record<string, number>\n * ```\n */\nexport function recordShape<S extends ContractShape>(\n\tvalues: S,\n\toptions?: RecordShapeOptions,\n): ObjectShape<Record<never, never>, S> {\n\treturn {\n\t\ttype: 'object',\n\t\tproperties: {},\n\t\tadditionalProperties: values,\n\t\tdescription: options?.description,\n\t}\n}\n\n// === Composition\n\n/**\n * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).\n *\n * @param variants - The candidate shapes; the first match wins at runtime\n * @returns A union shape whose `Infer` is the union of the variants\n *\n * @example\n * ```ts\n * const id = unionShape(stringShape(), integerShape())\n * // Infer<typeof id> = string | number\n * ```\n */\nexport function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V> {\n\treturn { type: 'union', variants }\n}\n\n/**\n * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.\n *\n * @remarks\n * Unlike {@link unionShape} (`anyOf` — at least one variant matches),\n * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:\n *\n * - **Guard**: accepts the value only when exactly one variant's guard\n * accepts it. A value matching two-or-more variants — which would violate\n * the emitted `oneOf` schema — is rejected, even though it would pass\n * {@link unionShape}'s guard.\n * - **Parser**: judged on the RAW input's guard matches only, with NO\n * coercion fallback for an ambiguous input. When exactly one variant's\n * guard accepts the raw value, that variant's parser runs. Zero matches or\n * two-or-more matches both parse to `undefined` — a value ambiguous\n * between variants has no well-defined coercion target.\n *\n * Prefer {@link unionShape} when a value may legitimately satisfy more than\n * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer\n * `oneOfShape` when overlap between variants indicates malformed input that\n * must be rejected.\n *\n * @param variants - The candidate shapes\n * @returns A union shape with `mode: 'oneOf'`\n *\n * @example\n * ```ts\n * const id = oneOfShape(numberShape(), integerShape())\n * // 3 fails — matches both numberShape and integerShape\n * // 3.5 passes — matches numberShape only\n * ```\n */\nexport function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V> {\n\treturn { type: 'union', variants, mode: 'oneOf' }\n}\n\n/**\n * Wrap a shape so it may be absent (`undefined`).\n *\n * @remarks\n * As an {@link objectShape} property, the field becomes a true optional property\n * in the inferred type.\n *\n * @param inner - The wrapped shape\n * @returns An optional shape\n */\nexport function optionalShape<S extends ContractShape>(inner: S): OptionalShape<S> {\n\treturn { type: 'optional', inner }\n}\n\n/**\n * Wrap a shape so it may be `null`.\n *\n * @param inner - The wrapped shape\n * @returns A nullable shape\n *\n * @example\n * ```ts\n * const bio = nullableShape(stringShape())\n * // Infer<typeof bio> = string | null\n * ```\n */\nexport function nullableShape<S extends ContractShape>(inner: S): NullableShape<S> {\n\treturn { type: 'nullable', inner }\n}\n\n// === Escape hatch\n\n/**\n * Build a {@link JSONShape}.\n *\n * @remarks\n * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary\n * schema fragment and accepts anything at runtime, while `jsonShape` validates\n * that a value is real JSON (via {@link isJSONValue}).\n *\n * @param options - Optional `description`\n * @returns A JSON passthrough shape\n *\n * @example\n * ```ts\n * const payload = jsonShape({ description: 'Arbitrary JSON payload' })\n * ```\n */\nexport function jsonShape(options?: JSONShapeOptions): JSONShape {\n\treturn { type: 'json', description: options?.description }\n}\n\n/**\n * Build a {@link RawShape} from a JSON Schema fragment.\n *\n * @remarks\n * For values the shape DSL can't express. The compiled guard accepts any value;\n * the parser passes it through; the schema is emitted verbatim.\n *\n * @param schema - The JSON Schema fragment to embed\n * @returns A raw shape\n *\n * @example\n * ```ts\n * const custom = rawShape({ type: 'string', format: 'uuid' })\n * ```\n */\nexport function rawShape(schema: JSONSchema): RawShape {\n\treturn { type: 'raw', schema }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,oBAA+C,OAAO,OAAO;CACzE;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;;ACID,SAAgB,OAAO,OAA+B;CACrD,OAAO,UAAU;AAClB;;;;;;;;;AAUA,SAAgB,YAAY,OAAoC;CAC/D,OAAO,UAAU,KAAA;AAClB;;;;;;;;;;AAWA,SAAgB,UAAa,OAAyC;CACrE,OAAO,UAAU,QAAQ,UAAU,KAAA;AACpC;;;;;;;;;AAUA,SAAgB,SAAS,OAAiC;CACzD,OAAO,OAAO,UAAU;AACzB;;;;;;;;;;;;;;AAeA,SAAgB,SAA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;CACpE,OAAO;EACN,MAAM;EACN;EACA,sBAAsB,SAAS;EAC/B,aAAa,SAAS;CACvB;AACD;;;;;;;;;;;;;;;;;AAkBA,SAAgB,YACf,QACA,SACuC;CACvC,OAAO;EACN,MAAM;EACN,YAAY,CAAC;EACb,sBAAsB;EACtB,aAAa,SAAS;CACvB;AACD;;;;;;;;;;;;;AAgBA,SAAgB,WAA+C,GAAG,UAA4B;CAC7F,OAAO;EAAE,MAAM;EAAS;CAAS;AAClC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,WAA+C,GAAG,UAA4B;CAC7F,OAAO;EAAE,MAAM;EAAS;EAAU,MAAM;CAAQ;AACjD;;;;;;;;;;;AAYA,SAAgB,cAAuC,OAA4B;CAClF,OAAO;EAAE,MAAM;EAAY;CAAM;AAClC;;;;;;;;;;;;;AAcA,SAAgB,cAAuC,OAA4B;CAClF,OAAO;EAAE,MAAM;EAAY;CAAM;AAClC;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,SAAuC;CAChE,OAAO;EAAE,MAAM;EAAQ,aAAa,SAAS;CAAY;AAC1D;;;;;;;;;;;;;;;;AAiBA,SAAgB,SAAS,QAA8B;CACtD,OAAO;EAAE,MAAM;EAAO;CAAO;AAC9B"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/combinators.ts","../../../src/core/parsers.ts","../../../src/core/compilers.ts","../../../src/core/inferers.ts","../../../src/core/shapers.ts"],"sourcesContent":["import type { JSONSchemaType } from './types.js'\n\n// JSON-related constants. Kept as plain frozen data so the shipped combinators\n// and parsers operate on them directly — there is deliberately no bespoke\n// JSON-Schema guard (AGENTS §14 — the deep recursive validators stay out by\n// design).\n\n/**\n * The seven standard JSON Schema `type` names, frozen.\n *\n * @remarks\n * The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose\n * it with the shipped primitives instead of reaching for a bespoke guard:\n * `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and\n * `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`\n * is the parser.\n *\n * @example\n * ```ts\n * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'\n *\n * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>\n * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined\n * ```\n */\nexport const JSON_SCHEMA_TYPES: readonly JSONSchemaType[] = Object.freeze([\n\t'null',\n\t'boolean',\n\t'object',\n\t'array',\n\t'number',\n\t'integer',\n\t'string',\n])\n\n// Reporting-surface bounds (`compileReporter` / `ContractInterface.explain`).\n\n/**\n * The maximum number of {@link Fault} entries a single `explain` report ever\n * returns, frozen.\n *\n * @remarks\n * Bounds the report against adversarial input (a giant array, a wide record) —\n * `compileReporter` collects faults in stable pre-order and stops once this cap\n * is reached, so the report size (and the work to build it) stays finite and\n * deterministic regardless of the input's size.\n */\nexport const FAULT_LIMIT = 64\n\n/**\n * The maximum character length of a {@link preview}-rendered string, frozen.\n *\n * @remarks\n * A previewed string longer than this is clipped with a trailing `…` so a\n * {@link Fault}'s `received` field never embeds an unbounded amount of\n * untrusted text.\n */\nexport const PREVIEW_LIMIT = 64\n\n// Value-to-schema inference bounds (`valueToSchema` / `samplesToSchema`).\n\n/**\n * The default maximum object/array nesting depth {@link valueToSchema} walks,\n * frozen.\n *\n * @remarks\n * Bounds inference against adversarial or cyclic runtime input — once the\n * remaining depth budget reaches zero, inference stops descending and emits\n * the empty accept-anything schema `{}` for that branch instead of recursing\n * further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.\n */\nexport const INFER_DEPTH_LIMIT = 32\n\n/**\n * The default maximum number of object properties / array elements\n * {@link valueToSchema} samples per container, frozen.\n *\n * @remarks\n * Bounds the work (and the emitted schema's size) against a wide record or a\n * huge array — properties/elements beyond this cap are never inspected.\n * Overridable per call via {@link ValueToSchemaOptions.maxProperties}.\n */\nexport const INFER_BREADTH_LIMIT = 256\n\n/**\n * The default maximum number of distinct values a multi-sample slot may hold\n * before enum inference gives up and falls back to a bare `type`, frozen.\n *\n * @remarks\n * Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples}\n * will emit — a slot with distinct-value count at or above this limit is\n * treated as unbounded (an ID column, not a category) and never gets an\n * `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum}\n * (which gates whether enum inference runs at all).\n */\nexport const INFER_ENUM_LIMIT = 12\n\n/**\n * The maximum string length {@link stringToFormat} attempts to classify,\n * frozen.\n *\n * @remarks\n * Bounds per-string format-detection work: a value longer than this returns\n * `undefined` immediately, before any pattern match runs. 128 sits\n * comfortably above the longest real format token — an RFC 3339 date-time\n * with fractional seconds and a UTC offset — so no legitimate classification\n * changes; only pathologically long strings (a multi-megabyte payload passed\n * as a candidate email/URI) are skipped.\n */\nexport const FORMAT_MAX_LENGTH = 128\n\n/**\n * Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats\n * (`uuid` / `email` / `uri`), frozen as data.\n *\n * @remarks\n * The ISO-8601 date/time formats are NOT listed here — they additionally\n * require an attempt-guarded `Date` validity check, so their pattern lives\n * inline in `stringToFormat` rather than as reusable standalone data.\n */\nexport const FORMAT_PATTERNS: Readonly<Record<'uuid' | 'email' | 'uri', RegExp>> = Object.freeze({\n\tuuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n\temail: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n\turi: /^[a-z][a-z0-9+.-]*:\\/\\//i,\n})\n","import type {\n\tAnyAsyncFunction,\n\tAnyConstructor,\n\tAnyFunction,\n\tJSONPrimitive,\n\tJSONValue,\n\tZeroArgAsyncFunction,\n\tZeroArgFunction,\n} from './types.js'\nimport { attempt, enumerableSymbolCount } from './helpers.js'\n\n// AGENTS §14: guards are total functions — a guard NEVER throws. Adversarial\n// input (hostile getters, exotic objects, cycles) returns `false`, never an\n// error. Guards built from a single `typeof` / strict-equality test are\n// immediately total — no probe of the value's internals can throw. Every\n// OTHER guard here probes the value in some way — a property read through\n// `Reflect.get`, a structural walk (`isPromiseLike`, `isIterable`,\n// `isAsyncIterable`, `isJSONValue`, `isRecord`), an `instanceof` check (which\n// invokes the target's `[Symbol.hasInstance]` / triggers a `getPrototypeOf`\n// trap), or an own-key enumeration (`isEmptyObject` / `isNonEmptyObject`) —\n// so a hostile getter, a revoked `Proxy`, or an exotic trap can throw\n// mid-probe. Totality is NOT automatic for these: each contains its\n// probe/walk in `attempt` (see ./helpers.js) and returns `false` on a caught\n// throw. Every `instanceof`-based guard in this file routes through the\n// shared {@link isInstance} helper, which is the one place that containment\n// lives for that family.\n\n// === Primitive guards\n\n/** Determine whether a value is `null`.\n *\n * @example\n * ```ts\n * isNull(null) // true\n * isNull(undefined) // false\n * ```\n */\nexport function isNull(value: unknown): value is null {\n\treturn value === null\n}\n\n/** Determine whether a value is `undefined`.\n *\n * @example\n * ```ts\n * isUndefined(undefined) // true\n * isUndefined(null) // false\n * ```\n */\nexport function isUndefined(value: unknown): value is undefined {\n\treturn value === undefined\n}\n\n/** Determine whether a value is defined (neither `null` nor `undefined`).\n *\n * @example\n * ```ts\n * isDefined('hi') // true\n * isDefined(null) // false\n * isDefined(undefined) // false\n * ```\n */\nexport function isDefined<T>(value: T | null | undefined): value is T {\n\treturn value !== null && value !== undefined\n}\n\n/** Determine whether a value is a string.\n *\n * @example\n * ```ts\n * isString('hi') // true\n * isString(42) // false\n * ```\n */\nexport function isString(value: unknown): value is string {\n\treturn typeof value === 'string'\n}\n\n/**\n * Determine whether a value is a number.\n *\n * @remarks\n * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.\n *\n * @example\n * ```ts\n * isNumber(42) // true\n * isNumber(Number.NaN) // true — NaN is still a number\n * isNumber('42') // false\n * ```\n */\nexport function isNumber(value: unknown): value is number {\n\treturn typeof value === 'number'\n}\n\n/** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).\n *\n * @example\n * ```ts\n * isFiniteNumber(42) // true\n * isFiniteNumber(Number.NaN) // false\n * isFiniteNumber(Infinity) // false\n * ```\n */\nexport function isFiniteNumber(value: unknown): value is number {\n\treturn typeof value === 'number' && Number.isFinite(value)\n}\n\n/** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).\n *\n * @example\n * ```ts\n * isInteger(3) // true\n * isInteger(3.5) // false\n * ```\n */\nexport function isInteger(value: unknown): value is number {\n\treturn Number.isInteger(value)\n}\n\n/** Determine whether a value is a boolean.\n *\n * @example\n * ```ts\n * isBoolean(true) // true\n * isBoolean(1) // false\n * ```\n */\nexport function isBoolean(value: unknown): value is boolean {\n\treturn typeof value === 'boolean'\n}\n\n/** Determine whether a value is exactly `true`.\n *\n * @example\n * ```ts\n * isTrue(true) // true\n * isTrue(false) // false\n * ```\n */\nexport function isTrue(value: unknown): value is true {\n\treturn value === true\n}\n\n/** Determine whether a value is exactly `false`.\n *\n * @example\n * ```ts\n * isFalse(false) // true\n * isFalse(true) // false\n * ```\n */\nexport function isFalse(value: unknown): value is false {\n\treturn value === false\n}\n\n/** Determine whether a value is a bigint.\n *\n * @example\n * ```ts\n * isBigInt(1n) // true\n * isBigInt(1) // false\n * ```\n */\nexport function isBigInt(value: unknown): value is bigint {\n\treturn typeof value === 'bigint'\n}\n\n/** Determine whether a value is a symbol.\n *\n * @example\n * ```ts\n * isSymbol(Symbol('x')) // true\n * isSymbol('x') // false\n * ```\n */\nexport function isSymbol(value: unknown): value is symbol {\n\treturn typeof value === 'symbol'\n}\n\n/** Determine whether a value is callable.\n *\n * @example\n * ```ts\n * isFunction(() => {}) // true\n * isFunction({}) // false\n * ```\n */\nexport function isFunction(value: unknown): value is AnyFunction {\n\treturn typeof value === 'function'\n}\n\n/** Determine whether a value is a string or `null`.\n *\n * @example\n * ```ts\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function isNullableString(value: unknown): value is string | null {\n\treturn value === null || isString(value)\n}\n\n/** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`).\n *\n * @example\n * ```ts\n * isNullableNumber(42) // true\n * isNullableNumber(null) // true\n * isNullableNumber('hi') // false\n * ```\n */\nexport function isNullableNumber(value: unknown): value is number | null {\n\treturn value === null || isNumber(value)\n}\n\n/** Determine whether a value is a boolean or `null`.\n *\n * @example\n * ```ts\n * isNullableBoolean(true) // true\n * isNullableBoolean(null) // true\n * isNullableBoolean(1) // false\n * ```\n */\nexport function isNullableBoolean(value: unknown): value is boolean | null {\n\treturn value === null || isBoolean(value)\n}\n\n// === Built-in guards\n//\n// The `instanceof`-based guard families below (Date/RegExp/Error/Promise,\n// Map/Set/WeakMap/WeakSet, the typed-array guards) are same-realm checks:\n// `instanceof` compares against the constructor's prototype in the CURRENT\n// realm, so a value built by another realm (a different `vm.Context`, iframe,\n// or worker global) fails even when it is structurally identical. This is a\n// known, accepted limitation — cross-realm identity would require duck-typing\n// every built-in, which trades soundness for portability.\n\n/**\n * Determine whether a value is an instance of a constructor, contained against\n * a throwing `instanceof` check.\n *\n * @remarks\n * The low-level total helper every `instanceof`-based guard in this file (and\n * the `instanceOf` combinator) routes through. A bare `value instanceof X` is\n * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a\n * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when\n * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This\n * wraps the check in {@link attempt} (see ./helpers.js) so any such throw\n * yields `false` instead of escaping.\n *\n * @param value - The value to test\n * @param ctor - The constructor to test against\n * @returns `true` when `value instanceof ctor`, `false` on a non-match or a\n * contained throw\n *\n * @example\n * ```ts\n * isInstance(new Date(), Date) // true\n * isInstance({}, Date) // false\n * ```\n */\nexport function isInstance<C>(\n\tvalue: unknown,\n\tctor: C,\n): value is InstanceType<C & AnyConstructor<object>> {\n\t// `ctor` is narrowed to a function through `isFunction` before the `instanceof`\n\t// check — an unconstrained generic RHS loses TS's built-in instanceof leniency\n\t// once nested inside another generic call (the `attempt` callback), so the\n\t// narrowing keeps this call legal without a constraint that would reject\n\t// combinators.ts's `instanceOf`, which validates `ctor` separately.\n\tconst target: unknown = ctor\n\tconst outcome = attempt(() => isFunction(target) && value instanceof target)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a `Date`.\n *\n * @example\n * ```ts\n * isDate(new Date()) // true\n * isDate('2024-01-01') // false\n * ```\n */\nexport function isDate(value: unknown): value is Date {\n\treturn isInstance(value, Date)\n}\n\n/** Determine whether a value is a `RegExp`.\n *\n * @example\n * ```ts\n * isRegExp(/a/) // true\n * isRegExp('a') // false\n * ```\n */\nexport function isRegExp(value: unknown): value is RegExp {\n\treturn isInstance(value, RegExp)\n}\n\n/** Determine whether a value is an `Error`.\n *\n * @example\n * ```ts\n * isError(new Error('boom')) // true\n * isError('boom') // false\n * ```\n */\nexport function isError(value: unknown): value is Error {\n\treturn isInstance(value, Error)\n}\n\n/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve()) // true\n * isPromise({ then() {} }) // false\n * ```\n */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n\treturn isInstance(value, Promise)\n}\n\n/**\n * Determine whether a value is promise-like — an object exposing callable\n * `then`, `catch`, and `finally` methods.\n *\n * @remarks\n * Accepts any object with all three methods, not only native `Promise`\n * instances. Use {@link isPromise} when you specifically need `instanceof Promise`.\n *\n * @example\n * ```ts\n * isPromiseLike(Promise.resolve()) // true\n * isPromiseLike({ then() {}, catch() {}, finally() {} }) // true\n * isPromiseLike({ then() {} }) // false\n * ```\n */\nexport function isPromiseLike<T = unknown>(\n\tvalue: unknown,\n): value is Promise<T> | (PromiseLike<T> & { catch: unknown; finally: unknown }) {\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => {\n\t\tconst thenValue = Reflect.get(value, 'then')\n\t\tconst catchValue = Reflect.get(value, 'catch')\n\t\tconst finallyValue = Reflect.get(value, 'finally')\n\t\treturn isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue)\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is an `ArrayBuffer`.\n *\n * @example\n * ```ts\n * isArrayBuffer(new ArrayBuffer(8)) // true\n * isArrayBuffer([]) // false\n * ```\n */\nexport function isArrayBuffer(value: unknown): value is ArrayBuffer {\n\treturn isInstance(value, ArrayBuffer)\n}\n\n/**\n * Determine whether a value is a `SharedArrayBuffer`.\n *\n * @remarks\n * Guards the global existence of `SharedArrayBuffer` first — safe where it is\n * absent or disabled (e.g. a context that is not cross-origin isolated).\n *\n * @example\n * ```ts\n * isSharedArrayBuffer(new SharedArrayBuffer(8)) // true\n * isSharedArrayBuffer(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n\treturn typeof SharedArrayBuffer !== 'undefined' && isInstance(value, SharedArrayBuffer)\n}\n\n// === Protocol guards\n\n/**\n * Determine whether a value implements the iterable protocol (`Symbol.iterator`).\n *\n * @remarks\n * Strings are explicitly included: a string has a callable `Symbol.iterator`\n * but is not an object, so the generic object path alone would miss it.\n *\n * @example\n * ```ts\n * isIterable([1, 2]) // true\n * isIterable('abc') // true\n * isIterable({ a: 1 }) // false\n * ```\n */\nexport function isIterable<T = unknown>(value: unknown): value is Iterable<T> {\n\tif (isString(value)) {\n\t\treturn true\n\t}\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.iterator)))\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).\n *\n * @example\n * ```ts\n * isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true\n * isAsyncIterable([1, 2]) // false\n * ```\n */\nexport function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T> {\n\tif (!isObject(value)) {\n\t\treturn false\n\t}\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)))\n\treturn outcome.success && outcome.value\n}\n\n// === Object & collection guards\n\n/**\n * Determine whether a value is a non-null object.\n *\n * @remarks\n * `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use\n * {@link isRecord} when you need a plain-record check.\n *\n * @example\n * ```ts\n * isObject({}) // true\n * isObject([]) // true\n * isObject(null) // false\n * ```\n */\nexport function isObject(value: unknown): value is object {\n\treturn typeof value === 'object' && value !== null\n}\n\n/**\n * Determine whether a value is a plain record (object literal or null-prototype),\n * not an array or class instance.\n *\n * @remarks\n * Use instead of {@link isObject} to distinguish a plain `{}` /\n * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain\n * test is realm-agnostic: rather than comparing against the current realm's\n * `Object.prototype` (which a plain object from another `vm.Context`, iframe,\n * or worker would fail), it accepts any value whose prototype is `null`, OR\n * whose prototype's own prototype is `null` — the shape every plain object\n * has in every realm, since `Object.prototype` itself always sits one step\n * above `null`. Arrays and class instances are still rejected: an array's\n * prototype chain runs through `Array.prototype` before `null`, and a class\n * instance's runs through the class's own prototype. The whole body runs\n * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile\n * `getPrototypeOf` trap cannot escape as a thrown error.\n *\n * @example\n * ```ts\n * isRecord({ a: 1 }) // true\n * isRecord(Object.create(null)) // true\n * isRecord([]) // false\n * isRecord(new Date()) // false\n * ```\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\tconst outcome = attempt(() => {\n\t\tif (!isObject(value) || isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst prototype = Object.getPrototypeOf(value)\n\t\treturn prototype === null || Object.getPrototypeOf(prototype) === null\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a `Map`.\n *\n * @example\n * ```ts\n * isMap(new Map()) // true\n * isMap({}) // false\n * ```\n */\nexport function isMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V> {\n\treturn isInstance(value, Map)\n}\n\n/** Determine whether a value is a `Set`.\n *\n * @example\n * ```ts\n * isSet(new Set()) // true\n * isSet([]) // false\n * ```\n */\nexport function isSet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn isInstance(value, Set)\n}\n\n/** Determine whether a value is a `WeakMap`.\n *\n * @example\n * ```ts\n * isWeakMap(new WeakMap()) // true\n * isWeakMap({}) // false\n * ```\n */\nexport function isWeakMap(value: unknown): value is WeakMap<object, unknown> {\n\treturn isInstance(value, WeakMap)\n}\n\n/** Determine whether a value is a `WeakSet`.\n *\n * @example\n * ```ts\n * isWeakSet(new WeakSet()) // true\n * isWeakSet({}) // false\n * ```\n */\nexport function isWeakSet(value: unknown): value is WeakSet<object> {\n\treturn isInstance(value, WeakSet)\n}\n\n// === Array & typed-array guards\n\n/** Determine whether a value is an array.\n *\n * @example\n * ```ts\n * isArray([1, 2]) // true\n * isArray('12') // false\n * ```\n */\nexport function isArray<T = unknown>(value: unknown): value is readonly T[] {\n\treturn Array.isArray(value)\n}\n\n/** Determine whether a value is a `DataView`.\n *\n * @example\n * ```ts\n * isDataView(new DataView(new ArrayBuffer(8))) // true\n * isDataView(new ArrayBuffer(8)) // false\n * ```\n */\nexport function isDataView(value: unknown): value is DataView<ArrayBufferLike> {\n\treturn isInstance(value, DataView)\n}\n\n/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).\n *\n * @example\n * ```ts\n * isArrayBufferView(new Uint8Array(4)) // true\n * isArrayBufferView([1, 2, 3, 4]) // false\n * ```\n */\nexport function isArrayBufferView(value: unknown): value is ArrayBufferView {\n\treturn ArrayBuffer.isView(value)\n}\n\n/** Determine whether a value is an `Int8Array`.\n *\n * @example\n * ```ts\n * isInt8Array(new Int8Array(2)) // true\n * isInt8Array(new Uint8Array(2)) // false\n * ```\n */\nexport function isInt8Array(value: unknown): value is Int8Array {\n\treturn isInstance(value, Int8Array)\n}\n\n/** Determine whether a value is a `Uint8Array`.\n *\n * @example\n * ```ts\n * isUint8Array(new Uint8Array(2)) // true\n * isUint8Array(new Int8Array(2)) // false\n * ```\n */\nexport function isUint8Array(value: unknown): value is Uint8Array {\n\treturn isInstance(value, Uint8Array)\n}\n\n/** Determine whether a value is a `Uint8ClampedArray`.\n *\n * @example\n * ```ts\n * isUint8ClampedArray(new Uint8ClampedArray(2)) // true\n * isUint8ClampedArray(new Uint8Array(2)) // false\n * ```\n */\nexport function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray {\n\treturn isInstance(value, Uint8ClampedArray)\n}\n\n/** Determine whether a value is an `Int16Array`.\n *\n * @example\n * ```ts\n * isInt16Array(new Int16Array(2)) // true\n * isInt16Array(new Int8Array(2)) // false\n * ```\n */\nexport function isInt16Array(value: unknown): value is Int16Array {\n\treturn isInstance(value, Int16Array)\n}\n\n/** Determine whether a value is a `Uint16Array`.\n *\n * @example\n * ```ts\n * isUint16Array(new Uint16Array(2)) // true\n * isUint16Array(new Int16Array(2)) // false\n * ```\n */\nexport function isUint16Array(value: unknown): value is Uint16Array {\n\treturn isInstance(value, Uint16Array)\n}\n\n/** Determine whether a value is an `Int32Array`.\n *\n * @example\n * ```ts\n * isInt32Array(new Int32Array(2)) // true\n * isInt32Array(new Int16Array(2)) // false\n * ```\n */\nexport function isInt32Array(value: unknown): value is Int32Array {\n\treturn isInstance(value, Int32Array)\n}\n\n/** Determine whether a value is a `Uint32Array`.\n *\n * @example\n * ```ts\n * isUint32Array(new Uint32Array(2)) // true\n * isUint32Array(new Int32Array(2)) // false\n * ```\n */\nexport function isUint32Array(value: unknown): value is Uint32Array {\n\treturn isInstance(value, Uint32Array)\n}\n\n/** Determine whether a value is a `Float32Array`.\n *\n * @example\n * ```ts\n * isFloat32Array(new Float32Array(2)) // true\n * isFloat32Array(new Float64Array(2)) // false\n * ```\n */\nexport function isFloat32Array(value: unknown): value is Float32Array {\n\treturn isInstance(value, Float32Array)\n}\n\n/** Determine whether a value is a `Float64Array`.\n *\n * @example\n * ```ts\n * isFloat64Array(new Float64Array(2)) // true\n * isFloat64Array(new Float32Array(2)) // false\n * ```\n */\nexport function isFloat64Array(value: unknown): value is Float64Array {\n\treturn isInstance(value, Float64Array)\n}\n\n/**\n * Determine whether a value is a `BigInt64Array`.\n *\n * @remarks\n * Guards the global existence of `BigInt64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigInt64Array(new BigInt64Array(2)) // true\n * isBigInt64Array(new Float64Array(2)) // false\n * ```\n */\nexport function isBigInt64Array(value: unknown): value is BigInt64Array {\n\treturn typeof BigInt64Array !== 'undefined' && isInstance(value, BigInt64Array)\n}\n\n/**\n * Determine whether a value is a `BigUint64Array`.\n *\n * @remarks\n * Guards the global existence of `BigUint64Array` first — safe in environments\n * that pre-date the BigInt typed-array additions.\n *\n * @example\n * ```ts\n * isBigUint64Array(new BigUint64Array(2)) // true\n * isBigUint64Array(new BigInt64Array(2)) // false\n * ```\n */\nexport function isBigUint64Array(value: unknown): value is BigUint64Array {\n\treturn typeof BigUint64Array !== 'undefined' && isInstance(value, BigUint64Array)\n}\n\n// === Emptiness guards\n\n/** Determine whether a value is the empty string `''`.\n *\n * @example\n * ```ts\n * isEmptyString('') // true\n * isEmptyString('a') // false\n * ```\n */\nexport function isEmptyString(value: unknown): value is '' {\n\treturn isString(value) && value.length === 0\n}\n\n/** Determine whether a value is an empty array.\n *\n * @example\n * ```ts\n * isEmptyArray([]) // true\n * isEmptyArray([1]) // false\n * ```\n */\nexport function isEmptyArray(value: unknown): value is readonly [] {\n\treturn isArray(value) && value.length === 0\n}\n\n/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).\n *\n * @example\n * ```ts\n * isEmptyObject({}) // true\n * isEmptyObject({ a: 1 }) // false\n * ```\n */\nexport function isEmptyObject(value: unknown): value is Record<string | symbol, never> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\t// Object.keys / getOwnPropertySymbols read the object's own-key list, which\n\t// an `ownKeys` Proxy trap can throw from — contained via `attempt` (AGENTS §14).\n\tconst outcome = attempt(\n\t\t() => Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0,\n\t)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is an empty `Map`.\n *\n * @example\n * ```ts\n * isEmptyMap(new Map()) // true\n * isEmptyMap(new Map([['a', 1]])) // false\n * ```\n */\nexport function isEmptyMap(value: unknown): value is ReadonlyMap<never, never> {\n\treturn isMap(value) && value.size === 0\n}\n\n/** Determine whether a value is an empty `Set`.\n *\n * @example\n * ```ts\n * isEmptySet(new Set()) // true\n * isEmptySet(new Set([1])) // false\n * ```\n */\nexport function isEmptySet(value: unknown): value is ReadonlySet<never> {\n\treturn isSet(value) && value.size === 0\n}\n\n/** Determine whether a value is a non-empty string (at least one character).\n *\n * @example\n * ```ts\n * isNonEmptyString('a') // true\n * isNonEmptyString('') // false\n * ```\n */\nexport function isNonEmptyString(value: unknown): value is string {\n\treturn isString(value) && value.length > 0\n}\n\n/** Determine whether a value is a non-empty array (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptyArray([1]) // true\n * isNonEmptyArray([]) // false\n * ```\n */\nexport function isNonEmptyArray<T = unknown>(value: unknown): value is readonly [T, ...T[]] {\n\treturn isArray(value) && value.length > 0\n}\n\n/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).\n *\n * @example\n * ```ts\n * isNonEmptyObject({ a: 1 }) // true\n * isNonEmptyObject({}) // false\n * ```\n */\nexport function isNonEmptyObject(value: unknown): value is Record<string | symbol, unknown> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\t// Same containment as isEmptyObject — an `ownKeys` Proxy trap can throw.\n\tconst outcome = attempt(() => Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0)\n\treturn outcome.success && outcome.value\n}\n\n/** Determine whether a value is a non-empty `Map` (at least one entry).\n *\n * @example\n * ```ts\n * isNonEmptyMap(new Map([['a', 1]])) // true\n * isNonEmptyMap(new Map()) // false\n * ```\n */\nexport function isNonEmptyMap<K = unknown, V = unknown>(\n\tvalue: unknown,\n): value is ReadonlyMap<K, V> {\n\treturn isMap(value) && value.size > 0\n}\n\n/** Determine whether a value is a non-empty `Set` (at least one element).\n *\n * @example\n * ```ts\n * isNonEmptySet(new Set([1])) // true\n * isNonEmptySet(new Set()) // false\n * ```\n */\nexport function isNonEmptySet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn isSet(value) && value.size > 0\n}\n\n// === Function guards\n\n/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).\n *\n * @example\n * ```ts\n * isZeroArg(() => {}) // true\n * isZeroArg((a) => a) // false\n * ```\n */\nexport function isZeroArg(value: unknown): value is ZeroArgFunction {\n\treturn isFunction(value) && value.length === 0\n}\n\n/**\n * Determine whether a value is a native `async function`.\n *\n * @remarks\n * Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is\n * unreliable across realms. The `?.` keeps the guard total (§14): a function\n * whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.\n *\n * @example\n * ```ts\n * isAsyncFunction(async () => {}) // true\n * isAsyncFunction(() => {}) // false\n * ```\n */\nexport function isAsyncFunction(value: unknown): value is AnyAsyncFunction {\n\treturn isFunction(value) && value.constructor?.name === 'AsyncFunction'\n}\n\n/** Determine whether a value is a generator function (`function*`).\n *\n * @example\n * ```ts\n * isGeneratorFunction(function* () {}) // true\n * isGeneratorFunction(() => {}) // false\n * ```\n */\nexport function isGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => Generator<unknown, unknown, unknown> {\n\treturn isFunction(value) && value.constructor?.name === 'GeneratorFunction'\n}\n\n/** Determine whether a value is an async generator function (`async function*`).\n *\n * @example\n * ```ts\n * isAsyncGeneratorFunction(async function* () {}) // true\n * isAsyncGeneratorFunction(function* () {}) // false\n * ```\n */\nexport function isAsyncGeneratorFunction(\n\tvalue: unknown,\n): value is (...args: unknown[]) => AsyncGenerator<unknown, unknown, unknown> {\n\treturn isFunction(value) && value.constructor?.name === 'AsyncGeneratorFunction'\n}\n\n/** Determine whether a value is a zero-argument async function.\n *\n * @example\n * ```ts\n * isZeroArgAsync(async () => {}) // true\n * isZeroArgAsync(async (a) => a) // false\n * ```\n */\nexport function isZeroArgAsync(value: unknown): value is ZeroArgAsyncFunction {\n\treturn isZeroArg(value) && isAsyncFunction(value)\n}\n\n/** Determine whether a value is a zero-argument generator function.\n *\n * @example\n * ```ts\n * isZeroArgGenerator(function* () {}) // true\n * isZeroArgGenerator(function* (a) {}) // false\n * ```\n */\nexport function isZeroArgGenerator(\n\tvalue: unknown,\n): value is () => Generator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isGeneratorFunction(value)\n}\n\n/** Determine whether a value is a zero-argument async generator function.\n *\n * @example\n * ```ts\n * isZeroArgAsyncGenerator(async function* () {}) // true\n * isZeroArgAsyncGenerator(async function* (a) {}) // false\n * ```\n */\nexport function isZeroArgAsyncGenerator(\n\tvalue: unknown,\n): value is () => AsyncGenerator<unknown, unknown, unknown> {\n\treturn isZeroArg(value) && isAsyncGeneratorFunction(value)\n}\n\n/**\n * Determine whether a value can be used as a `new`-target constructor.\n *\n * @remarks\n * Probes with `Reflect.construct(String, [], value)`: a real constructor\n * succeeds, while arrow functions, plain functions, and non-functions throw\n * and yield `false`. Never throws. Backs the `instanceOf` combinator.\n *\n * @example\n * ```ts\n * isConstructor(class X {}) // true\n * isConstructor(() => {}) // false\n * ```\n */\nexport function isConstructor(value: unknown): value is AnyConstructor<object> {\n\tif (!isFunction(value)) {\n\t\treturn false\n\t}\n\ttry {\n\t\tReflect.construct(String, [], value)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n// === JSON\n\n/**\n * Determine whether a value is a cycle-safe JSON value.\n *\n * @remarks\n * Total guard: never throws, returns `false` for cycles, functions, `Date`\n * instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records\n * are walked with an ancestor set so recursive input fails instead of hanging.\n * The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a\n * record property, or a revoked `Proxy` anywhere in the structure, is caught\n * and yields `false` instead of escaping as a thrown error.\n *\n * @param value - The value to test\n * @returns `true` when the value has a JSON representation\n *\n * @example\n * ```ts\n * isJSONValue({ nested: [1, 'x', null] }) // true\n * isJSONValue(Number.NaN) // false\n * ```\n */\nexport function isJSONValue(value: unknown): value is JSONValue {\n\tconst ancestors = new WeakSet<object>()\n\tconst check = (entry: unknown): entry is JSONValue => {\n\t\tif (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true\n\t\tif (Array.isArray(entry)) {\n\t\t\tif (ancestors.has(entry)) return false\n\t\t\tancestors.add(entry)\n\t\t\tconst valid = entry.every(check)\n\t\t\tancestors.delete(entry)\n\t\t\treturn valid\n\t\t}\n\t\tif (!isRecord(entry)) return false\n\t\tif (ancestors.has(entry)) return false\n\t\tancestors.add(entry)\n\t\tconst valid = Object.values(entry).every(check)\n\t\tancestors.delete(entry)\n\t\treturn valid\n\t}\n\tconst outcome = attempt(() => check(value))\n\treturn outcome.success && outcome.value\n}\n\n/**\n * Determine whether a value is a primitive JSON value.\n *\n * @remarks\n * The flat leaf of any JSON document: `null`, a string, a **finite** number, or\n * a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON\n * carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.\n *\n * The recursive {@link isJSONValue} guard is shipped and stays total with\n * cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and\n * the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with\n * the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.\n *\n * @param value - The value to test\n * @returns `true` when `value` is `null`, a string, a finite number, or a boolean\n *\n * @example\n * ```ts\n * isJSONPrimitive(null) // true\n * isJSONPrimitive('hi') // true\n * isJSONPrimitive(42) // true\n * isJSONPrimitive(Number.NaN) // false — not representable in JSON\n * isJSONPrimitive({}) // false\n * ```\n */\nexport function isJSONPrimitive(value: unknown): value is JSONPrimitive {\n\treturn isNull(value) || isString(value) || isFiniteNumber(value) || isBoolean(value)\n}\n","import type {\n\tContractShape,\n\tFaultKind,\n\tFieldPath,\n\tJSONSchema,\n\tRandomFunction,\n\tResult,\n} from './types.js'\nimport { PREVIEW_LIMIT } from './constants.js'\nimport {\n\tisBigInt,\n\tisBoolean,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisString,\n\tisSymbol,\n} from './validators.js'\n\n// === Result helpers\n\n/**\n * Invoke a callback and capture its outcome as a {@link Result}, never letting\n * a throw escape.\n *\n * @remarks\n * The single sanctioned never-throw boundary for the guards (AGENTS §14). The\n * `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied\n * callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a\n * `boolean`. This converts a throwing callback into a `Failure` so the\n * surrounding guard can treat it as a non-match instead of propagating the\n * exception, written once and shared rather than copy-pasted as ad-hoc\n * `try`/`catch`.\n *\n * @param callback - The callback to invoke with no arguments\n * @returns A `Success` carrying the return value, or a `Failure` carrying the\n * thrown reason normalised to an `Error`\n *\n * @example\n * ```ts\n * const outcome = attempt(() => predicate(value))\n * return outcome.success && outcome.value\n * ```\n */\nexport function attempt<T>(callback: () => T): Result<T> {\n\ttry {\n\t\treturn { success: true, value: callback() }\n\t} catch (reason) {\n\t\tif (reason instanceof Error) {\n\t\t\treturn { success: false, error: reason }\n\t\t}\n\t\t// A thrown non-Error value's own `toString` may itself throw (a hostile\n\t\t// object) — contain that conversion too so normalization never escapes.\n\t\tlet message = 'Unknown thrown value'\n\t\ttry {\n\t\t\tmessage = String(reason)\n\t\t} catch {\n\t\t\t// keep the fallback message\n\t\t}\n\t\treturn { success: false, error: new Error(message) }\n\t}\n}\n\n// === Record-field access\n\n/**\n * Resolve a (possibly nested) field value from a record by a key or key path.\n *\n * @remarks\n * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a\n * string array descends left-to-right through nested objects. Intermediates may\n * be any object — records, class instances, or arrays indexed by string. Returns\n * `undefined` the moment a segment is missing or lands on a non-object, so the\n * lookup is total — even against a hostile getter or Proxy trap that throws on\n * read, contained via {@link attempt} so the throw never escapes.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The resolved value, or `undefined`\n *\n * @example\n * ```ts\n * resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'\n * resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)\n * resolveField({ a: 1 }, ['a', 'b']) // undefined\n * ```\n */\nexport function resolveField(record: Readonly<Record<string, unknown>>, path: FieldPath): unknown {\n\tconst keys = isString(path) ? [path] : path\n\tlet current: unknown = record\n\tfor (const key of keys) {\n\t\tif (!isObject(current)) return undefined\n\t\tconst container = current\n\t\tconst outcome = attempt(() => Reflect.get(container, key))\n\t\tif (!outcome.success) return undefined\n\t\tcurrent = outcome.value\n\t}\n\treturn current\n}\n\n// === Random\n\n/**\n * Build a deterministic pseudo-random source seeded from a single number.\n *\n * @remarks\n * A mulberry32 generator — the same seed always yields the same sequence, so\n * generated seed data is reproducible across runs. Used as the default random\n * source for {@link compileGenerator}, seeded from the wall clock so casual\n * callers still get varied output without passing a source themselves.\n *\n * @param seed - The seed for the sequence\n * @returns A {@link RandomFunction} returning values in `[0, 1)`\n *\n * @example\n * ```ts\n * const random = seededRandom(42)\n * random() // always the same first value for seed 42\n * ```\n */\nexport function seededRandom(seed: number): RandomFunction {\n\tlet state = seed >>> 0\n\treturn () => {\n\t\tstate = (state + 0x6d2b79f5) >>> 0\n\t\tlet t = state\n\t\tt = Math.imul(t ^ (t >>> 15), t | 1)\n\t\tt ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n\t\treturn ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296\n\t}\n}\n\n/**\n * Count the enumerable own-symbol keys on a value.\n *\n * @remarks\n * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose\n * descriptor is `enumerable` are counted. Backs the object-emptiness guards\n * (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an\n * enumerable symbol is not mistaken for empty.\n *\n * @param value - The object to inspect\n * @returns The number of enumerable own-symbol keys\n *\n * @example\n * ```ts\n * const flag = Symbol('flag')\n * enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1\n * enumerableSymbolCount({}) // 0\n * ```\n */\nexport function enumerableSymbolCount(value: object): number {\n\tlet count = 0\n\tfor (const symbol of Object.getOwnPropertySymbols(value)) {\n\t\tif (Object.getOwnPropertyDescriptor(value, symbol)?.enumerable) {\n\t\t\tcount += 1\n\t\t}\n\t}\n\treturn count\n}\n\n/**\n * Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape\n * tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never\n * an assertion (AGENTS §14).\n *\n * @remarks\n * A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a\n * tool advertises its `parameters` as an open record. The two are structurally compatible but not\n * assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema\n * is always a record, so the guard passes; the `undefined` fallback only satisfies the type's\n * optionality. This is the single sanctioned narrowing from a compiled contract schema to the open\n * tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.\n *\n * @param schema - The compiled JSON Schema (a contract's `schema`)\n * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record\n *\n * @example\n * ```ts\n * import { createContract, schemaToParameters } from '@src/core'\n *\n * const contract = createContract(shape)\n * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises\n * ```\n */\nexport function schemaToParameters(\n\tschema: JSONSchema,\n): Readonly<Record<string, unknown>> | undefined {\n\treturn isRecord(schema) ? schema : undefined\n}\n\n/**\n * Wrap a non-object `JSONSchema` root in a single-property object schema, so\n * an inferred primitive/array/union schema can flow into {@link schemaToParameters}\n * as an MCP-compatible `inputSchema`.\n *\n * @remarks\n * Total and deterministic. `schema.type === 'object'` passes through\n * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only\n * schema with no `type`, or the empty `{}`) is wrapped as a single required\n * `value` property: `{ type: 'object', properties: { value: schema },\n * required: ['value'], additionalProperties: false }`. Composition:\n * `schemaToParameters(schemaToObject(valueToSchema(payload)))`.\n *\n * @param schema - The schema to wrap\n * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema\n *\n * @example\n * ```ts\n * schemaToObject({ type: 'string' })\n * // { type: 'object', properties: { value: { type: 'string' } },\n * // required: ['value'], additionalProperties: false }\n * schemaToObject({ type: 'object', properties: {} }) // unchanged\n * ```\n */\nexport function schemaToObject(schema: JSONSchema): JSONSchema {\n\tif (schema.type === 'object') return schema\n\treturn {\n\t\ttype: 'object',\n\t\tproperties: { value: schema },\n\t\trequired: ['value'],\n\t\tadditionalProperties: false,\n\t}\n}\n\n// === Inference option sanitization\n\n/**\n * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to\n * a finite non-negative integer, falling back to a default for anything else.\n *\n * @remarks\n * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or\n * malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard\n * (`NaN <= 0` is `false`, so recursion never halts), and a negative\n * `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key\n * instead of capping the list (a fractional value has a similarly undefined\n * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`\n * is `false` — since an unbounded budget is exactly the adversarial case the\n * caps exist to prevent. A valid finite non-negative integer passes through\n * unchanged.\n *\n * @param value - The candidate budget value\n * @param fallback - The default to use when `value` is not a finite\n * non-negative integer\n * @returns A finite non-negative integer budget\n *\n * @example\n * ```ts\n * sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT\n * sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT\n * sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4\n * ```\n */\nexport function sanitizeBudget(value: number | undefined, fallback: number): number {\n\treturn typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : fallback\n}\n\n// === Reporting\n\n/**\n * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s\n * `received` field.\n *\n * @remarks\n * A primitive renders as its literal: a string is `JSON.stringify`-escaped and\n * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when\n * clipped); a number / boolean / bigint / symbol renders via `String`; `null`\n * and `undefined` render as their own name. Everything else — a plain object,\n * an array, a function, a class instance, a `Map` — is NEVER traversed or\n * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),\n * so a hostile or enormous structure can never blow up the preview.\n *\n * @param value - The value to preview\n * @returns A short descriptive string, always safe to embed in a diagnostic\n *\n * @example\n * ```ts\n * preview('hi') // '\"hi\"'\n * preview(42) // '42'\n * preview(null) // 'null'\n * preview({ a: 1 }) // 'object'\n * preview([1, 2, 3]) // 'object'\n * ```\n */\nexport function preview(value: unknown): string {\n\tif (value === null) return 'null'\n\tif (value === undefined) return 'undefined'\n\tif (isString(value)) {\n\t\tconst text = JSON.stringify(value)\n\t\treturn text.length > PREVIEW_LIMIT ? `${text.slice(0, PREVIEW_LIMIT)}…` : text\n\t}\n\tif (isNumber(value) || isBoolean(value)) return String(value)\n\tif (isBigInt(value)) return `${value}n`\n\tif (isSymbol(value)) return value.toString()\n\treturn typeof value\n}\n\n/**\n * Project a {@link ContractShape} to the {@link FaultKind} it describes.\n *\n * @remarks\n * A structural mapping used by {@link compileReporter} to fill a `Fault`'s\n * `expected` field: most shapes map to their own `type` (`numberShape` maps to\n * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /\n * `nullableShape` project through to their inner shape's kind, and `rawShape`\n * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.\n *\n * @param shape - The shape to project\n * @returns The shape's {@link FaultKind}\n *\n * @example\n * ```ts\n * shapeToKind(stringShape()) // 'string'\n * shapeToKind(integerShape()) // 'integer'\n * shapeToKind(optionalShape(nullShape())) // 'null'\n * ```\n */\nexport function shapeToKind(shape: ContractShape): FaultKind {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\t\treturn shape.integer === true ? 'integer' : 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tcase 'null':\n\t\t\treturn 'null'\n\t\tcase 'literal':\n\t\t\treturn 'literal'\n\t\tcase 'array':\n\t\t\treturn 'array'\n\t\tcase 'object':\n\t\t\treturn 'object'\n\t\tcase 'union':\n\t\t\treturn 'union'\n\t\tcase 'json':\n\t\t\treturn 'json'\n\t\tcase 'optional':\n\t\t\treturn shapeToKind(shape.inner)\n\t\tcase 'nullable':\n\t\t\treturn shapeToKind(shape.inner)\n\t\tcase 'raw':\n\t\t\treturn 'json'\n\t}\n}\n","import type {\n\tFromGuards,\n\tGuard,\n\tGuardsShape,\n\tGuardType,\n\tIntersectionFromGuards,\n\tOptionalFromGuards,\n\tTupleFromGuards,\n} from './types.js'\nimport {\n\tisArray,\n\tisConstructor,\n\tisFiniteNumber,\n\tisInstance,\n\tisIterable,\n\tisMap,\n\tisNumber,\n\tisObject,\n\tisRecord,\n\tisSet,\n\tisString,\n\tisSymbol,\n} from './validators.js'\nimport { attempt } from './helpers.js'\n\n// Every combinator returns a `Guard<T>` — a total function (AGENTS §14). The\n// three combinators that invoke a caller-supplied callback inside the guard\n// body (`whereOf`, `lazyOf`, `transformOf`) contain any throw via `attempt`, so\n// the produced guard reports a non-match instead of propagating. The container\n// combinators (`arrayOf`, `tupleOf`, `setOf`, `mapOf`, `iterableOf`, `recordOf`)\n// likewise wrap their element/entry/key-read walk in `attempt` after the cheap\n// structural check — a hostile Proxy trap, a throwing getter, a throwing\n// iterator, or a throwing caller-supplied predicate yields a non-match, never a\n// propagated throw.\n\n/**\n * Build a guard that accepts arrays whose every element satisfies `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringArray = arrayOf(isString)\n * isStringArray(['a', 'b']) // true\n * isStringArray(['a', 1]) // false\n * ```\n */\nexport function arrayOf<T>(elementGuard: Guard<T>): Guard<readonly T[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]>\nexport function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] => {\n\t\tif (!isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => value.every(elementGuard))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts fixed-arity tuples, testing each index with the\n * corresponding guard.\n *\n * @example\n * ```ts\n * const isPair = tupleOf(isString, isNumber)\n * isPair(['hello', 42]) // true\n * isPair(['hello']) // false — wrong arity\n * ```\n */\nexport function tupleOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<TupleFromGuards<Gs>>\nexport function tupleOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]>\nexport function tupleOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<readonly unknown[]> {\n\treturn (value: unknown): value is readonly unknown[] => {\n\t\tif (!isArray(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// Arity comparison reads `.length`, which — like the element reads below —\n\t\t// can hit a hostile Proxy trap, so it stays inside the contained region too.\n\t\tconst outcome = attempt(() => {\n\t\t\tif (value.length !== guards.length) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let index = 0; index < guards.length; index += 1) {\n\t\t\t\tconst guard = guards[index]\n\t\t\t\tif (!guard?.(value[index])) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts values identical (via `Object.is`) to one of the\n * provided literal primitives.\n *\n * @example\n * ```ts\n * const isRole = literalOf('admin', 'member', 'guest')\n * isRole('admin') // true\n * isRole('owner') // false\n * ```\n */\nexport function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(\n\t...literals: Literals\n): Guard<Literals[number]> {\n\treturn (value: unknown): value is Literals[number] =>\n\t\tliterals.some((literal) => Object.is(literal, value))\n}\n\n/**\n * Build a guard that accepts instances of the provided constructor.\n *\n * @remarks\n * Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,\n * so passing an arrow function does not silently produce a broken guard.\n *\n * @example\n * ```ts\n * const isDateValue = instanceOf(Date)\n * isDateValue(new Date()) // true\n * isDateValue({}) // false\n * ```\n */\nexport function instanceOf<C extends abstract new (...args: never) => object>(\n\tctor: C,\n): Guard<InstanceType<C>> {\n\treturn (value: unknown): value is InstanceType<C> =>\n\t\tisConstructor(ctor) && isObject(value) && isInstance(value, ctor)\n}\n\n/**\n * Build a guard from a native `enum` or any object whose values are strings or\n * numbers.\n *\n * @example\n * ```ts\n * enum Direction { Up = 'up', Down = 'down' }\n * const isDirection = enumOf(Direction)\n * isDirection('up') // true\n * isDirection('left') // false\n * ```\n */\nexport function enumOf<const E extends Record<string, string | number>>(\n\tenumeration: E,\n): Guard<E[keyof E]> {\n\tconst values = new Set(Object.values(enumeration))\n\treturn (value: unknown): value is E[keyof E] =>\n\t\t(isString(value) || isNumber(value)) && values.has(value)\n}\n\n/**\n * Build a guard that accepts `Set` instances whose every element satisfies\n * `elementGuard`.\n *\n * @example\n * ```ts\n * const isStringSet = setOf(isString)\n * isStringSet(new Set(['a', 'b'])) // true\n * isStringSet(new Set(['a', 1])) // false\n * ```\n */\nexport function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>\nexport function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>> {\n\treturn (value: unknown): value is ReadonlySet<unknown> => {\n\t\tif (!isSet(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (!elementGuard(entry)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts `Map` instances where every key satisfies\n * `keyGuard` and every value satisfies `valueGuard`.\n *\n * @example\n * ```ts\n * const isStringNumberMap = mapOf(isString, isNumber)\n * isStringNumberMap(new Map([['a', 1]])) // true\n * isStringNumberMap(new Map([[1, 'a']])) // false\n * ```\n */\nexport function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): Guard<ReadonlyMap<K, V>>\nexport function mapOf(\n\tkeyPredicate: (value: unknown) => boolean,\n\tvaluePredicate: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>>\nexport function mapOf(\n\tkeyGuard: (value: unknown) => boolean,\n\tvalueGuard: (value: unknown) => boolean,\n): Guard<ReadonlyMap<unknown, unknown>> {\n\treturn (value: unknown): value is ReadonlyMap<unknown, unknown> => {\n\t\tif (!isMap(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const [key, entryValue] of value) {\n\t\t\t\tif (!keyGuard(key) || !valueGuard(entryValue)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\nexport function recordOf<S extends GuardsShape>(shape: S): Guard<FromGuards<S>>\nexport function recordOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\toptional: K,\n): Guard<OptionalFromGuards<S, K>>\nexport function recordOf<S extends GuardsShape>(\n\tshape: S,\n\toptional: true,\n): Guard<Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>>\n\n/**\n * Build a guard that accepts plain records matching a guard shape.\n *\n * @remarks\n * Three calling modes depending on the `optional` argument:\n * - **No `optional`** — all shape keys required; extra keys rejected.\n * - **`optional: K[]`** — the listed keys are optional; all others required.\n * - **`optional: true`** — every shape key is optional.\n *\n * Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by\n * an inherited prototype member (`toString`, `constructor`, …) counts as absent.\n * A non-object / `null` / array input returns `false` rather than throwing. The\n * extra-key check only inspects `Object.keys` (string keys), so an extra\n * enumerable SYMBOL key is never rejected — intentional, for JSON fidelity, and\n * matches the compiled guard.\n *\n * @example\n * ```ts\n * const isUser = recordOf({ name: isString, age: isNumber })\n * isUser({ name: 'Ada', age: 36 }) // true\n * isUser({ name: 'Ada' }) // false — age missing\n *\n * const isPartial = recordOf({ name: isString, age: isNumber }, ['age'])\n * isPartial({ name: 'Ada' }) // true\n * ```\n */\nexport function recordOf<\n\tS extends GuardsShape,\n\tK extends ReadonlyArray<keyof S & string> | true | undefined,\n>(\n\tshape: S,\n\toptional?: K,\n): Guard<\n\tK extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S>\n> {\n\tconst allowed = new Set<string>()\n\tfor (const key in shape) {\n\t\tif (Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tallowed.add(key)\n\t\t}\n\t}\n\tconst optionalSet = new Set<string>(\n\t\toptional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : [],\n\t)\n\n\treturn (\n\t\tvalue: unknown,\n\t): value is K extends true\n\t\t? Readonly<{ [P in keyof S]?: FromGuards<S>[P] }>\n\t\t: K extends ReadonlyArray<keyof S & string>\n\t\t\t? OptionalFromGuards<S, K>\n\t\t\t: FromGuards<S> => {\n\t\tif (!isRecord(value)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\tif (!allowed.has(key)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const key in shape) {\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst present = Object.hasOwn(value, key)\n\t\t\t\tif (!optionalSet.has(key) && !present) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif (present) {\n\t\t\t\t\tconst guard = shape[key]\n\t\t\t\t\tif (!guard(value[key])) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts any iterable whose every element satisfies\n * `elementGuard`.\n *\n * @example\n * ```ts\n * const isNumberIterable = iterableOf(isNumber)\n * isNumberIterable([1, 2, 3]) // true\n * isNumberIterable(new Set([1, 2])) // true\n * isNumberIterable([1, 'two']) // false\n * ```\n */\nexport function iterableOf<T>(elementGuard: Guard<T>): Guard<Iterable<T>>\nexport function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>>\nexport function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>> {\n\treturn (value: unknown): value is Iterable<unknown> => {\n\t\tif (!isIterable(value)) {\n\t\t\treturn false\n\t\t}\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (!elementGuard(entry)) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that accepts values that are own keys of the provided object.\n *\n * @remarks\n * Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys\n * (`toString`, `constructor`, …) are rejected. An own property that shadows a\n * prototype name is accepted.\n *\n * @example\n * ```ts\n * const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const\n * const isColorKey = keyOf(COLORS)\n * isColorKey('red') // true\n * isColorKey('purple') // false\n * isColorKey('toString') // false — inherited, not an own key\n * ```\n */\nexport function keyOf<const O extends Readonly<Record<PropertyKey, unknown>>>(\n\tvalue: O,\n): Guard<keyof O> {\n\treturn (entry: unknown): entry is keyof O =>\n\t\t(isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry)\n}\n\n/**\n * Build a new guard shape by keeping only the listed keys — the structural\n * equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isName = recordOf(pickOf(full, ['name']))\n * isName({ name: 'Ada' }) // true\n * ```\n */\nexport function pickOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Pick<S, K[number]> {\n\t// Honest typing: the accumulator IS the picked-shape type, so every write is\n\t// checked against `S[P]` — no `as` / `!` / `asserts`. The seed is a genuine\n\t// null-prototype empty object, filled before any read.\n\tconst result: { [P in K[number]]: S[P] } = Object.create(null)\n\tfor (const key of keys) {\n\t\tif (Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Build a new guard shape by removing the listed keys — the structural\n * equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n *\n * @example\n * ```ts\n * const full = { name: isString, age: isNumber, role: isString }\n * const isPublic = recordOf(omitOf(full, ['role']))\n * isPublic({ name: 'Ada', age: 36 }) // true\n * ```\n */\nexport function omitOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(\n\tshape: S,\n\tkeys: K,\n): Omit<S, K[number]> {\n\tconst skipped = new Set<PropertyKey>()\n\tfor (const key of keys) {\n\t\tskipped.add(key)\n\t}\n\t// Sound over-approximation: only kept keys are written, so the value\n\t// structurally satisfies `Omit<S, K[number]>`. Same honest typing as\n\t// `pickOf` — no `as` / `!` / `asserts`.\n\tconst result: { [P in keyof S]: S[P] } = Object.create(null)\n\tfor (const key in shape) {\n\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!skipped.has(key)) {\n\t\t\tresult[key] = shape[key]\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Combine two guards with logical AND — passes only when both pass.\n *\n * @remarks\n * Use {@link whereOf} when the right side refines an already-narrowed type; use\n * `andOf` to combine two independent guards.\n *\n * @example\n * ```ts\n * const isShortString = andOf(isString, isNonEmptyString)\n * ```\n */\nexport function andOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A & B>\nexport function andOf<T, U extends T>(left: Guard<T>, right: (value: T) => value is U): Guard<U>\nexport function andOf<T>(left: Guard<T>, right: (value: T) => boolean): Guard<T>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function andOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => left(value) && right(value)\n}\n\n/**\n * Combine two guards with logical OR — passes when at least one passes. For more\n * than two variants prefer {@link unionOf}.\n *\n * @example\n * ```ts\n * const isStringOrNumber = orOf(isString, isNumber)\n * ```\n */\nexport function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown>\nexport function orOf(\n\tleft: (value: unknown) => boolean,\n\tright: (value: unknown) => boolean,\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => left(value) || right(value)\n}\n\n/**\n * Negate a guard or predicate — passes when `guard` returns `false`.\n *\n * @remarks\n * Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use\n * {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.\n *\n * @example\n * ```ts\n * const isNotNull = notOf(isNull)\n * ```\n */\nexport function notOf(guard: (value: unknown) => boolean): Guard<unknown> {\n\treturn (value: unknown): value is unknown => !guard(value)\n}\n\n/**\n * Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass\n * `base` but not `excluded`.\n *\n * @example\n * ```ts\n * const isNonEmpty = complementOf(isString, isEmptyString)\n * isNonEmpty('hi') // true\n * isNonEmpty('') // false\n * ```\n */\nexport function complementOf<TBase, TExcluded extends TBase>(\n\tbase: Guard<TBase>,\n\texcluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded),\n): Guard<Exclude<TBase, TExcluded>> {\n\treturn (value: unknown): value is Exclude<TBase, TExcluded> => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\treturn !excluded(value)\n\t}\n}\n\n/**\n * Build a guard that accepts values matching at least one of the provided\n * guards — the variadic form of {@link orOf}.\n *\n * @example\n * ```ts\n * const isStringOrBoolean = unionOf(isString, isBoolean)\n * ```\n */\nexport function unionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<GuardType<Gs[number]>>\nexport function unionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>\nexport function unionOf(...guards: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown> {\n\treturn (value: unknown): value is unknown => guards.some((guard) => guard(value))\n}\n\n/**\n * Build a guard that accepts values matching ALL of the provided guards — the\n * variadic form of {@link andOf}.\n *\n * @example\n * ```ts\n * const isNonEmpty = intersectionOf(isString, isNonEmptyString)\n * ```\n */\nexport function intersectionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(\n\t...guards: Gs\n): Guard<IntersectionFromGuards<Gs>>\nexport function intersectionOf(\n\t...predicates: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown>\nexport function intersectionOf(\n\t...guards: ReadonlyArray<(value: unknown) => boolean>\n): Guard<unknown> {\n\treturn (value: unknown): value is unknown => guards.every((guard) => guard(value))\n}\n\n/**\n * Refine a base guard with an additional predicate that runs only when the base\n * passes.\n *\n * @remarks\n * The predicate receives a value already narrowed to `T`. When the predicate is\n * itself a type guard (`value is U`), the result narrows to `Guard<U>` — it\n * passes only when the value is genuinely a `U`, so the narrowing is sound. Per\n * §14 the returned guard never throws: if `predicate` throws, the throw is\n * contained and the guard reports a non-match.\n *\n * @example\n * ```ts\n * const isPositive = whereOf(isNumber, (n) => n > 0)\n * isPositive(5) // true\n * isPositive(-1) // false\n *\n * // A narrowing predicate refines the result type to Guard<5>\n * const isFive = whereOf(isNumber, (n): n is 5 => n === 5)\n * ```\n */\nexport function whereOf<T, U extends T>(\n\tbase: Guard<T>,\n\tpredicate: (value: T) => value is U,\n): Guard<U>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T>\nexport function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// `predicate` is user-supplied with no never-throw contract; §14 forbids\n\t\t// the guard from propagating its throw.\n\t\tconst outcome = attempt(() => predicate(value))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Defer guard creation until first use by calling `thunk()` on every\n * invocation.\n *\n * @remarks\n * `thunk` is called on every guard call, not cached — this lets it close over a\n * binding assigned *after* `lazyOf` is called, the primary use case for\n * self-referential recursive guards. Per §14 a throw from `thunk` (or the guard\n * it resolves to) is contained and reported as a non-match.\n *\n * A recursive guard built this way has no cycle/depth detection: a cyclic or\n * pathologically deep input is stack-bounded — the overflow is contained and the\n * guard returns `false` rather than throwing, but it is not validated correctly\n * past that bound.\n *\n * @example\n * ```ts\n * type Tree = { value: number; children: Tree[] }\n * let isTree: Guard<Tree>\n * isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })\n * ```\n */\nexport function lazyOf<T>(thunk: () => Guard<T>): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\t// `thunk` and the guard it returns are user-supplied; §14 forbids\n\t\t// propagating either throw.\n\t\tconst outcome = attempt(() => thunk()(value))\n\t\treturn outcome.success && outcome.value\n\t}\n}\n\n/**\n * Build a guard that passes when the base passes AND the projection of the value\n * satisfies the target guard. Still narrows to `T` (the base type) — the target\n * check is a validity constraint on a derived view, not a type transformation.\n *\n * @remarks\n * `project` is a plain `(value: T) => U`. Per §14 the returned guard never\n * throws: a throw from `project` is contained and reported as a non-match.\n * `target` is itself a Guard (already §14-bound), so it stays outside the\n * contained region. (Unlike the reference implementation, there is no\n * \"curried projector\" branch — a projection that legitimately returns a function\n * would be double-invoked under that scheme. Compose explicitly if you need it.)\n *\n * @example\n * ```ts\n * const isBounded = transformOf(\n * isString,\n * (s) => s.trim().length,\n * whereOf(isNumber, (n) => n >= 1 && n <= 50),\n * )\n * isBounded('hello') // true\n * isBounded('') // false\n * ```\n */\nexport function transformOf<T, U>(\n\tbase: Guard<T>,\n\tproject: (value: T) => U,\n\ttarget: Guard<U>,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T>\nexport function transformOf<T>(\n\tbase: Guard<T>,\n\tproject: (value: T) => unknown,\n\ttarget: (value: unknown) => boolean,\n): Guard<T> {\n\treturn (value: unknown): value is T => {\n\t\tif (!base(value)) {\n\t\t\treturn false\n\t\t}\n\t\t// `project` is user-supplied with no never-throw contract; §14 forbids the\n\t\t// guard from propagating its throw.\n\t\tconst outcome = attempt(() => project(value))\n\t\treturn outcome.success && target(outcome.value)\n\t}\n}\n\n/**\n * Build a guard that accepts finite numbers within an inclusive `[min, max]`\n * range.\n *\n * @remarks\n * Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /\n * `±Infinity` are rejected before any comparison runs. An absent bound never\n * constrains that side. Reused for a number's own value AND, applied to a\n * `.length`, for string and array length refinements — the single source of the\n * bound logic shared by the compiled guard and parser (compilers.ts).\n *\n * @example\n * ```ts\n * const inRange = boundsOf(1, 5)\n * inRange(3) // true\n * inRange(0) // false — below min\n * inRange(6) // false — above max\n *\n * const atLeastTwo = boundsOf(2)\n * atLeastTwo(2) // true — unbounded above\n * ```\n */\nexport function boundsOf(min?: number, max?: number): Guard<number> {\n\treturn whereOf(\n\t\tisFiniteNumber,\n\t\t(value) => (min === undefined || value >= min) && (max === undefined || value <= max),\n\t)\n}\n\n/**\n * Build a guard that accepts strings matching a regular expression.\n *\n * @example\n * ```ts\n * const isHex = matchOf(/^[0-9a-f]+$/)\n * isHex('1a2f') // true\n * isHex('xyz') // false\n * ```\n */\nexport function matchOf(pattern: RegExp): Guard<string> {\n\treturn whereOf(isString, (value) => pattern.test(value))\n}\n\n/**\n * Build a guard that accepts strings satisfying optional length and pattern\n * refinements — `min` / `max` length and a `pattern`.\n *\n * @remarks\n * Composes {@link isString} with {@link boundsOf} on the string's `.length` and\n * an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns\n * the bare {@link isString} guard (the unconstrained fast path), so an\n * unrefined string leaf pays no wrapping cost. The single source of the string\n * refinement shared by the compiled guard and parser (compilers.ts).\n *\n * @example\n * ```ts\n * const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })\n * isSlug('hello-world') // true\n * isSlug('') // false — below min\n * isSlug('Hello') // false — pattern miss\n *\n * stringOf() // identical to isString\n * ```\n */\nexport function stringOf(options?: {\n\tmin?: number\n\tmax?: number\n\tpattern?: RegExp\n}): Guard<string> {\n\tconst min = options?.min\n\tconst max = options?.max\n\tconst pattern = options?.pattern\n\tif (min === undefined && max === undefined && pattern === undefined) {\n\t\treturn isString\n\t}\n\tconst withinLength = boundsOf(min, max)\n\treturn whereOf(\n\t\tisString,\n\t\t(value) => withinLength(value.length) && (pattern === undefined || pattern.test(value)),\n\t)\n}\n\n/**\n * Extend a guard to also allow `null`.\n *\n * @example\n * ```ts\n * const isNullableString = nullableOf(isString)\n * isNullableString('hi') // true\n * isNullableString(null) // true\n * isNullableString(42) // false\n * ```\n */\nexport function nullableOf<T>(guard: Guard<T>): Guard<T | null> {\n\treturn (value: unknown): value is T | null => value === null || guard(value)\n}\n\n/**\n * Extend a guard to also allow `undefined` — the optional counterpart of\n * {@link nullableOf}.\n *\n * @example\n * ```ts\n * const isOptionalString = optionalOf(isString)\n * isOptionalString('hi') // true\n * isOptionalString(undefined) // true\n * isOptionalString(null) // false\n * ```\n */\nexport function optionalOf<T>(guard: Guard<T>): Guard<T | undefined> {\n\treturn (value: unknown): value is T | undefined => value === undefined || guard(value)\n}\n","import type { Guard, JSONValue } from './types.js'\nimport type { FieldPath } from './types.js'\nimport { isArray, isFiniteNumber, isJSONValue, isNull, isRecord, isString } from './validators.js'\nimport { resolveField } from './helpers.js'\n\n// AGENTS §14: a parser answers \"give me a `T` or nothing\" — it returns the\n// typed value or `undefined`, and it never throws. Each leaf parser here forms a\n// SOUND pair with the guard for its output TYPE: a guard-valid input is returned\n// UNCHANGED (by identity, never rejected), and every non-`undefined` output\n// satisfies that type guard. The pairings (verified in parsers.test.ts):\n//\n// parseString ↔ isString parseRecord ↔ isRecord\n// parseNumber ↔ isFiniteNumber parseArray ↔ arrayOf(guard) / isArray\n// parseInteger ↔ isInteger parseEnum ↔ literalOf(...allowed)\n// parseBoolean ↔ isBoolean parseNull ↔ isNull\n// parseJSONValue ↔ isJSONValue\n//\n// Coercion of NON-valid inputs (e.g. numeric strings → numbers) is a bonus on\n// top of soundness, not a violation of it — clause A only constrains inputs the\n// guard already accepts.\n//\n// These leaf parsers are deliberately TYPE-only: they know nothing about a\n// shape's `min` / `max` / `pattern` refinements. Those refinements are enforced\n// one layer up, by the compiled parser (compilers.ts `compileParser`), which\n// re-applies the shared refinement combinators (`stringOf` / `boundsOf`,\n// combinators.ts) after coercion — the same source the compiled guard uses. So `createContract(...).parse` IS sound against the FULL\n// guard (refinements included); the split keeps each leaf parser small while the\n// compiler composes the full soundness.\n//\n// Coercion policy — which types cross into which:\n// - number <-> string is BIDIRECTIONAL by design: parseNumber accepts a\n// numeric string ('42' -> 42) and parseString accepts a finite number,\n// stringifying it (42 -> '42'). Use isString / isFiniteNumber directly\n// (never the parser) when you need STRICT type rejection with no coercion.\n// - boolean is a coercion SINK, never a source: parseBoolean accepts\n// 'true'/'false'/'1'/'0' and 1/0 and coerces them TO a boolean, but\n// parseNumber and parseString both reject booleans outright — a boolean\n// never coerces INTO a number or string. This is intentional asymmetry:\n// '1' meaning \"the number one\" and '1' meaning \"true\" are genuinely\n// different domains, so only the boolean parser treats the numeric/string\n// forms as booleans.\n\n// === Primitive parsers\n\n/**\n * Parse an unknown value to a string.\n *\n * @remarks\n * A string is returned unchanged; a finite number is coerced to its decimal\n * string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A string, or `undefined`\n *\n * @example\n * ```ts\n * parseString('hi') // 'hi'\n * parseString(42) // '42'\n * parseString(true) // undefined\n * ```\n */\nexport function parseString(value: unknown): string | undefined {\n\tif (isString(value)) return value\n\tif (isFiniteNumber(value)) return String(value)\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite number.\n *\n * @remarks\n * A finite number is returned unchanged; a non-blank numeric string is parsed\n * via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every\n * other type → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumber(42) // 42\n * parseNumber('42') // 42\n * parseNumber('abc') // undefined\n * ```\n */\nexport function parseNumber(value: unknown): number | undefined {\n\tif (typeof value === 'number') {\n\t\treturn Number.isFinite(value) ? value : undefined\n\t}\n\tif (isString(value)) {\n\t\tif (value.trim() === '') return undefined\n\t\tconst parsed = Number(value)\n\t\treturn Number.isFinite(parsed) ? parsed : undefined\n\t}\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to a finite integer.\n *\n * @remarks\n * Accepts whatever {@link parseNumber} accepts, then requires the result to have\n * no fractional part. `3.14` / `'3.14'` → `undefined`.\n *\n * @param value - The value to parse\n * @returns A finite integer, or `undefined`\n *\n * @example\n * ```ts\n * parseInteger(42) // 42\n * parseInteger(3.14) // undefined\n * ```\n */\nexport function parseInteger(value: unknown): number | undefined {\n\tconst parsed = parseNumber(value)\n\tif (parsed === undefined) return undefined\n\treturn Number.isInteger(parsed) ? parsed : undefined\n}\n\n/**\n * Parse an unknown value to a boolean.\n *\n * @remarks\n * A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /\n * `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything\n * else → `undefined`.\n *\n * @param value - The value to parse\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBoolean(true) // true\n * parseBoolean('1') // true\n * parseBoolean('nope') // undefined\n * ```\n */\nexport function parseBoolean(value: unknown): boolean | undefined {\n\tif (typeof value === 'boolean') return value\n\tif (value === 'true' || value === '1' || value === 1) return true\n\tif (value === 'false' || value === '0' || value === 0) return false\n\treturn undefined\n}\n\n/**\n * Parse an unknown value to `null`.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel every other parser in this file uses. Only `null` passes;\n * every other value (including `undefined`) → `undefined`.\n *\n * @param value - The value to parse\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNull(null) // null\n * parseNull(undefined) // undefined\n * ```\n */\nexport function parseNull(value: unknown): null | undefined {\n\treturn isNull(value) ? value : undefined\n}\n\n// === Structural parsers\n\n/**\n * Parse an unknown value to a plain record — the input reference, never cloned.\n *\n * @param value - The value to parse\n * @returns The record, or `undefined`\n */\nexport function parseRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn isRecord(value) ? value : undefined\n}\n\n/**\n * Parse an unknown value to an array — the input reference, never cloned —\n * optionally guarding every element.\n *\n * @remarks\n * Without a `guard`, element types are NOT verified; let `T` default to\n * `unknown` rather than asserting a specific element type.\n *\n * @param value - The value to parse\n * @param guard - Optional element guard\n * @returns The array, or `undefined`\n *\n * @example\n * ```ts\n * parseArray([1, 2]) // [1, 2]\n * parseArray([1, 'x'], isNumber) // undefined\n * ```\n */\nexport function parseArray<T = unknown>(\n\tvalue: unknown,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\tif (!isArray<T>(value)) return undefined\n\tif (guard !== undefined && !value.every(guard)) return undefined\n\treturn value\n}\n\n/**\n * Parse an unknown value to a cycle-safe JSON value — the input reference,\n * never cloned.\n *\n * @remarks\n * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it\n * walks the entire tree via {@link isJSONValue} rather than checking only the\n * top-level shape. That walk is cycle-safe and total (never throws) because\n * `isJSONValue` runs its own probe inside a guard, so an adversarial\n * structure (a cycle, a hostile getter) yields `undefined` instead of hanging\n * or throwing.\n *\n * @param value - The value to parse\n * @returns The value, or `undefined` when it is not a valid JSON value\n *\n * @example\n * ```ts\n * parseJSONValue({ a: 1 }) // { a: 1 }\n * parseJSONValue(Number.NaN) // undefined\n * ```\n */\nexport function parseJSONValue(value: unknown): JSONValue | undefined {\n\treturn isJSONValue(value) ? value : undefined\n}\n\n// === Enum parser\n\n/**\n * Parse an unknown value as one of the allowed literal primitives.\n *\n * @remarks\n * Pairs with {@link literalOf} — both match by `Object.is`, so the\n * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive\n * (string, number, or boolean), not only strings. Matching is identity, never\n * cross-type coercion: `parseEnum('1', [1])` stays `undefined`.\n *\n * @param value - The value to parse\n * @param allowed - The permitted literal values\n * @returns The matched literal (by identity), or `undefined`\n *\n * @example\n * ```ts\n * parseEnum('b', ['a', 'b', 'c']) // 'b'\n * parseEnum('z', ['a', 'b', 'c']) // undefined\n * ```\n */\nexport function parseEnum<const T extends string | number | boolean>(\n\tvalue: unknown,\n\tallowed: readonly T[],\n): T | undefined {\n\tfor (const option of allowed) {\n\t\tif (Object.is(value, option)) return option\n\t}\n\treturn undefined\n}\n\n// === Record-field parsers\n\n/**\n * Read and parse a string field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A string, or `undefined`\n */\nexport function parseStringField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): string | undefined {\n\treturn parseString(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-number field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite number, or `undefined`\n *\n * @example\n * ```ts\n * parseNumberField({ age: '42' }, 'age') // 42\n * parseNumberField({}, 'age') // undefined\n * ```\n */\nexport function parseNumberField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseNumber(resolveField(record, path))\n}\n\n/**\n * Read and parse a finite-integer field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A finite integer, or `undefined`\n */\nexport function parseIntegerField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): number | undefined {\n\treturn parseInteger(resolveField(record, path))\n}\n\n/**\n * Read and parse a boolean field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A boolean, or `undefined`\n *\n * @example\n * ```ts\n * parseBooleanField({ on: 'true' }, 'on') // true\n * parseBooleanField({}, 'on') // undefined\n * ```\n */\nexport function parseBooleanField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): boolean | undefined {\n\treturn parseBoolean(resolveField(record, path))\n}\n\n/**\n * Read and parse a `null` field from a record by key or nested key path.\n *\n * @remarks\n * A successful parse returns `null` itself — distinct from the `undefined`\n * failure sentinel, which also covers a missing field.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns `null` on a successful parse, or `undefined`\n *\n * @example\n * ```ts\n * parseNullField({ value: null }, 'value') // null\n * parseNullField({}, 'value') // undefined\n * ```\n */\nexport function parseNullField(record: Record<string, unknown>, path: FieldPath): null | undefined {\n\treturn parseNull(resolveField(record, path))\n}\n\n/**\n * Read and parse a nested record field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns A plain record, or `undefined`\n */\nexport function parseRecordField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): Record<string, unknown> | undefined {\n\treturn parseRecord(resolveField(record, path))\n}\n\n/**\n * Read and parse an array field from a record by key or nested key path,\n * optionally guarding elements.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param guard - Optional element guard\n * @returns An array, or `undefined`\n *\n * @example\n * ```ts\n * parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2]\n * parseArrayField({}, 'tags') // undefined\n * ```\n */\nexport function parseArrayField<T = unknown>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tguard?: Guard<T>,\n): readonly T[] | undefined {\n\treturn parseArray(resolveField(record, path), guard)\n}\n\n/**\n * Read and parse an enum field from a record by key or nested key path.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @param allowed - The permitted literal values\n * @returns The matched literal, or `undefined`\n */\nexport function parseEnumField<const T extends string | number | boolean>(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n\tallowed: readonly T[],\n): T | undefined {\n\treturn parseEnum(resolveField(record, path), allowed)\n}\n\n/**\n * Read and parse a JSON-value field from a record by key or nested key path.\n *\n * @remarks\n * Deep-gates the field's whole subtree via {@link parseJSONValue} — see that\n * function's remarks for why this differs from the shallow\n * {@link parseRecordField} / {@link parseArrayField}.\n *\n * @param record - The source record\n * @param path - A property key, or a key path descending into nested objects\n * @returns The value, or `undefined`\n *\n * @example\n * ```ts\n * parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 }\n * parseJSONValueField({}, 'data') // undefined\n * ```\n */\nexport function parseJSONValueField(\n\trecord: Record<string, unknown>,\n\tpath: FieldPath,\n): JSONValue | undefined {\n\treturn parseJSONValue(resolveField(record, path))\n}\n\n// === JSON\n\n/**\n * Parse a JSON string, returning `undefined` instead of throwing.\n *\n * @remarks\n * The safe boundary for untrusted JSON text: a malformed string yields\n * `undefined`, never an exception. Returns `unknown` — a successful parse proves\n * nothing about shape, so narrow the result with a guard (or use\n * {@link parseJSONAs}). A large document is not walked here; parsing is shallow\n * and lazy validation is the caller's to compose.\n *\n * @param value - The JSON string to parse\n * @returns The parsed value, or `undefined` when `value` is not valid JSON\n */\nexport function parseJSON(value: string): unknown {\n\ttry {\n\t\treturn JSON.parse(value)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Parse a JSON string and validate the result against a guard.\n *\n * @remarks\n * The lazy, safe path from an untrusted string to a typed `T`: parse, then check\n * the parsed value with the guard you bring — typically one composed from the\n * combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is\n * validated, so a large document is never walked in full unless the guard does.\n *\n * @param value - The JSON string to parse\n * @param guard - The guard for the expected shape\n * @returns The parsed value when it satisfies `guard`, otherwise `undefined`\n *\n * @example\n * ```ts\n * const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })\n * parseJSONAs('{\"host\":\"localhost\",\"tags\":[\"a\"]}', isConfig) // { host: 'localhost', tags: ['a'] }\n * parseJSONAs('{\"host\":\"localhost\"}', isConfig) // undefined — guard fails\n * parseJSONAs('not json', isConfig) // undefined — never throws\n * ```\n */\nexport function parseJSONAs<T>(value: string, guard: Guard<T>): T | undefined {\n\tconst parsed = parseJSON(value)\n\tif (parsed === undefined) return undefined\n\treturn guard(parsed) ? parsed : undefined\n}\n","import type {\n\tContractInterface,\n\tContractShape,\n\tFault,\n\tFaultKind,\n\tGuard,\n\tInfer,\n\tJSONSchema,\n\tParser,\n\tRandomFunction,\n} from './types.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisInteger,\n\tisJSONValue,\n\tisNull,\n\tisRecord,\n\tisString,\n\tisUndefined,\n} from './validators.js'\nimport { attempt, preview, seededRandom, shapeToKind } from './helpers.js'\nimport { FAULT_LIMIT } from './constants.js'\nimport {\n\tarrayOf,\n\tboundsOf,\n\tintersectionOf,\n\tliteralOf,\n\tnullableOf,\n\torOf,\n\trecordOf,\n\tstringOf,\n\tunionOf,\n\twhereOf,\n} from './combinators.js'\nimport { parseBoolean, parseInteger, parseNumber, parseRecord, parseString } from './parsers.js'\n\n// The compilers walk a finite, developer-authored shape tree (never cyclic) and\n// recurse on themselves — branches are kept inline and public per AGENTS §5,\n// never hidden behind private helpers. `compileGuard` / `compileParser` reuse the\n// existing combinators and parsers rather than re-implementing them.\n\n// === Validation\n\n/**\n * Validate that a {@link ContractShape} tree is well-formed — a pure recursive\n * prepass run before compilation.\n *\n * @remarks\n * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this\n * throws a plain `Error` immediately rather than surfacing as a silently-wrong\n * guard, parser, schema, or generator later. Checks, recursively:\n *\n * - An {@link OptionalShape} is only legal as a direct object-property value —\n * `optionalShape` wrapping an array item, a union variant, another\n * optional/nullable's inner shape, `additionalProperties`, or the top-level\n * shape all throw. An object property IS the one legal placement: its value\n * is unwrapped to `.inner` before recursing, so `.inner` itself is validated\n * as a normal (non-optional-wrapping) shape.\n * - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}\n * needs at least one value and rejects non-finite (`NaN` / `Infinity` /\n * `-Infinity`) number values.\n * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}\n * needs `min <= max` when both are set.\n * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer\n * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.\n * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion\n * continues into array items, object properties (and `additionalProperties`\n * when it is a shape), union variants, and optional/nullable inner shapes.\n *\n * @param shape - The shape to validate\n * @throws {Error} When the shape is malformed\n *\n * @example\n * ```ts\n * validateShape(stringShape({ min: 1, max: 10 })) // does not throw\n * validateShape(stringShape({ min: 10, max: 1 })) // throws\n * ```\n */\nexport function validateShape(shape: ContractShape): void {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: a string shape has min greater than max')\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase 'number': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: a number shape has min greater than max')\n\t\t\t}\n\t\t\tif (shape.integer === true) {\n\t\t\t\tconst lo = Math.ceil(shape.min ?? Number.NEGATIVE_INFINITY)\n\t\t\t\tconst hi = Math.floor(shape.max ?? Number.POSITIVE_INFINITY)\n\t\t\t\tif (lo > hi) {\n\t\t\t\t\tthrow new Error('validateShape: an integer number shape has an empty integer range')\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcase 'boolean':\n\t\tcase 'null':\n\t\tcase 'json':\n\t\tcase 'raw':\n\t\t\treturn\n\t\tcase 'literal':\n\t\t\tif (shape.values.length === 0) {\n\t\t\t\tthrow new Error('validateShape: a literal shape needs at least one value')\n\t\t\t}\n\t\t\tfor (const value of shape.values) {\n\t\t\t\tif (typeof value === 'number' && !Number.isFinite(value)) {\n\t\t\t\t\tthrow new Error('validateShape: a literal shape may not contain non-finite number values')\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\tcase 'array': {\n\t\t\tif (shape.min !== undefined && shape.max !== undefined && shape.min > shape.max) {\n\t\t\t\tthrow new Error('validateShape: an array shape has min greater than max')\n\t\t\t}\n\t\t\tvalidateShape(shape.items)\n\t\t\treturn\n\t\t}\n\t\tcase 'object': {\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tvalidateShape(child.type === 'optional' ? child.inner : child)\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tif (extra !== undefined && extra !== true && extra !== false) validateShape(extra)\n\t\t\treturn\n\t\t}\n\t\tcase 'union':\n\t\t\tif (shape.variants.length === 0) {\n\t\t\t\tthrow new Error('validateShape: a union shape needs at least one variant')\n\t\t\t}\n\t\t\tfor (const variant of shape.variants) validateShape(variant)\n\t\t\treturn\n\t\tcase 'optional':\n\t\t\tthrow new Error(\n\t\t\t\t'validateShape: an optional shape may only appear as a direct object-property value',\n\t\t\t)\n\t\tcase 'nullable':\n\t\t\tvalidateShape(shape.inner)\n\t\t\treturn\n\t}\n}\n\n// === Schema\n\n/**\n * Compile a {@link ContractShape} into a JSON Schema document.\n *\n * @remarks\n * Object shapes emit `additionalProperties: false` (unless opened) and list only\n * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:\n * 'null' }`. Emission only — it never inspects a runtime value.\n *\n * @param shape - The shape to compile\n * @returns The emitted JSON Schema\n *\n * @example\n * ```ts\n * compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 }\n * ```\n */\nexport function compileSchema(shape: ContractShape): JSONSchema {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\treturn {\n\t\t\t\ttype: 'string',\n\t\t\t\t...(shape.min !== undefined ? { minLength: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maxLength: shape.max } : {}),\n\t\t\t\t...(shape.pattern !== undefined ? { pattern: shape.pattern.source } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'number':\n\t\t\treturn {\n\t\t\t\ttype: shape.integer === true ? 'integer' : 'number',\n\t\t\t\t...(shape.min !== undefined ? { minimum: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maximum: shape.max } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'boolean':\n\t\t\treturn {\n\t\t\t\ttype: 'boolean',\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'null':\n\t\t\treturn {\n\t\t\t\ttype: 'null',\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'json':\n\t\t\treturn {\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'literal':\n\t\t\treturn {\n\t\t\t\tenum: [...shape.values],\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'array':\n\t\t\treturn {\n\t\t\t\ttype: 'array',\n\t\t\t\titems: compileSchema(shape.items),\n\t\t\t\t...(shape.min !== undefined ? { minItems: shape.min } : {}),\n\t\t\t\t...(shape.max !== undefined ? { maxItems: shape.max } : {}),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'object': {\n\t\t\tconst properties: Record<string, JSONSchema> = {}\n\t\t\tconst required: string[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tproperties[key] = compileSchema(child)\n\t\t\t\tif (child.type !== 'optional') required.push(key)\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tconst additionalProperties: boolean | JSONSchema =\n\t\t\t\textra === true\n\t\t\t\t\t? true\n\t\t\t\t\t: extra !== undefined && extra !== false\n\t\t\t\t\t\t? compileSchema(extra)\n\t\t\t\t\t\t: false\n\t\t\treturn {\n\t\t\t\ttype: 'object',\n\t\t\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t\t\t...(required.length > 0 ? { required } : {}),\n\t\t\t\tadditionalProperties,\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\t}\n\t\tcase 'union':\n\t\t\treturn {\n\t\t\t\t...(shape.mode === 'oneOf'\n\t\t\t\t\t? { oneOf: shape.variants.map((variant) => compileSchema(variant)) }\n\t\t\t\t\t: { anyOf: shape.variants.map((variant) => compileSchema(variant)) }),\n\t\t\t\t...(shape.description !== undefined ? { description: shape.description } : {}),\n\t\t\t}\n\t\tcase 'optional':\n\t\t\treturn compileSchema(shape.inner)\n\t\tcase 'nullable':\n\t\t\treturn { anyOf: [compileSchema(shape.inner), { type: 'null' }] }\n\t\tcase 'raw':\n\t\t\treturn shape.schema\n\t}\n}\n\n// === Guard\n\n/**\n * Compile a {@link ContractShape} into a runtime type guard.\n *\n * @remarks\n * Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,\n * `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,\n * and `whereOf` for constraint refinement. Like every guard it is total — it\n * never throws (AGENTS §14).\n *\n * @param shape - The shape to compile\n * @returns A guard narrowing to the shape's inferred type\n *\n * @example\n * ```ts\n * const isUser = compileGuard(objectShape({ name: stringShape() }))\n * isUser({ name: 'Ada' }) // true\n * ```\n */\nexport function compileGuard<S extends ContractShape>(shape: S): Guard<Infer<S>>\nexport function compileGuard(shape: ContractShape): Guard<unknown>\nexport function compileGuard(shape: ContractShape): Guard<unknown> {\n\tswitch (shape.type) {\n\t\tcase 'string':\n\t\t\t// `stringOf` returns bare `isString` when unrefined, else composes the\n\t\t\t// length-bounds + pattern refinement — the same guard the parser re-applies.\n\t\t\treturn stringOf({ min: shape.min, max: shape.max, pattern: shape.pattern })\n\t\tcase 'number': {\n\t\t\tconst base = shape.integer === true ? isInteger : isFiniteNumber\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\t// `boundsOf` already refines `isFiniteNumber`; intersect with `isInteger`\n\t\t\t// when the leaf is an integer so both the integrality and the bounds hold.\n\t\t\treturn shape.integer === true\n\t\t\t\t? intersectionOf(isInteger, boundsOf(shape.min, shape.max))\n\t\t\t\t: boundsOf(shape.min, shape.max)\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn isBoolean\n\t\tcase 'null':\n\t\t\treturn isNull\n\t\tcase 'json':\n\t\t\treturn isJSONValue\n\t\tcase 'literal':\n\t\t\treturn literalOf(...shape.values)\n\t\tcase 'array': {\n\t\t\tconst base = arrayOf(compileGuard(shape.items))\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max)\n\t\t\treturn whereOf(base, (value) => withinLength(value.length))\n\t\t}\n\t\tcase 'object': {\n\t\t\t// Honest typing: a null-prototype accumulator so a property literally\n\t\t\t// named '__proto__' becomes an own data key instead of mutating the\n\t\t\t// prototype — the same pattern `pickOf` uses (combinators.ts).\n\t\t\tconst map: Record<string, Guard<unknown>> = Object.create(null)\n\t\t\tconst optionalKeys: string[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional') {\n\t\t\t\t\tmap[key] = compileGuard(child.inner)\n\t\t\t\t\toptionalKeys.push(key)\n\t\t\t\t} else {\n\t\t\t\t\tmap[key] = compileGuard<ContractShape>(child)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties\n\t\t\t// Closed object → the exact, optional-key-aware `recordOf`.\n\t\t\tif (extra === undefined || extra === false) {\n\t\t\t\treturn optionalKeys.length > 0 ? recordOf(map, optionalKeys) : recordOf(map)\n\t\t\t}\n\t\t\t// Open object → validate known keys, then accept (`true`) or guard extras.\n\t\t\tconst additional = extra === true ? undefined : compileGuard(extra)\n\t\t\tconst required = Object.keys(map).filter((key) => !optionalKeys.includes(key))\n\t\t\treturn (value: unknown): value is unknown => {\n\t\t\t\tif (!isRecord(value)) return false\n\t\t\t\tfor (const key of required) {\n\t\t\t\t\tif (!Object.hasOwn(value, key)) return false\n\t\t\t\t}\n\t\t\t\t// Contain the whole key-enumeration + value-read walk — a hostile\n\t\t\t\t// getter on `value` must yield `false`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\t\t\tconst guard = Object.hasOwn(map, key) ? map[key] : undefined\n\t\t\t\t\t\tif (guard !== undefined) {\n\t\t\t\t\t\t\tif (!guard(value[key])) return false\n\t\t\t\t\t\t} else if (additional !== undefined && !additional(value[key])) {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\treturn outcome.success && outcome.value\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst guards = shape.variants.map((variant) => compileGuard(variant))\n\t\t\t// A `oneOf`-mode union matches the emitted JSON Schema `oneOf` keyword —\n\t\t\t// EXACTLY one variant must guard-accept the value, not \"at least one\"\n\t\t\t// (unionOf's anyOf semantics). A value matching two-or-more variants is\n\t\t\t// rejected, since it would violate the compiled schema.\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\treturn (value: unknown): value is unknown =>\n\t\t\t\t\tguards.filter((guard) => guard(value)).length === 1\n\t\t\t}\n\t\t\treturn unionOf(...guards)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn orOf(isUndefined, compileGuard(shape.inner))\n\t\tcase 'nullable':\n\t\t\treturn nullableOf(compileGuard(shape.inner))\n\t\tcase 'raw':\n\t\t\t// The tautological always-true guard for `raw` — accepts anything, so `_value` is\n\t\t\t// genuinely unused (the `_` suppresses the unused-arg lint; AGENTS §4.8).\n\t\t\treturn (_value: unknown): _value is unknown => true\n\t}\n}\n\n// === Parser\n\n/**\n * Compile a {@link ContractShape} into an input parser.\n *\n * @remarks\n * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /\n * `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a\n * whole on any required-field failure; a union returns a guard-valid value\n * unchanged, otherwise the first variant that both parses and guards wins.\n *\n * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same\n * combinators `compileGuard` uses — `stringOf` for a string's length/pattern and\n * `boundsOf` for a number's value and an array's length — so a value that coerces\n * but violates a bound parses to `undefined`. The result is full parse↔guard\n * soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's\n * `is`, refinements included.\n *\n * @param shape - The shape to compile\n * @returns A parser yielding the shape's inferred type or `undefined`\n *\n * @example\n * ```ts\n * const parseUser = compileParser(objectShape({ name: stringShape() }))\n * parseUser({ name: 'Ada' }) // { name: 'Ada' }\n * ```\n */\nexport function compileParser<S extends ContractShape>(shape: S): Parser<Infer<S>>\nexport function compileParser(shape: ContractShape): Parser<unknown>\nexport function compileParser(shape: ContractShape): Parser<unknown> {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tif (shape.min === undefined && shape.max === undefined && shape.pattern === undefined) {\n\t\t\t\treturn parseString\n\t\t\t}\n\t\t\t// Coerce by type, then re-apply the SAME refinement the guard enforces (the\n\t\t\t// identical `stringOf`) — a value that parses but violates a bound or the\n\t\t\t// pattern fails the parse (returns `undefined`).\n\t\t\tconst guard = stringOf({ min: shape.min, max: shape.max, pattern: shape.pattern })\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = parseString(value)\n\t\t\t\treturn parsed !== undefined && guard(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst base = shape.integer === true ? parseInteger : parseNumber\n\t\t\tif (shape.min === undefined && shape.max === undefined) return base\n\t\t\t// The same bound check the guard applies (integrality is already enforced by\n\t\t\t// `parseInteger`, so only the bounds need re-checking after coercion).\n\t\t\tconst within = boundsOf(shape.min, shape.max)\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = base(value)\n\t\t\t\treturn parsed !== undefined && within(parsed) ? parsed : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean\n\t\tcase 'null':\n\t\t\treturn (value) => (value === null ? null : undefined)\n\t\tcase 'json':\n\t\t\treturn (value) => (isJSONValue(value) ? value : undefined)\n\t\t// The literal parser trims a matching string but never numeric-coerces —\n\t\t// `'42'` never parses to the literal `42`; only an exact (post-trim) match\n\t\t// of one of `shape.values` succeeds. This is an intended leniency, not a\n\t\t// soundness gap: a coerced value is always re-checked against `allowed`.\n\t\tcase 'literal': {\n\t\t\tconst allowed = new Set<unknown>(shape.values)\n\t\t\treturn (value) => {\n\t\t\t\tif (allowed.has(value)) return value\n\t\t\t\tif (isString(value)) {\n\t\t\t\t\tconst trimmed = value.trim()\n\t\t\t\t\tif (allowed.has(trimmed)) return trimmed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst item = compileParser(shape.items)\n\t\t\tconst unbounded = shape.min === undefined && shape.max === undefined\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max)\n\t\t\treturn (value) => {\n\t\t\t\tif (!isArray(value)) return undefined\n\t\t\t\tconst result: unknown[] = []\n\t\t\t\tfor (const entry of value) {\n\t\t\t\t\tconst parsed = item(entry)\n\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\tresult.push(parsed)\n\t\t\t\t}\n\t\t\t\t// Enforce the SAME length bounds the guard does (coercion never changes\n\t\t\t\t// length, so this is checked once on the assembled result).\n\t\t\t\treturn unbounded || withinLength(result.length) ? result : undefined\n\t\t\t}\n\t\t}\n\t\t// A closed object (no `additionalProperties`) silently drops unknown keys\n\t\t// present on the input rather than failing the parse — an intended\n\t\t// coercion leniency (the compiled guard still rejects them; this only\n\t\t// matters for guard-invalid inputs handed to `parse`).\n\t\tcase 'object': {\n\t\t\tconst entries: { key: string; parse: Parser<unknown>; optional: boolean }[] = []\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tconst optional = child.type === 'optional'\n\t\t\t\tentries.push({ key, parse: compileParser(optional ? child.inner : child), optional })\n\t\t\t}\n\t\t\tconst known = new Set(entries.map((entry) => entry.key))\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tconst additional =\n\t\t\t\textra === undefined || extra === false || extra === true ? undefined : compileParser(extra)\n\t\t\tconst open = extra === true || additional !== undefined\n\t\t\treturn (value) => {\n\t\t\t\tconst record = parseRecord(value)\n\t\t\t\tif (record === undefined) return undefined\n\t\t\t\t// Contain the whole record walk — a hostile getter on `record` must\n\t\t\t\t// yield `undefined`, never throw (AGENTS §14).\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\t// Honest typing: a null-prototype accumulator so an input own key\n\t\t\t\t\t// literally named '__proto__' lands as an own data key instead of\n\t\t\t\t\t// mutating the prototype (same pattern as `pickOf`).\n\t\t\t\t\tconst result: Record<string, unknown> = Object.create(null)\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst raw = record[entry.key]\n\t\t\t\t\t\tif (raw === undefined) {\n\t\t\t\t\t\t\tif (entry.optional) continue\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst parsed = entry.parse(raw)\n\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\tresult[entry.key] = parsed\n\t\t\t\t\t}\n\t\t\t\t\tif (open) {\n\t\t\t\t\t\tfor (const key of Object.keys(record)) {\n\t\t\t\t\t\t\tif (known.has(key)) continue\n\t\t\t\t\t\t\tif (additional === undefined) {\n\t\t\t\t\t\t\t\tresult[key] = record[key]\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst parsed = additional(record[key])\n\t\t\t\t\t\t\t\tif (parsed === undefined) return undefined\n\t\t\t\t\t\t\t\tresult[key] = parsed\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn result\n\t\t\t\t})\n\t\t\t\treturn outcome.success ? outcome.value : undefined\n\t\t\t}\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst variants = shape.variants.map((variant) => ({\n\t\t\t\tparse: compileParser(variant),\n\t\t\t\tguard: compileGuard(variant),\n\t\t\t}))\n\t\t\t// `oneOf` exactly-one semantics (documented on `oneOfShape`): judged on\n\t\t\t// the RAW input's guard matches only — no coercion fallback. Exactly one\n\t\t\t// variant's guard must accept the raw value; that variant's parser then\n\t\t\t// runs (its parse must equal the already guard-valid input by clause A).\n\t\t\t// Zero matches (no variant fits) or two-or-more matches (ambiguous —\n\t\t\t// which variant the value belongs to isn't well-defined) both fail the\n\t\t\t// parse, deliberately simpler than attempting a coercion-then-recheck\n\t\t\t// resolution for ambiguous input.\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\treturn (value) => {\n\t\t\t\t\tconst matches = variants.filter((variant) => variant.guard(value))\n\t\t\t\t\tconst [only] = matches\n\t\t\t\t\treturn matches.length === 1 && only !== undefined ? only.parse(value) : undefined\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn (value) => {\n\t\t\t\t// Identity pass first (AGENTS §14 clause A): a value already valid\n\t\t\t\t// against ANY variant's guard is returned unchanged, so an earlier\n\t\t\t\t// variant's coercion never overwrites a guard-valid input.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tif (variant.guard(value)) return value\n\t\t\t\t}\n\t\t\t\t// Coercion pass: no variant matched as-is, so parse-then-guard,\n\t\t\t\t// first variant that both parses and guards wins.\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tconst parsed = variant.parse(value)\n\t\t\t\t\tif (parsed !== undefined && variant.guard(parsed)) return parsed\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tcase 'optional': {\n\t\t\tconst inner = compileParser(shape.inner)\n\t\t\treturn (value) => (value === undefined ? undefined : inner(value))\n\t\t}\n\t\tcase 'nullable': {\n\t\t\tconst inner = compileParser(shape.inner)\n\t\t\treturn (value) => (value === null ? null : inner(value))\n\t\t}\n\t\tcase 'raw':\n\t\t\treturn (value) => value\n\t}\n}\n\n// === Generator\n\n/**\n * Compile a {@link ContractShape} into a deterministic seed value.\n *\n * @remarks\n * The same shape and the same `random` source always produce the same value, so\n * seed data is reproducible. Defaults to a {@link seededRandom} source seeded\n * from the wall clock when none is supplied. Throws on a degenerate empty\n * `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose\n * generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded\n * schema is arbitrary and cannot be auto-generated) — a programmer error that\n * cannot generate a value (AGENTS §12). `createContract` runs\n * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /\n * bounded shape is normally caught there; these throws remain here as defense\n * for standalone `compileGenerator` use.\n *\n * @param shape - The shape to generate from\n * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)\n * @returns A value matching the shape\n *\n * @example\n * ```ts\n * compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism)\n * ```\n */\nexport function compileGenerator<S extends ContractShape>(\n\tshape: S,\n\trandom?: RandomFunction,\n): Infer<S>\nexport function compileGenerator(shape: ContractShape, random?: RandomFunction): unknown\nexport function compileGenerator(\n\tshape: ContractShape,\n\trandom: RandomFunction = seededRandom(Date.now()),\n): unknown {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tconst min = shape.min ?? 0\n\t\t\tconst max = shape.max ?? Math.max(min, 12)\n\t\t\tconst length = Math.max(min, Math.min(max, 8))\n\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n\t\t\tlet value = ''\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tvalue += alphabet[Math.floor(random() * alphabet.length)]\n\t\t\t}\n\t\t\tif (shape.pattern !== undefined && !shape.pattern.test(value)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way',\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst min = shape.min ?? 0\n\t\t\tconst max = shape.max ?? 100\n\t\t\tif (shape.integer === true) {\n\t\t\t\tconst lo = Math.ceil(min)\n\t\t\t\tconst hi = Math.floor(max)\n\t\t\t\treturn Math.floor(random() * (hi - lo + 1)) + lo\n\t\t\t}\n\t\t\treturn random() * (max - min) + min\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn random() >= 0.5\n\t\tcase 'null':\n\t\t\treturn null\n\t\tcase 'json': {\n\t\t\tconst pick = Math.floor(random() * 5)\n\t\t\tif (pick === 0) return null\n\t\t\tif (pick === 1) return random() >= 0.5\n\t\t\tif (pick === 2) return Math.floor(random() * 1000)\n\t\t\tif (pick === 3) {\n\t\t\t\tconst alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\t\t\t\tlet value = ''\n\t\t\t\tfor (let index = 0; index < 6; index += 1) {\n\t\t\t\t\tvalue += alphabet[Math.floor(random() * alphabet.length)]\n\t\t\t\t}\n\t\t\t\treturn value\n\t\t\t}\n\t\t\treturn { value: Math.floor(random() * 1000) }\n\t\t}\n\t\tcase 'literal': {\n\t\t\tif (shape.values.length === 0) {\n\t\t\t\tthrow new Error('compileGenerator: a literal shape needs at least one value')\n\t\t\t}\n\t\t\treturn shape.values[Math.floor(random() * shape.values.length)]\n\t\t}\n\t\tcase 'array': {\n\t\t\tconst lo = shape.min ?? Math.min(1, shape.max ?? 1)\n\t\t\tconst hi = shape.max ?? Math.max(lo, 3)\n\t\t\tconst length = Math.floor(random() * (hi - lo + 1)) + lo\n\t\t\tconst result: unknown[] = []\n\t\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\t\tresult.push(compileGenerator(shape.items, random))\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'object': {\n\t\t\tconst result: Record<string, unknown> = {}\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key]\n\t\t\t\tif (child === undefined) continue\n\t\t\t\tif (child.type === 'optional' && random() < 0.3) continue\n\t\t\t\tresult[key] = compileGenerator(child, random)\n\t\t\t}\n\t\t\t// An open object (additionalProperties is a shape, not a boolean) also\n\t\t\t// generates synthetic extra entries so the shape does not trivially\n\t\t\t// generate as `{}` — skip any collision with a declared property name.\n\t\t\tconst extra = shape.additionalProperties\n\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\tconst count = 1 + Math.floor(random() * 2)\n\t\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\t\tconst key = `key${index}`\n\t\t\t\t\tif (Object.hasOwn(result, key)) continue\n\t\t\t\t\tresult[key] = compileGenerator(extra, random)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result\n\t\t}\n\t\tcase 'union': {\n\t\t\tif (shape.variants.length === 0) {\n\t\t\t\tthrow new Error('compileGenerator: a union shape needs at least one variant')\n\t\t\t}\n\t\t\treturn compileGenerator(shape.variants[Math.floor(random() * shape.variants.length)], random)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn compileGenerator(shape.inner, random)\n\t\tcase 'nullable':\n\t\t\treturn random() < 0.2 ? null : compileGenerator(shape.inner, random)\n\t\tcase 'raw':\n\t\t\tthrow new Error(\n\t\t\t\t'compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way',\n\t\t\t)\n\t}\n}\n\n// === Reporter\n\n/**\n * Compile a {@link ContractShape} into a structured fault report for a value —\n * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.\n *\n * @remarks\n * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards\n * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /\n * `isJSONValue` / …), so the soundness invariant\n * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`\n * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a\n * coercible value like `'42'` against a `numberShape` reports no fault, the\n * same leniency `parse` grants, even though the strict guard would reject it).\n *\n * Faults are collected in stable pre-order (declared key/index order); every\n * call — object, array, and union alike, including a union's `oneOf` \"no\n * match\" / \"no consensus\" summary fault prepended to its closest variant's\n * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the\n * bound holds at every level of nesting, not just the outermost container, on\n * adversarial input (a huge array, a wide record, a wide union of wide\n * records). A closed object's extra keys never\n * fault — `parse` silently drops them, so `explain` mirrors that leniency; an\n * open object with a constraining `additionalProperties` shape recurses extras\n * against it instead. A hostile getter or throwing `Proxy` trap is contained\n * via {@link attempt} and surfaces as a single top-level type fault, never a\n * throw (AGENTS §14).\n *\n * @param shape - The shape to report against\n * @param value - The value to check\n * @param path - The path prefix for faults produced at this call (defaults to the root)\n * @returns The faults found, empty when the value parses successfully\n *\n * @example\n * ```ts\n * const user = objectShape({ name: stringShape({ min: 1 }) })\n * compileReporter(user, { name: '' })\n * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '\"\"' }]\n * compileReporter(user, { name: 'Ada' }) // []\n * ```\n */\nexport function compileReporter(\n\tshape: ContractShape,\n\tvalue: unknown,\n\tpath: string[] = [],\n): readonly Fault[] {\n\tswitch (shape.type) {\n\t\tcase 'string': {\n\t\t\tconst parsed = parseString(value)\n\t\t\tif (parsed === undefined) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'string', received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tif (shape.min !== undefined && parsed.length < shape.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: shape.min,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.max !== undefined && parsed.length > shape.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: shape.max,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.pattern !== undefined && !shape.pattern.test(parsed)) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'string',\n\t\t\t\t\tconstraint: 'pattern',\n\t\t\t\t\tlimit: shape.pattern.source,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst kind: FaultKind = shape.integer === true ? 'integer' : 'number'\n\t\t\tconst parsed = parseNumber(value)\n\t\t\tif (parsed === undefined) {\n\t\t\t\treturn [{ reason: 'type', path, expected: kind, received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tif (shape.integer === true && !Number.isInteger(parsed)) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'integer',\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.min !== undefined && parsed < shape.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: shape.min,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.max !== undefined && parsed > shape.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: kind,\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: shape.max,\n\t\t\t\t\treceived: preview(parsed),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults\n\t\t}\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean(value) === undefined\n\t\t\t\t? [{ reason: 'type', path, expected: 'boolean', received: preview(value) }]\n\t\t\t\t: []\n\t\tcase 'null':\n\t\t\treturn value === null\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'null', received: preview(value) }]\n\t\tcase 'json':\n\t\t\treturn isJSONValue(value)\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'json', received: preview(value) }]\n\t\tcase 'literal': {\n\t\t\tconst allowed = new Set<unknown>(shape.values)\n\t\t\tconst matched = allowed.has(value) || (isString(value) && allowed.has(value.trim()))\n\t\t\treturn matched\n\t\t\t\t? []\n\t\t\t\t: [{ reason: 'type', path, expected: 'literal', received: preview(value) }]\n\t\t}\n\t\tcase 'array': {\n\t\t\tif (!isArray(value)) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'array', received: preview(value) }]\n\t\t\t}\n\t\t\tconst faults: Fault[] = []\n\t\t\tconst outcome = attempt(() => {\n\t\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\tfaults.push(...compileReporter(shape.items, value[index], [...path, String(index)]))\n\t\t\t\t}\n\t\t\t})\n\t\t\tif (!outcome.success) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'array', received: preview(value) }]\n\t\t\t}\n\t\t\tif (shape.min !== undefined && value.length < shape.min) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'array',\n\t\t\t\t\tconstraint: 'min',\n\t\t\t\t\tlimit: shape.min,\n\t\t\t\t\treceived: String(value.length),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (shape.max !== undefined && value.length > shape.max) {\n\t\t\t\tfaults.push({\n\t\t\t\t\treason: 'constraint',\n\t\t\t\t\tpath,\n\t\t\t\t\texpected: 'array',\n\t\t\t\t\tconstraint: 'max',\n\t\t\t\t\tlimit: shape.max,\n\t\t\t\t\treceived: String(value.length),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn faults.length > FAULT_LIMIT ? faults.slice(0, FAULT_LIMIT) : faults\n\t\t}\n\t\tcase 'object': {\n\t\t\tif (!isRecord(value)) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'object', received: preview(value) }]\n\t\t\t}\n\t\t\tconst record = value\n\t\t\tconst faults: Fault[] = []\n\t\t\tconst known = new Set<string>()\n\t\t\tconst outcome = attempt(() => {\n\t\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\tconst child = shape.properties[key]\n\t\t\t\t\tif (child === undefined) continue\n\t\t\t\t\tknown.add(key)\n\t\t\t\t\tconst optional = child.type === 'optional'\n\t\t\t\t\tconst inner = optional ? child.inner : child\n\t\t\t\t\t// Mirror the parser's presence gate exactly (compileParser,\n\t\t\t\t\t// object branch, ~line 492): a property is \"absent\" when its\n\t\t\t\t\t// VALUE is `undefined`, not when the key itself is missing\n\t\t\t\t\t// (`Object.hasOwn`) — a present key with an explicit `undefined`\n\t\t\t\t\t// value is treated identically to a missing one, so `explain`\n\t\t\t\t\t// never faults (or recurses into the inner reporter) where\n\t\t\t\t\t// `parse` silently skips it.\n\t\t\t\t\tconst raw = record[key]\n\t\t\t\t\tif (raw === undefined) {\n\t\t\t\t\t\tif (!optional) {\n\t\t\t\t\t\t\tfaults.push({ reason: 'missing', path: [...path, key], expected: shapeToKind(inner) })\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfaults.push(...compileReporter(inner, raw, [...path, key]))\n\t\t\t\t}\n\t\t\t\tconst extra = shape.additionalProperties\n\t\t\t\tif (extra !== undefined && extra !== true && extra !== false) {\n\t\t\t\t\tfor (const key of Object.keys(record)) {\n\t\t\t\t\t\tif (faults.length >= FAULT_LIMIT) return\n\t\t\t\t\t\tif (known.has(key)) continue\n\t\t\t\t\t\tfaults.push(...compileReporter(extra, record[key], [...path, key]))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\tif (!outcome.success) {\n\t\t\t\treturn [{ reason: 'type', path, expected: 'object', received: preview(value) }]\n\t\t\t}\n\t\t\treturn faults.length > FAULT_LIMIT ? faults.slice(0, FAULT_LIMIT) : faults\n\t\t}\n\t\tcase 'union': {\n\t\t\tconst perVariant = shape.variants.map((variant) => compileReporter(variant, value, path))\n\t\t\tlet bestIndex = 0\n\t\t\tfor (let index = 1; index < perVariant.length; index += 1) {\n\t\t\t\tconst current = perVariant[index]\n\t\t\t\tconst best = perVariant[bestIndex]\n\t\t\t\tif (current !== undefined && best !== undefined && current.length < best.length) {\n\t\t\t\t\tbestIndex = index\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst closest = perVariant[bestIndex] ?? []\n\t\t\tif (shape.mode === 'oneOf') {\n\t\t\t\tlet matched = 0\n\t\t\t\tfor (const variant of shape.variants) {\n\t\t\t\t\tif (compileGuard(variant)(value)) matched += 1\n\t\t\t\t}\n\t\t\t\tif (matched === 1) return []\n\t\t\t\tif (matched === 0) {\n\t\t\t\t\tconst summary: Fault = { reason: 'oneOf', path, matched: 0 }\n\t\t\t\t\treturn [summary, ...closest].slice(0, FAULT_LIMIT)\n\t\t\t\t}\n\t\t\t\treturn [{ reason: 'oneOf', path, matched }]\n\t\t\t}\n\t\t\tconst anyMatch = perVariant.some((variantFaults) => variantFaults.length === 0)\n\t\t\tif (anyMatch) return []\n\t\t\tconst summary: Fault = { reason: 'variant', path, variants: shape.variants.length }\n\t\t\treturn [summary, ...closest].slice(0, FAULT_LIMIT)\n\t\t}\n\t\tcase 'optional':\n\t\t\treturn value === undefined ? [] : compileReporter(shape.inner, value, path)\n\t\tcase 'nullable':\n\t\t\treturn value === null ? [] : compileReporter(shape.inner, value, path)\n\t\tcase 'raw':\n\t\t\treturn []\n\t}\n}\n\n// === Contract\n\n/**\n * Compile a {@link ContractShape} into a {@link ContractInterface} — the four\n * lockstep outputs from one declaration.\n *\n * @remarks\n * Runs {@link validateShape} first — a malformed shape throws immediately\n * rather than compiling into a silently-wrong contract (AGENTS §12). Then\n * precompiles the schema, guard, and parser once; `generate` walks the shape\n * per call with the supplied random source, and `explain` compiles the\n * diagnostic report via {@link compileReporter} at zero added compile-time cost\n * (it re-walks the shape per call, exactly like `generate`).\n *\n * @param shape - The shape to compile\n * @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`\n *\n * @example\n * ```ts\n * const user = createContract(objectShape({ name: stringShape(), age: integerShape() }))\n * user.is({ name: 'Ada', age: 36 }) // true\n * user.parse({ name: 'Ada', age: '36' }) // { name: 'Ada', age: 36 }\n * user.schema // { type: 'object', properties: { … }, … }\n * ```\n */\nexport function createContract<S extends ContractShape>(shape: S): ContractInterface<Infer<S>>\nexport function createContract(shape: ContractShape): ContractInterface<unknown>\nexport function createContract(shape: ContractShape): ContractInterface<unknown> {\n\tvalidateShape(shape)\n\tconst schema = compileSchema(shape)\n\tconst guard = compileGuard(shape)\n\tconst parser = compileParser(shape)\n\treturn {\n\t\tschema,\n\t\tis: guard,\n\t\tparse(value: unknown): unknown {\n\t\t\treturn parser(value)\n\t\t},\n\t\texplain(value: unknown): readonly Fault[] {\n\t\t\treturn compileReporter(shape, value)\n\t\t},\n\t\tgenerate(random?: RandomFunction): unknown {\n\t\t\treturn compileGenerator(shape, random)\n\t\t},\n\t}\n}\n","import type { JSONSchema, SchemaFormat, ValueToSchemaOptions } from './types.js'\nimport {\n\tFORMAT_MAX_LENGTH,\n\tFORMAT_PATTERNS,\n\tINFER_BREADTH_LIMIT,\n\tINFER_DEPTH_LIMIT,\n\tINFER_ENUM_LIMIT,\n} from './constants.js'\nimport {\n\tisArray,\n\tisBoolean,\n\tisDate,\n\tisFiniteNumber,\n\tisInteger,\n\tisNull,\n\tisNumber,\n\tisRecord,\n\tisString,\n} from './validators.js'\nimport { attempt, sanitizeBudget } from './helpers.js'\n\n// The inferers walk an UNKNOWN, possibly adversarial runtime value (or a set\n// of example values) and emit a JSONSchema — the reverse direction of\n// compileSchema (compilers.ts), which walks a finite, developer-authored\n// ContractShape tree. Recursion here is runtime-only and bounded on three\n// axes: a WeakSet of ancestor objects/arrays (cycle safety), a decrementing\n// depth budget (INFER_DEPTH_LIMIT default), and a per-container sampling cap\n// (INFER_BREADTH_LIMIT default) — every branch stays total, per AGENTS §14.\n\n// === Canonicalization\n\n/**\n * Render a value as a deterministic, key-sorted JSON string.\n *\n * @remarks\n * The stable-stringify backing {@link unifySchemas}'s de-duplication and\n * ordering: unlike `JSON.stringify`, object keys are sorted before encoding\n * (recursively, at every nesting level), so two structurally-equal\n * `JSONSchema` fragments built independently always canonicalize to the same\n * string. Pure ECMAScript — no `structuredClone`, no `node:*` import.\n *\n * @param value - The value to canonicalize (a `JSONSchema` fragment, or any\n * nested piece of one)\n * @returns A deterministic string encoding of `value`\n *\n * @example\n * ```ts\n * canonicalStringify({ type: 'object', properties: {} }) ===\n * \tcanonicalStringify({ properties: {}, type: 'object' }) // true\n * ```\n */\nexport function canonicalStringify(value: unknown): string {\n\tif (isArray(value)) {\n\t\treturn `[${value.map((entry) => canonicalStringify(entry)).join(',')}]`\n\t}\n\tif (isRecord(value)) {\n\t\tconst keys = Object.keys(value).sort()\n\t\tconst parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalStringify(value[key])}`)\n\t\treturn `{${parts.join(',')}}`\n\t}\n\treturn JSON.stringify(value)\n}\n\n/**\n * Unify a list of inferred `JSONSchema` fragments into one schema.\n *\n * @remarks\n * De-duplicates by {@link canonicalStringify}, then applies the one\n * special-case subsumption inference performs: a bare `{ type: 'integer' }`\n * alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }`\n * (an integer sample is also a valid `number` sample). A single surviving\n * distinct schema is returned directly; two or more are wrapped as\n * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.\n * An empty input list returns the empty accept-anything schema `{}`.\n *\n * @param schemas - The schemas to unify\n * @returns The unified schema\n *\n * @example\n * ```ts\n * unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' }\n * unifySchemas([{ type: 'string' }, { type: 'boolean' }])\n * // { anyOf: [{ type: 'boolean' }, { type: 'string' }] }\n * ```\n */\nexport function unifySchemas(schemas: readonly JSONSchema[]): JSONSchema {\n\tif (schemas.length === 0) return {}\n\tconst seen = new Map<string, JSONSchema>()\n\tfor (const schema of schemas) {\n\t\tconst key = canonicalStringify(schema)\n\t\tif (!seen.has(key)) seen.set(key, schema)\n\t}\n\tconst integerKey = canonicalStringify({ type: 'integer' })\n\tconst numberKey = canonicalStringify({ type: 'number' })\n\tif (seen.has(integerKey) && seen.has(numberKey)) {\n\t\tseen.delete(integerKey)\n\t}\n\tconst distinct = [...seen.entries()]\n\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))\n\t\t.map(([, schema]) => schema)\n\tif (distinct.length <= 1) {\n\t\tconst [only] = distinct\n\t\treturn only ?? {}\n\t}\n\treturn { anyOf: distinct }\n}\n\n// === Format inference\n\n/**\n * Determine whether an ISO-8601-shaped string parses to a valid instant.\n *\n * @remarks\n * A pure, attempt-guarded `Date` validity probe: `new Date(value)` never\n * throws on a string input, but a value like `2020-13-45` parses to an\n * `Invalid Date` whose `getTime()` is `NaN` — this is the real validation\n * step behind {@link stringToFormat}'s `date` / `date-time` / `time`\n * branches, which pattern-match the shape first and confirm validity here.\n *\n * @param value - The candidate ISO-8601 string\n * @returns `true` when `value` parses to a real instant\n *\n * @example\n * ```ts\n * isValidISOInstant('2020-01-01') // true\n * isValidISOInstant('2020-13-45') // false\n * ```\n */\nexport function isValidISOInstant(value: string): boolean {\n\tconst outcome = attempt(() => {\n\t\tconst date = new Date(value)\n\t\treturn !Number.isNaN(date.getTime())\n\t})\n\treturn outcome.success && outcome.value\n}\n\n/**\n * Classify a string against the {@link SchemaFormat} vocabulary.\n *\n * @remarks\n * Total, pure, and deterministic. Fixed precedence, most specific first:\n * `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first\n * match wins. The `date-time` / `date` / `time` branches require BOTH a\n * strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity\n * check, so a shape-plausible but impossible date (`2020-13-45`) is rejected.\n * Returns `undefined` when no format matches (including the empty string).\n *\n * @param value - The string to classify\n * @returns The matched {@link SchemaFormat}, or `undefined`\n *\n * @example\n * ```ts\n * stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid'\n * stringToFormat('2024-01-15') // 'date'\n * stringToFormat('2020-13-45') // undefined — invalid date\n * stringToFormat('ada@example.com') // 'email'\n * stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset\n * stringToFormat('10:30:00+02:00') // 'time'\n * ```\n */\nexport function stringToFormat(value: string): SchemaFormat | undefined {\n\tif (value.length > FORMAT_MAX_LENGTH) return undefined\n\tif (FORMAT_PATTERNS.uuid.test(value)) return 'uuid'\n\tif (\n\t\t/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n\t\tisValidISOInstant(value)\n\t) {\n\t\treturn 'date-time'\n\t}\n\tif (/^\\d{4}-\\d{2}-\\d{2}$/.test(value) && isValidISOInstant(value)) {\n\t\treturn 'date'\n\t}\n\tif (\n\t\t/^\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n\t\tisValidISOInstant(`1970-01-01T${value}`)\n\t) {\n\t\treturn 'time'\n\t}\n\tif (FORMAT_PATTERNS.email.test(value)) return 'email'\n\tif (FORMAT_PATTERNS.uri.test(value)) return 'uri'\n\treturn undefined\n}\n\n/**\n * Classify a list of sample values against the {@link SchemaFormat}\n * vocabulary, requiring unanimity.\n *\n * @remarks\n * A format is returned ONLY IF every value is a string AND every one maps to\n * the SAME {@link stringToFormat} result (including all mapping to\n * `undefined`, which itself returns `undefined` here). A single disagreeing\n * value, a non-string value, or an empty list all yield `undefined` — the\n * multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples})\n * relies on this unanimity so a slot with mixed string shapes emits a bare\n * `{ type: 'string' }` rather than an `anyOf` of formats.\n *\n * @param values - The sample values to classify\n * @returns The unanimous {@link SchemaFormat}, or `undefined`\n *\n * @example\n * ```ts\n * samplesToFormat(['2024-01-01', '2024-02-02']) // 'date'\n * samplesToFormat(['2024-01-01', 'not a date']) // undefined\n * samplesToFormat([]) // undefined\n * ```\n */\nexport function samplesToFormat(values: readonly unknown[]): SchemaFormat | undefined {\n\tif (values.length === 0 || !values.every((value) => isString(value))) return undefined\n\tconst formats = values.map((value) => stringToFormat(value))\n\tconst [first, ...rest] = formats\n\tif (first === undefined) return undefined\n\treturn rest.every((format) => format === first) ? first : undefined\n}\n\n// === Enum inference\n\n/**\n * Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated\n * primitive slot — the multi-sample-only counterpart to\n * {@link stringToFormat} ({@link valueToSchema} never emits `enum`).\n *\n * @remarks\n * Fires only when ALL of: every value is the same primitive kind (all string\n * or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed\n * slot never qualifies, and a slot containing `NaN` / `±Infinity` never\n * qualifies either, since {@link canonicalStringify} collapses `NaN` to\n * `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2\n * values are given; the distinct-by-{@link canonicalStringify} count is LESS\n * than the value count (repetition required — separates a categorical column\n * from an ID column); and the distinct count is at most `limit`. The emitted\n * schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s\n * `literalShape` emission. Members are sorted by canonical key for\n * deterministic output.\n *\n * @param values - The collected slot values\n * @param limit - The maximum distinct-value count before giving up\n * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible\n *\n * @example\n * ```ts\n * inferPrimitiveEnum(['active', 'inactive', 'active'], 12)\n * // { enum: ['active', 'inactive'] }\n * inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition\n * ```\n */\nexport function inferPrimitiveEnum(\n\tvalues: readonly unknown[],\n\tlimit: number,\n): JSONSchema | undefined {\n\tif (values.length < 2) return undefined\n\tconst allString = values.every((value) => isString(value))\n\tconst allNumber = !allString && values.every((value) => isFiniteNumber(value))\n\tif (!allString && !allNumber) return undefined\n\tconst distinct = new Map<string, string | number>()\n\tfor (const value of values) {\n\t\tif (isString(value) || isFiniteNumber(value)) distinct.set(canonicalStringify(value), value)\n\t}\n\tif (distinct.size >= values.length || distinct.size > limit) return undefined\n\tconst sorted = [...distinct.entries()].sort(([left], [right]) =>\n\t\tleft < right ? -1 : left > right ? 1 : 0,\n\t)\n\treturn { enum: sorted.map(([, value]) => value) }\n}\n\n// === Single-value inference\n\n/**\n * Infer a `JSONSchema` fragment for one runtime value — the recursive spine\n * shared by {@link valueToSchema} and, per collected property/element, by\n * {@link inferArray} / {@link inferObject}.\n *\n * @remarks\n * Total: never throws, and terminates on cyclic input via `visited`. Leaf\n * classification order: `null`, boolean, integer (`Number.isInteger`\n * semantics — `-0` counts), finite non-integer number, non-finite number\n * (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a\n * `format` keyword when `format` is on and {@link stringToFormat} matches),\n * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,\n * plus `format: 'date-time'` when `format` is on); everything else\n * (function, symbol, bigint, `undefined`, and other non-plain objects such as\n * `Map` / `Set`) is the empty accept-anything schema `{}`.\n *\n * @param value - The value to classify\n * @param depth - Remaining descent budget (0 halts recursion with `{}`)\n * @param breadth - The per-container sampling cap passed through to children\n * @param closed - Whether descended objects emit `additionalProperties: false`\n * @param format - Whether a string/`Date` leaf gains a `format` keyword\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred schema fragment for `value`\n *\n * @example\n * ```ts\n * inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' }\n * ```\n */\nexport function inferValue(\n\tvalue: unknown,\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (isNull(value)) return { type: 'null' }\n\tif (isBoolean(value)) return { type: 'boolean' }\n\tif (isInteger(value)) return { type: 'integer' }\n\tif (isFiniteNumber(value)) return { type: 'number' }\n\tif (isNumber(value)) return { type: 'number' }\n\tif (isString(value)) {\n\t\tif (format) {\n\t\t\tconst detected = stringToFormat(value)\n\t\t\tif (detected) return { type: 'string', format: detected }\n\t\t}\n\t\treturn { type: 'string' }\n\t}\n\tif (isArray(value)) return inferArray(value, depth, breadth, closed, format, visited, memo)\n\tif (isRecord(value)) return inferObject(value, depth, breadth, closed, format, visited, memo)\n\tif (isDate(value)) return format ? { type: 'string', format: 'date-time' } : { type: 'string' }\n\treturn {}\n}\n\n/**\n * Infer a `JSONSchema` array fragment from an array's sampled elements.\n *\n * @remarks\n * An empty array infers `{ type: 'array' }` with no `items`. Otherwise the\n * first `breadth` elements are classified via {@link inferValue} (one less\n * depth) and unified with {@link unifySchemas}: a single distinct element\n * schema becomes `items` directly; multiple distinct schemas become\n * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of\n * `value` both yield the empty schema `{}` instead of descending. A sparse\n * array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before\n * sampling so every slot — including a hole — is visited as an explicit\n * `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left\n * as a hole that would otherwise reach {@link unifySchemas} as `undefined`.\n *\n * ALL reads of `value` — including its `length` — happen inside\n * {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose\n * `get` trap throws) is exactly as contained as a throwing own-getter element\n * or a Proxy-over-array element access, and cannot escape as a thrown error.\n * On failure — or when the sampled/classified list ends up empty — this\n * returns `{ type: 'array' }` (no `items`), since `value` is still known to\n * be an array, mirroring the empty-array emission. A same-object\n * re-inference at the same remaining `depth` is served from `memo` instead\n * of recomputing (guards a shared-reference DAG against exponential blowup).\n *\n * @param value - The array to infer from\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of elements sampled\n * @param closed - Threaded through to nested object elements\n * @param format - Threaded through to nested string/`Date` elements\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred array schema\n *\n * @example\n * ```ts\n * inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap())\n * // { type: 'array', items: { type: 'number' } }\n * ```\n */\nexport function inferArray(\n\tvalue: readonly unknown[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (!(depth > 0) || visited.has(value)) return {}\n\t// At a node reached through a cycle at the SAME remaining depth via two\n\t// different paths, the memo may serve the first traversal's already\n\t// cycle-truncated fragment (`{}`) to the second path instead of a fully\n\t// re-descended schema — a sound, deterministic over-approximation, never\n\t// a false-reject (a schema too permissive, never too strict).\n\tconst cached = memo.get(value)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(value)\n\tconst outcome = attempt(() => {\n\t\tconst sampled = Array.from(value.slice(0, breadth))\n\t\treturn sampled.map((entry) =>\n\t\t\tinferValue(entry, depth - 1, breadth, closed, format, visited, memo),\n\t\t)\n\t})\n\tvisited.delete(value)\n\tconst schema: JSONSchema =\n\t\toutcome.success && outcome.value.length > 0\n\t\t\t? { type: 'array', items: unifySchemas(outcome.value) }\n\t\t\t: { type: 'array' }\n\tlet depths = memo.get(value)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(value, depths)\n\t}\n\tdepths.set(depth, schema)\n\treturn schema\n}\n\n/**\n * Infer a `JSONSchema` object fragment from a plain record's sampled\n * properties.\n *\n * @remarks\n * Own enumerable string keys via `Object.keys`, sorted lexicographically for\n * deterministic output, capped at `breadth`. Each property value is read\n * through {@link attempt} so a hostile getter cannot escape as a thrown\n * error; a property whose value is `undefined` (hostile-getter failure\n * included) is treated as ABSENT — it contributes neither a `properties`\n * entry nor a `required` entry. Every other present key is required (single-\n * value mode). Emits `additionalProperties: false` when `closed`, `true`\n * otherwise — mirroring {@link compileSchema}'s object-emission convention —\n * EXCEPT when the own-key list exceeds `breadth`: a truncated key list means\n * the sampled schema no longer describes every property `value` actually\n * carries, so `additionalProperties` is forced to `true` regardless of\n * `closed` (a closed schema built from a truncated sample would otherwise\n * reject the very object it was inferred from). Depth exhaustion or a cyclic\n * re-encounter of `value` both yield `{}`. A same-object re-inference at the\n * same remaining `depth` is served from `memo` instead of recomputing\n * (guards a shared-reference DAG against exponential blowup).\n *\n * @param value - The record to infer from\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties sampled\n * @param closed - Whether the emitted schema closes to unknown keys\n * @param format - Threaded through to nested string/`Date` properties\n * @param visited - The ancestor set guarding against cycles\n * @param memo - A per-call `(object, remaining depth) → schema` cache guarding\n * against exponential re-inference of a shared-reference DAG\n * @returns The inferred object schema\n *\n * @example\n * ```ts\n * inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap())\n * // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'],\n * // additionalProperties: false }\n * ```\n */\nexport function inferObject(\n\tvalue: Record<string, unknown>,\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tvisited: WeakSet<object>,\n\tmemo: WeakMap<object, Map<number, JSONSchema>>,\n): JSONSchema {\n\tif (!(depth > 0) || visited.has(value)) return {}\n\tconst cached = memo.get(value)?.get(depth)\n\tif (cached) return cached\n\tvisited.add(value)\n\t// Contain the whole key-enumeration + value-read walk — a hostile ownKeys\n\t// trap or property getter on `value` must yield {} for this object, never\n\t// throw (AGENTS §14) — mirroring compileGuard's object branch\n\t// (compilers.ts).\n\tconst outcome = attempt(() => {\n\t\tconst allKeys = Object.keys(value).sort()\n\t\tconst keys = allKeys.slice(0, breadth)\n\t\tconst truncated = allKeys.length > breadth\n\t\t// Honest typing: a null-prototype accumulator so a property literally\n\t\t// named '__proto__' becomes an own data key instead of mutating the\n\t\t// prototype — the same pattern compileGuard / compileParser use\n\t\t// (compilers.ts).\n\t\tconst properties: Record<string, JSONSchema> = Object.create(null)\n\t\tconst required: string[] = []\n\t\tfor (const key of keys) {\n\t\t\tconst propertyValue = value[key]\n\t\t\tif (propertyValue === undefined) continue\n\t\t\tproperties[key] = inferValue(propertyValue, depth - 1, breadth, closed, format, visited, memo)\n\t\t\trequired.push(key)\n\t\t}\n\t\treturn { properties, required, truncated }\n\t})\n\tvisited.delete(value)\n\tif (!outcome.success) return {}\n\tconst { properties, required, truncated } = outcome.value\n\tconst schema: JSONSchema = {\n\t\ttype: 'object',\n\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t...(required.length > 0 ? { required } : {}),\n\t\tadditionalProperties: truncated ? true : !closed,\n\t}\n\tlet depths = memo.get(value)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tmemo.set(value, depths)\n\t}\n\tdepths.set(depth, schema)\n\treturn schema\n}\n\n/**\n * Infer a `JSONSchema` for one unknown value — the reverse direction of\n * {@link compileSchema}.\n *\n * @remarks\n * Total: never throws, and is cycle/depth/breadth-bounded (see\n * {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested\n * objects close to unknown keys (`additionalProperties: false`) by default;\n * pass `closed: false` to open them. `format` (default `false`) opts a\n * string/`Date` leaf into the `format` keyword. Structurally-equal inputs\n * infer byte-identical schemas (object keys and `anyOf` members are sorted).\n *\n * A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string'\n * }` — is structurally accepted by `schemaToParameters`, but MCP clients\n * expect an object-shaped `inputSchema`; wrap a non-object payload with\n * {@link schemaToObject} before advertising it as a tool's parameters.\n *\n * `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a\n * finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /\n * {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,\n * fractional) — a hostile or malformed budget can never defeat the depth\n * guard or corrupt the sampled key/element list.\n *\n * @param value - The value to infer a schema from\n * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds\n * @returns The inferred `JSONSchema`\n *\n * @example\n * ```ts\n * valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] })\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' },\n * // tags: { type: 'array', items: { type: 'string' } } },\n * // required: ['id', 'name', 'tags'], additionalProperties: false }\n * ```\n */\nexport function valueToSchema(value: unknown, options?: ValueToSchemaOptions): JSONSchema {\n\tconst maxDepth = sanitizeBudget(options?.maxDepth, INFER_DEPTH_LIMIT)\n\tconst maxProperties = sanitizeBudget(options?.maxProperties, INFER_BREADTH_LIMIT)\n\tconst closed = options?.closed ?? true\n\tconst format = options?.format ?? false\n\treturn inferValue(value, maxDepth, maxProperties, closed, format, new WeakSet(), new WeakMap())\n}\n\n// === Multi-sample inference\n\n/**\n * Infer a `JSONSchema` for a collected slot of sample values — the shared\n * non-record recursion step behind {@link samplesToSchema} (top level) and\n * {@link inferRecordSamples} (per collected property).\n *\n * @remarks\n * When every value is itself a plain record, delegates to\n * {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when\n * `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality,\n * repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins\n * outright (ENUM > FORMAT > bare string). Failing that, each value is\n * classified independently via {@link inferValue} with `format` FORCED OFF\n * (the multi-sample seam: nested formats never compound into an `anyOf`) and\n * unified with {@link unifySchemas}; only when that unified result is exactly\n * `{ type: 'string' }` and the outer `format` flag is on does\n * {@link samplesToFormat} run to (maybe) reattach a unanimous `format`.\n *\n * @param samples - The collected slot values\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties/elements sampled per nested container\n * @param closed - Whether nested objects close to unknown keys\n * @param format - Whether a unanimous string slot gains a `format` keyword\n * @param enumOn - Whether low-cardinality primitive slots may emit `enum`\n * @returns The inferred schema for the slot\n *\n * @example\n * ```ts\n * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)\n * // { type: 'string', format: 'date' }\n * ```\n */\nexport function inferSamples(\n\tsamples: readonly unknown[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tenumOn: boolean,\n): JSONSchema {\n\tif (samples.length === 0) return {}\n\tif (samples.every((sample) => isRecord(sample))) {\n\t\treturn inferRecordSamples(samples, depth, breadth, closed, format, enumOn)\n\t}\n\tif (enumOn) {\n\t\tconst enumSchema = inferPrimitiveEnum(samples, INFER_ENUM_LIMIT)\n\t\tif (enumSchema) return enumSchema\n\t}\n\tconst schemas = samples.map((sample) =>\n\t\tinferValue(sample, depth, breadth, closed, false, new WeakSet(), new WeakMap()),\n\t)\n\tconst unified = unifySchemas(schemas)\n\tif (format && unified.type === 'string' && Object.keys(unified).length === 1) {\n\t\tconst detected = samplesToFormat(samples)\n\t\tif (detected) return { type: 'string', format: detected }\n\t}\n\treturn unified\n}\n\n/**\n * Infer a `JSONSchema` object fragment from a set of plain-record samples\n * (e.g. database rows) — the record-specialized branch of\n * {@link samplesToSchema}.\n *\n * @remarks\n * `properties` is the union of every sample's own keys (sorted, capped at\n * `breadth`); a key is `required` only when present (and non-`undefined`) in\n * EVERY sample. Each key's schema is inferred over the collected values for\n * that key via {@link inferSamples} itself (one less depth), so a\n * property that is itself an array/object of varying shape across rows is\n * unified the same way the top level is, and the same `format` / `enum`\n * gating applies per key. Unlike {@link inferObject}/\n * {@link inferArray}, this path carries no `visited` `WeakSet` — a value\n * shared by reference across multiple sample rows is legitimate (not a\n * cycle back to an ancestor), so termination on cyclic row data relies on\n * the decrementing `depth` budget alone. When the union of sample keys\n * exceeds `breadth`, the key list is truncated and `additionalProperties` is\n * forced to `true` regardless of `closed` — the same truncation-opens-the-\n * schema rule {@link inferObject} applies, so a closed schema built from a\n * truncated key union never rejects the very rows it was inferred from. A\n * hostile getter on ONE sample row drops that key for ALL rows (the whole\n * per-key value collection is a single {@link attempt}-contained walk) —\n * this is a deliberate all-or-nothing scope, not a per-row partial failure.\n *\n * @param samples - The plain-record samples\n * @param depth - Remaining descent budget\n * @param breadth - The maximum number of properties sampled\n * @param closed - Whether the emitted schema closes to unknown keys\n * @param format - Whether a unanimous string column gains a `format` keyword\n * @param enumOn - Whether a low-cardinality column may emit `enum`\n * @returns The inferred object schema\n *\n * @example\n * ```ts\n * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },\n * // required: ['id'], additionalProperties: false }\n * ```\n */\nexport function inferRecordSamples(\n\tsamples: readonly Record<string, unknown>[],\n\tdepth: number,\n\tbreadth: number,\n\tclosed: boolean,\n\tformat: boolean,\n\tenumOn: boolean,\n): JSONSchema {\n\tif (!(depth > 0)) return {}\n\t// Contain the whole key-enumeration walk — a hostile ownKeys trap on any\n\t// sample must yield an empty key set for this branch, never throw\n\t// (AGENTS §14).\n\tconst keysOutcome = attempt(() => {\n\t\tconst keySet = new Set<string>()\n\t\tfor (const sample of samples) {\n\t\t\tfor (const key of Object.keys(sample)) keySet.add(key)\n\t\t}\n\t\tconst allKeys = [...keySet].sort()\n\t\treturn { keys: allKeys.slice(0, breadth), truncated: allKeys.length > breadth }\n\t})\n\tconst keys = keysOutcome.success ? keysOutcome.value.keys : []\n\tconst truncated = keysOutcome.success && keysOutcome.value.truncated\n\t// Honest typing: a null-prototype accumulator so a key literally named\n\t// '__proto__' becomes an own data key instead of mutating the prototype —\n\t// the same pattern compileGuard / compileParser use (compilers.ts).\n\tconst properties: Record<string, JSONSchema> = Object.create(null)\n\tconst required: string[] = []\n\t// Bounded by depth alone: unlike inferObject/inferArray, this record-\n\t// sample path carries no `visited` WeakSet. A shared reference across\n\t// sample rows is legitimate data (not a cycle back to an ancestor), so\n\t// the decrementing depth budget is the sole termination guarantee here.\n\tfor (const key of keys) {\n\t\t// Contain the per-sample value read — a hostile getter on any sample\n\t\t// must yield an empty value list for this key, never throw\n\t\t// (AGENTS §14).\n\t\tconst valuesOutcome = attempt(() => {\n\t\t\tconst values: unknown[] = []\n\t\t\tfor (const sample of samples) {\n\t\t\t\tconst propertyValue = sample[key]\n\t\t\t\tif (propertyValue !== undefined) values.push(propertyValue)\n\t\t\t}\n\t\t\treturn values\n\t\t})\n\t\tconst values = valuesOutcome.success ? valuesOutcome.value : []\n\t\tif (values.length > 0) {\n\t\t\tproperties[key] = inferSamples(values, depth - 1, breadth, closed, format, enumOn)\n\t\t}\n\t\tif (values.length === samples.length) required.push(key)\n\t}\n\treturn {\n\t\ttype: 'object',\n\t\t...(Object.keys(properties).length > 0 ? { properties } : {}),\n\t\t...(required.length > 0 ? { required } : {}),\n\t\tadditionalProperties: truncated ? true : !closed,\n\t}\n}\n\n/**\n * Infer a `JSONSchema` from a set of example values — the multi-example\n * counterpart of {@link valueToSchema} (e.g. inferring one schema from\n * several database rows).\n *\n * @remarks\n * An empty `samples` array infers the empty accept-anything schema `{}`.\n * When every sample is a plain record, properties/required are unified\n * per-key across all samples (see {@link inferRecordSamples}) — a key\n * required iff present and non-`undefined` in every sample. Otherwise the\n * slot is inferred via {@link inferSamples} (independent {@link valueToSchema}\n * per sample, unified with {@link unifySchemas} — the same de-duplication and\n * `anyOf` ordering {@link inferArray} applies to element schemas). `format`\n * and `enum` (both default `false`) opt a low-cardinality/unanimous-format\n * slot into the corresponding keyword — see {@link inferSamples} for the\n * precedence and the multi-sample format-disabling seam. `maxDepth` /\n * `maxProperties` are sanitized via {@link sanitizeBudget} the same way\n * {@link valueToSchema} sanitizes them — see there for why.\n *\n * @param samples - The example values to infer a schema from\n * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds\n * @returns The inferred `JSONSchema`\n *\n * @example\n * ```ts\n * samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }])\n * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },\n * // required: ['id'], additionalProperties: false }\n * samplesToSchema([]) // {}\n * ```\n */\nexport function samplesToSchema(\n\tsamples: readonly unknown[],\n\toptions?: ValueToSchemaOptions,\n): JSONSchema {\n\tconst maxDepth = sanitizeBudget(options?.maxDepth, INFER_DEPTH_LIMIT)\n\tconst maxProperties = sanitizeBudget(options?.maxProperties, INFER_BREADTH_LIMIT)\n\tconst closed = options?.closed ?? true\n\tconst format = options?.format ?? false\n\tconst enumOn = options?.enum ?? false\n\treturn inferSamples(samples, maxDepth, maxProperties, closed, format, enumOn)\n}\n","import type {\n\tArrayShape,\n\tArrayShapeOptions,\n\tBooleanShape,\n\tBooleanShapeOptions,\n\tContractShape,\n\tJSONSchema,\n\tJSONShape,\n\tJSONShapeOptions,\n\tLiteralShape,\n\tLiteralShapeOptions,\n\tNullableShape,\n\tNullShape,\n\tNullShapeOptions,\n\tNumberShape,\n\tNumberShapeOptions,\n\tObjectShape,\n\tObjectShapeOptions,\n\tOptionalShape,\n\tRawShape,\n\tRecordShapeOptions,\n\tStringShape,\n\tStringShapeOptions,\n\tUnionShape,\n} from './types.js'\n\n// The builders return the parameterized types.ts interfaces (e.g. `ArrayShape<S>`,\n// `ObjectShape<P>`), never inline object literals — the generic parameter keeps\n// `Infer<typeof shape>` exact while the return type still enforces conformance to\n// the shared shape interface.\n\n// Shape builders — pure constructors for the `ContractShape` union. Each returns\n// a plain descriptor; the compilers (compilers.ts) turn it into a guard, parser,\n// schema, and generator. The precise return types (e.g. literal tuples, generic\n// `items` / `properties`) are preserved so `Infer<typeof shape>` stays exact.\n\n// === Primitives\n\n/**\n * Build a string {@link StringShape}.\n *\n * @param options - Optional length (`min` / `max`), `pattern`, and `description`\n * @returns A string shape\n *\n * @example\n * ```ts\n * const name = stringShape({ min: 1, max: 80, description: 'Display name' })\n * ```\n */\nexport function stringShape(options?: StringShapeOptions): StringShape {\n\treturn {\n\t\ttype: 'string',\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tpattern: options?.pattern,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a numeric {@link NumberShape}.\n *\n * @param options - Optional bounds (`min` / `max`), `integer`, and `description`\n * @returns A number shape\n *\n * @example\n * ```ts\n * const age = numberShape({ min: 0, max: 120 })\n * ```\n */\nexport function numberShape(options?: NumberShapeOptions): NumberShape {\n\treturn {\n\t\ttype: 'number',\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tinteger: options?.integer,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an integer {@link NumberShape} — forces `integer: true`.\n *\n * @remarks\n * The emitted JSON Schema uses `\"type\": \"integer\"` and the guard rejects\n * fractional numbers.\n *\n * @param options - Optional bounds and `description` (no `integer` key)\n * @returns An integer number shape\n */\nexport function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape {\n\treturn {\n\t\ttype: 'number',\n\t\tinteger: true,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a {@link BooleanShape}.\n *\n * @param options - Optional `description`\n * @returns A boolean shape\n *\n * @example\n * ```ts\n * const active = booleanShape({ description: 'Whether the record is active' })\n * ```\n */\nexport function booleanShape(options?: BooleanShapeOptions): BooleanShape {\n\treturn {\n\t\ttype: 'boolean',\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build a {@link NullShape}.\n *\n * @param options - Optional `description`\n * @returns A null shape\n *\n * @example\n * ```ts\n * const empty = nullShape()\n * ```\n */\nexport function nullShape(options?: NullShapeOptions): NullShape {\n\treturn { type: 'null', description: options?.description }\n}\n\n/**\n * Build a literal shape from a fixed set of primitive values.\n *\n * @param values - The permitted literals\n * @param options - Optional `description`\n * @returns A literal shape whose `Infer` is the union of `values`\n *\n * @example\n * ```ts\n * const role = literalShape(['admin', 'member', 'guest'])\n * // Infer<typeof role> = 'admin' | 'member' | 'guest'\n *\n * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })\n * ```\n */\nexport function literalShape<const T extends readonly (string | number | boolean)[]>(\n\tvalues: T,\n\toptions?: LiteralShapeOptions,\n): LiteralShape<T> {\n\treturn { type: 'literal', values, description: options?.description }\n}\n\n// === Collections\n\n/**\n * Build an {@link ArrayShape} from an element shape.\n *\n * @param items - The element shape\n * @param options - Optional length bounds and `description`\n * @returns An array shape\n *\n * @example\n * ```ts\n * const tags = arrayShape(stringShape(), { max: 10 })\n * ```\n */\nexport function arrayShape<S extends ContractShape>(\n\titems: S,\n\toptions?: ArrayShapeOptions,\n): ArrayShape<S> {\n\treturn {\n\t\ttype: 'array',\n\t\titems,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an {@link ObjectShape} from a property map.\n *\n * @remarks\n * Wrap any property in {@link optionalShape} to allow its absence. By default\n * the compiled guard rejects unknown keys; pass `additionalProperties` to open\n * the object.\n *\n * @param properties - Map of property names to child shapes\n * @param options - Optional `additionalProperties` and `description`\n * @returns An object shape\n *\n * @example\n * ```ts\n * const user = objectShape({\n * \tname: stringShape({ min: 1 }),\n * \tage: integerShape({ min: 0, max: 120 }),\n * \tbio: optionalShape(stringShape()),\n * })\n * ```\n */\nexport function objectShape<\n\tP extends Readonly<Record<string, ContractShape>>,\n\tconst A extends boolean | ContractShape = false,\n>(properties: P, options?: ObjectShapeOptions<A>): ObjectShape<P, A> {\n\treturn {\n\t\ttype: 'object',\n\t\tproperties,\n\t\tadditionalProperties: options?.additionalProperties,\n\t\tdescription: options?.description,\n\t}\n}\n\n/**\n * Build an open {@link ObjectShape} with no fixed properties — a dictionary.\n *\n * @remarks\n * Every value is validated against `values`; keys are unconstrained. Equivalent\n * to `objectShape({}, { additionalProperties: values })`.\n *\n * @param values - The shape every value must match\n * @param options - Optional `description`\n * @returns An open object shape\n *\n * @example\n * ```ts\n * const bindings = recordShape(numberShape()) // ~ Record<string, number>\n * ```\n */\nexport function recordShape<S extends ContractShape>(\n\tvalues: S,\n\toptions?: RecordShapeOptions,\n): ObjectShape<Record<never, never>, S> {\n\treturn {\n\t\ttype: 'object',\n\t\tproperties: {},\n\t\tadditionalProperties: values,\n\t\tdescription: options?.description,\n\t}\n}\n\n// === Composition\n\n/**\n * Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).\n *\n * @param variants - The candidate shapes; the first match wins at runtime\n * @returns A union shape whose `Infer` is the union of the variants\n *\n * @example\n * ```ts\n * const id = unionShape(stringShape(), integerShape())\n * // Infer<typeof id> = string | number\n * ```\n */\nexport function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V> {\n\treturn { type: 'union', variants }\n}\n\n/**\n * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.\n *\n * @remarks\n * Unlike {@link unionShape} (`anyOf` — at least one variant matches),\n * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:\n *\n * - **Guard**: accepts the value only when exactly one variant's guard\n * accepts it. A value matching two-or-more variants — which would violate\n * the emitted `oneOf` schema — is rejected, even though it would pass\n * {@link unionShape}'s guard.\n * - **Parser**: judged on the RAW input's guard matches only, with NO\n * coercion fallback for an ambiguous input. When exactly one variant's\n * guard accepts the raw value, that variant's parser runs. Zero matches or\n * two-or-more matches both parse to `undefined` — a value ambiguous\n * between variants has no well-defined coercion target.\n *\n * Prefer {@link unionShape} when a value may legitimately satisfy more than\n * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer\n * `oneOfShape` when overlap between variants indicates malformed input that\n * must be rejected.\n *\n * @param variants - The candidate shapes\n * @returns A union shape with `mode: 'oneOf'`\n *\n * @example\n * ```ts\n * const id = oneOfShape(numberShape(), integerShape())\n * // 3 fails — matches both numberShape and integerShape\n * // 3.5 passes — matches numberShape only\n * ```\n */\nexport function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V> {\n\treturn { type: 'union', variants, mode: 'oneOf' }\n}\n\n/**\n * Wrap a shape so it may be absent (`undefined`).\n *\n * @remarks\n * As an {@link objectShape} property, the field becomes a true optional property\n * in the inferred type.\n *\n * @param inner - The wrapped shape\n * @returns An optional shape\n */\nexport function optionalShape<S extends ContractShape>(inner: S): OptionalShape<S> {\n\treturn { type: 'optional', inner }\n}\n\n/**\n * Wrap a shape so it may be `null`.\n *\n * @param inner - The wrapped shape\n * @returns A nullable shape\n *\n * @example\n * ```ts\n * const bio = nullableShape(stringShape())\n * // Infer<typeof bio> = string | null\n * ```\n */\nexport function nullableShape<S extends ContractShape>(inner: S): NullableShape<S> {\n\treturn { type: 'nullable', inner }\n}\n\n// === Escape hatch\n\n/**\n * Build a {@link JSONShape}.\n *\n * @remarks\n * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary\n * schema fragment and accepts anything at runtime, while `jsonShape` validates\n * that a value is real JSON (via {@link isJSONValue}).\n *\n * @param options - Optional `description`\n * @returns A JSON passthrough shape\n *\n * @example\n * ```ts\n * const payload = jsonShape({ description: 'Arbitrary JSON payload' })\n * ```\n */\nexport function jsonShape(options?: JSONShapeOptions): JSONShape {\n\treturn { type: 'json', description: options?.description }\n}\n\n/**\n * Build a {@link RawShape} from a JSON Schema fragment.\n *\n * @remarks\n * For values the shape DSL can't express. The compiled guard accepts any value;\n * the parser passes it through; the schema is emitted verbatim.\n *\n * @param schema - The JSON Schema fragment to embed\n * @returns A raw shape\n *\n * @example\n * ```ts\n * const custom = rawShape({ type: 'string', format: 'uuid' })\n * ```\n */\nexport function rawShape(schema: JSONSchema): RawShape {\n\treturn { type: 'raw', schema }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,oBAA+C,OAAO,OAAO;CACzE;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;;AAcD,IAAa,cAAc;;;;;;;;;AAU3B,IAAa,gBAAgB;;;;;;;;;;;AAc7B,IAAa,oBAAoB;;;;;;;;;;AAWjC,IAAa,sBAAsB;;;;;;;;;;;;AAanC,IAAa,mBAAmB;;;;;;;;;;;;;AAchC,IAAa,oBAAoB;;;;;;;;;;AAWjC,IAAa,kBAAsE,OAAO,OAAO;CAChG,MAAM;CACN,OAAO;CACP,KAAK;AACN,CAAC;;;;;;;;;;;ACvFD,SAAgB,OAAO,OAA+B;CACrD,OAAO,UAAU;AAClB;;;;;;;;;AAUA,SAAgB,YAAY,OAAoC;CAC/D,OAAO,UAAU,KAAA;AAClB;;;;;;;;;;AAWA,SAAgB,UAAa,OAAyC;CACrE,OAAO,UAAU,QAAQ,UAAU,KAAA;AACpC;;;;;;;;;AAUA,SAAgB,SAAS,OAAiC;CACzD,OAAO,OAAO,UAAU;AACzB;;;;;;;;;;;;;;AAeA,SAAgB,SAAS,OAAiC;CACzD,OAAO,OAAO,UAAU;AACzB;;;;;;;;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