@orkestrel/contract 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +46 -0
- package/dist/src/core/combinators.d.ts +384 -0
- package/dist/src/core/compilers.d.ts +119 -0
- package/dist/src/core/constants.d.ts +20 -0
- package/dist/src/core/helpers.d.ts +112 -0
- package/dist/src/core/index.d.ts +8 -0
- package/dist/src/core/index.js +2026 -0
- package/dist/src/core/index.js.map +1 -0
- package/dist/src/core/parsers.d.ts +230 -0
- package/dist/src/core/shapers.d.ts +178 -0
- package/dist/src/core/types.d.ts +372 -0
- package/dist/src/core/validators.d.ts +250 -0
- package/package.json +69 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","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. Most guards here are a single structural test with no user callbacks,\n// so totality is immediate. The reflective guards — those that probe a\n// property through `Reflect.get` or walk a structure (`isPromiseLike`,\n// `isIterable`, `isAsyncIterable`, `isJSONValue`, `isRecord`) can hit a hostile\n// getter or a revoked `Proxy` that throws mid-probe, so totality is NOT\n// automatic for them — each contains its probe/walk in `attempt` (see\n// ./helpers.js) and returns `false` on a caught throw.\n\n// === Primitive guards\n\n/** Determine whether a value is `null`. */\nexport function isNull(value: unknown): value is null {\n\treturn value === null\n}\n\n/** Determine whether a value is `undefined`. */\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`). */\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. */\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 */\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`). */\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). */\nexport function isInteger(value: unknown): value is number {\n\treturn Number.isInteger(value)\n}\n\n/** Determine whether a value is a boolean. */\nexport function isBoolean(value: unknown): value is boolean {\n\treturn typeof value === 'boolean'\n}\n\n/** Determine whether a value is exactly `true`. */\nexport function isTrue(value: unknown): value is true {\n\treturn value === true\n}\n\n/** Determine whether a value is exactly `false`. */\nexport function isFalse(value: unknown): value is false {\n\treturn value === false\n}\n\n/** Determine whether a value is a bigint. */\nexport function isBigInt(value: unknown): value is bigint {\n\treturn typeof value === 'bigint'\n}\n\n/** Determine whether a value is a symbol. */\nexport function isSymbol(value: unknown): value is symbol {\n\treturn typeof value === 'symbol'\n}\n\n/** Determine whether a value is callable. */\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`. */\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`). */\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`. */\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/** Determine whether a value is a `Date`. */\nexport function isDate(value: unknown): value is Date {\n\treturn value instanceof Date\n}\n\n/** Determine whether a value is a `RegExp`. */\nexport function isRegExp(value: unknown): value is RegExp {\n\treturn value instanceof RegExp\n}\n\n/** Determine whether a value is an `Error`. */\nexport function isError(value: unknown): value is Error {\n\treturn value instanceof Error\n}\n\n/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable). */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n\treturn value instanceof 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 */\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`. */\nexport function isArrayBuffer(value: unknown): value is ArrayBuffer {\n\treturn value instanceof 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 */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n\treturn typeof SharedArrayBuffer !== 'undefined' && value instanceof 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 */\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`). */\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 */\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 */\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`. */\nexport function isMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V> {\n\treturn value instanceof Map\n}\n\n/** Determine whether a value is a `Set`. */\nexport function isSet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn value instanceof Set\n}\n\n/** Determine whether a value is a `WeakMap`. */\nexport function isWeakMap(value: unknown): value is WeakMap<object, unknown> {\n\treturn value instanceof WeakMap\n}\n\n/** Determine whether a value is a `WeakSet`. */\nexport function isWeakSet(value: unknown): value is WeakSet<object> {\n\treturn value instanceof WeakSet\n}\n\n// === Array & typed-array guards\n\n/** Determine whether a value is an array. */\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`. */\nexport function isDataView(value: unknown): value is DataView<ArrayBufferLike> {\n\treturn value instanceof DataView\n}\n\n/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`). */\nexport function isArrayBufferView(value: unknown): value is ArrayBufferView {\n\treturn ArrayBuffer.isView(value)\n}\n\n/** Determine whether a value is an `Int8Array`. */\nexport function isInt8Array(value: unknown): value is Int8Array {\n\treturn value instanceof Int8Array\n}\n\n/** Determine whether a value is a `Uint8Array`. */\nexport function isUint8Array(value: unknown): value is Uint8Array {\n\treturn value instanceof Uint8Array\n}\n\n/** Determine whether a value is a `Uint8ClampedArray`. */\nexport function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray {\n\treturn value instanceof Uint8ClampedArray\n}\n\n/** Determine whether a value is an `Int16Array`. */\nexport function isInt16Array(value: unknown): value is Int16Array {\n\treturn value instanceof Int16Array\n}\n\n/** Determine whether a value is a `Uint16Array`. */\nexport function isUint16Array(value: unknown): value is Uint16Array {\n\treturn value instanceof Uint16Array\n}\n\n/** Determine whether a value is an `Int32Array`. */\nexport function isInt32Array(value: unknown): value is Int32Array {\n\treturn value instanceof Int32Array\n}\n\n/** Determine whether a value is a `Uint32Array`. */\nexport function isUint32Array(value: unknown): value is Uint32Array {\n\treturn value instanceof Uint32Array\n}\n\n/** Determine whether a value is a `Float32Array`. */\nexport function isFloat32Array(value: unknown): value is Float32Array {\n\treturn value instanceof Float32Array\n}\n\n/** Determine whether a value is a `Float64Array`. */\nexport function isFloat64Array(value: unknown): value is Float64Array {\n\treturn value instanceof 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 */\nexport function isBigInt64Array(value: unknown): value is BigInt64Array {\n\treturn typeof BigInt64Array !== 'undefined' && value instanceof 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 */\nexport function isBigUint64Array(value: unknown): value is BigUint64Array {\n\treturn typeof BigUint64Array !== 'undefined' && value instanceof BigUint64Array\n}\n\n// === Emptiness guards\n\n/** Determine whether a value is the empty string `''`. */\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. */\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). */\nexport function isEmptyObject(value: unknown): value is Record<string | symbol, never> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\treturn Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0\n}\n\n/** Determine whether a value is an empty `Map`. */\nexport function isEmptyMap(value: unknown): value is ReadonlyMap<never, never> {\n\treturn value instanceof Map && value.size === 0\n}\n\n/** Determine whether a value is an empty `Set`. */\nexport function isEmptySet(value: unknown): value is ReadonlySet<never> {\n\treturn value instanceof Set && value.size === 0\n}\n\n/** Determine whether a value is a non-empty string (at least one character). */\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). */\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). */\nexport function isNonEmptyObject(value: unknown): value is Record<string | symbol, unknown> {\n\tif (!isRecord(value)) {\n\t\treturn false\n\t}\n\treturn Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0\n}\n\n/** Determine whether a value is a non-empty `Map` (at least one entry). */\nexport function isNonEmptyMap<K = unknown, V = unknown>(\n\tvalue: unknown,\n): value is ReadonlyMap<K, V> {\n\treturn value instanceof Map && value.size > 0\n}\n\n/** Determine whether a value is a non-empty `Set` (at least one element). */\nexport function isNonEmptySet<T = unknown>(value: unknown): value is ReadonlySet<T> {\n\treturn value instanceof Set && value.size > 0\n}\n\n// === Function guards\n\n/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`). */\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 */\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*`). */\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*`). */\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. */\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. */\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. */\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 */\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\tAnyConstructor,\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\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>(ctor: C): Guard<InstanceType<C & AnyConstructor<object>>> {\n\treturn (value: unknown): value is InstanceType<C & AnyConstructor<object>> =>\n\t\tisConstructor(ctor) && isObject(value) && value instanceof 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<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] | undefined }>>\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] | undefined }>\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] | undefined }>\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// === 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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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(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\treturn unionOf(...shape.variants.map((variant) => compileGuard(variant)))\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 */\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\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 */\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 */\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 */\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 */\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<P extends Readonly<Record<string, ContractShape>>>(\n\tproperties: P,\n\toptions?: ObjectShapeOptions,\n): ObjectShape<P> {\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 {\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 * Runtime behavior is identical to {@link unionShape} — only the emitted schema\n * keyword differs (`oneOf` vs `anyOf`).\n *\n * @param variants - The candidate shapes\n * @returns A union shape with `mode: 'oneOf'`\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 */\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 */\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 */\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;;;;ACTD,SAAgB,OAAO,OAA+B;CACrD,OAAO,UAAU;AAClB;;AAGA,SAAgB,YAAY,OAAoC;CAC/D,OAAO,UAAU,KAAA;AAClB;;AAGA,SAAgB,UAAa,OAAyC;CACrE,OAAO,UAAU,QAAQ,UAAU,KAAA;AACpC;;AAGA,SAAgB,SAAS,OAAiC;CACzD,OAAO,OAAO,UAAU;AACzB;;;;;;;AAQA,SAAgB,SAAS,OAAiC;CACzD,OAAO,OAAO,UAAU;AACzB;;AAGA,SAAgB,eAAe,OAAiC;CAC/D,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AAC1D;;AAGA,SAAgB,UAAU,OAAiC;CAC1D,OAAO,OAAO,UAAU,KAAK;AAC9B;;AAGA,SAAgB,UAAU,OAAkC;CAC3D,OAAO,OAAO,UAAU;AACzB;;AAGA,SAAgB,OAAO,OAA+B;CACrD,OAAO,UAAU;AAClB;;AAGA,SAAgB,QAAQ,OAAgC;CACvD,OAAO,UAAU;AAClB;;AAGA,SAAgB,SAAS,OAAiC;CACzD,OAAO,OAAO,UAAU;AACzB;;AAGA,SAAgB,SAAS,OAAiC;CACzD,OAAO,OAAO,UAAU;AACzB;;AAGA,SAAgB,WAAW,OAAsC;CAChE,OAAO,OAAO,UAAU;AACzB;;AAGA,SAAgB,iBAAiB,OAAwC;CACxE,OAAO,UAAU,QAAQ,SAAS,KAAK;AACxC;;AAGA,SAAgB,iBAAiB,OAAwC;CACxE,OAAO,UAAU,QAAQ,SAAS,KAAK;AACxC;;AAGA,SAAgB,kBAAkB,OAAyC;CAC1E,OAAO,UAAU,QAAQ,UAAU,KAAK;AACzC;;AAaA,SAAgB,OAAO,OAA+B;CACrD,O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;EAAE,MAAM;EAAW;EAAQ,aAAa,SAAS;CAAY;AACrE;;;;;;;;;;;;;AAgBA,SAAgB,WACf,OACA,SACgB;CAChB,OAAO;EACN,MAAM;EACN;EACA,KAAK,SAAS;EACd,KAAK,SAAS;EACd,aAAa,SAAS;CACvB;AACD;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,YACf,YACA,SACiB;CACjB,OAAO;EACN,MAAM;EACN;EACA,sBAAsB,SAAS;EAC/B,aAAa,SAAS;CACvB;AACD;;;;;;;;;;;;;;;;;AAkBA,SAAgB,YACf,QACA,SACc;CACd,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;;;;;;;;;;;AAYA,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;;;;;;;AAQA,SAAgB,cAAuC,OAA4B;CAClF,OAAO;EAAE,MAAM;EAAY;CAAM;AAClC;;;;;;;;;;;;AAeA,SAAgB,UAAU,SAAuC;CAChE,OAAO;EAAE,MAAM;EAAQ,aAAa,SAAS;CAAY;AAC1D;;;;;;;;;;;AAYA,SAAgB,SAAS,QAA8B;CACtD,OAAO;EAAE,MAAM;EAAO;CAAO;AAC9B"}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import type { Guard, JSONValue } from './types.js';
|
|
2
|
+
import type { FieldPath } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Parse an unknown value to a string.
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* A string is returned unchanged; a finite number is coerced to its decimal
|
|
8
|
+
* string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.
|
|
9
|
+
*
|
|
10
|
+
* @param value - The value to parse
|
|
11
|
+
* @returns A string, or `undefined`
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseString(value: unknown): string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Parse an unknown value to a finite number.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* A finite number is returned unchanged; a non-blank numeric string is parsed
|
|
19
|
+
* via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every
|
|
20
|
+
* other type → `undefined`.
|
|
21
|
+
*
|
|
22
|
+
* @param value - The value to parse
|
|
23
|
+
* @returns A finite number, or `undefined`
|
|
24
|
+
*/
|
|
25
|
+
export declare function parseNumber(value: unknown): number | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Parse an unknown value to a finite integer.
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* Accepts whatever {@link parseNumber} accepts, then requires the result to have
|
|
31
|
+
* no fractional part. `3.14` / `'3.14'` → `undefined`.
|
|
32
|
+
*
|
|
33
|
+
* @param value - The value to parse
|
|
34
|
+
* @returns A finite integer, or `undefined`
|
|
35
|
+
*/
|
|
36
|
+
export declare function parseInteger(value: unknown): number | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Parse an unknown value to a boolean.
|
|
39
|
+
*
|
|
40
|
+
* @remarks
|
|
41
|
+
* A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /
|
|
42
|
+
* `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything
|
|
43
|
+
* else → `undefined`.
|
|
44
|
+
*
|
|
45
|
+
* @param value - The value to parse
|
|
46
|
+
* @returns A boolean, or `undefined`
|
|
47
|
+
*/
|
|
48
|
+
export declare function parseBoolean(value: unknown): boolean | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Parse an unknown value to `null`.
|
|
51
|
+
*
|
|
52
|
+
* @remarks
|
|
53
|
+
* A successful parse returns `null` itself — distinct from the `undefined`
|
|
54
|
+
* failure sentinel every other parser in this file uses. Only `null` passes;
|
|
55
|
+
* every other value (including `undefined`) → `undefined`.
|
|
56
|
+
*
|
|
57
|
+
* @param value - The value to parse
|
|
58
|
+
* @returns `null` on a successful parse, or `undefined`
|
|
59
|
+
*/
|
|
60
|
+
export declare function parseNull(value: unknown): null | undefined;
|
|
61
|
+
/**
|
|
62
|
+
* Parse an unknown value to a plain record — the input reference, never cloned.
|
|
63
|
+
*
|
|
64
|
+
* @param value - The value to parse
|
|
65
|
+
* @returns The record, or `undefined`
|
|
66
|
+
*/
|
|
67
|
+
export declare function parseRecord(value: unknown): Record<string, unknown> | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* Parse an unknown value to an array — the input reference, never cloned —
|
|
70
|
+
* optionally guarding every element.
|
|
71
|
+
*
|
|
72
|
+
* @remarks
|
|
73
|
+
* Without a `guard`, element types are NOT verified; let `T` default to
|
|
74
|
+
* `unknown` rather than asserting a specific element type.
|
|
75
|
+
*
|
|
76
|
+
* @param value - The value to parse
|
|
77
|
+
* @param guard - Optional element guard
|
|
78
|
+
* @returns The array, or `undefined`
|
|
79
|
+
*/
|
|
80
|
+
export declare function parseArray<T = unknown>(value: unknown, guard?: Guard<T>): readonly T[] | undefined;
|
|
81
|
+
/**
|
|
82
|
+
* Parse an unknown value to a cycle-safe JSON value — the input reference,
|
|
83
|
+
* never cloned.
|
|
84
|
+
*
|
|
85
|
+
* @remarks
|
|
86
|
+
* Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it
|
|
87
|
+
* walks the entire tree via {@link isJSONValue} rather than checking only the
|
|
88
|
+
* top-level shape. That walk is cycle-safe and total (never throws) because
|
|
89
|
+
* `isJSONValue` runs its own probe inside a guard, so an adversarial
|
|
90
|
+
* structure (a cycle, a hostile getter) yields `undefined` instead of hanging
|
|
91
|
+
* or throwing.
|
|
92
|
+
*
|
|
93
|
+
* @param value - The value to parse
|
|
94
|
+
* @returns The value, or `undefined` when it is not a valid JSON value
|
|
95
|
+
*/
|
|
96
|
+
export declare function parseJSONValue(value: unknown): JSONValue | undefined;
|
|
97
|
+
/**
|
|
98
|
+
* Parse an unknown value as one of the allowed literal primitives.
|
|
99
|
+
*
|
|
100
|
+
* @remarks
|
|
101
|
+
* Pairs with {@link literalOf} — both match by `Object.is`, so the
|
|
102
|
+
* `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
|
|
103
|
+
* (string, number, or boolean), not only strings. Matching is identity, never
|
|
104
|
+
* cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
|
|
105
|
+
*
|
|
106
|
+
* @param value - The value to parse
|
|
107
|
+
* @param allowed - The permitted literal values
|
|
108
|
+
* @returns The matched literal (by identity), or `undefined`
|
|
109
|
+
*/
|
|
110
|
+
export declare function parseEnum<const T extends string | number | boolean>(value: unknown, allowed: readonly T[]): T | undefined;
|
|
111
|
+
/**
|
|
112
|
+
* Read and parse a string field from a record by key or nested key path.
|
|
113
|
+
*
|
|
114
|
+
* @param record - The source record
|
|
115
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
116
|
+
* @returns A string, or `undefined`
|
|
117
|
+
*/
|
|
118
|
+
export declare function parseStringField(record: Record<string, unknown>, path: FieldPath): string | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* Read and parse a finite-number field from a record by key or nested key path.
|
|
121
|
+
*
|
|
122
|
+
* @param record - The source record
|
|
123
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
124
|
+
* @returns A finite number, or `undefined`
|
|
125
|
+
*/
|
|
126
|
+
export declare function parseNumberField(record: Record<string, unknown>, path: FieldPath): number | undefined;
|
|
127
|
+
/**
|
|
128
|
+
* Read and parse a finite-integer field from a record by key or nested key path.
|
|
129
|
+
*
|
|
130
|
+
* @param record - The source record
|
|
131
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
132
|
+
* @returns A finite integer, or `undefined`
|
|
133
|
+
*/
|
|
134
|
+
export declare function parseIntegerField(record: Record<string, unknown>, path: FieldPath): number | undefined;
|
|
135
|
+
/**
|
|
136
|
+
* Read and parse a boolean field from a record by key or nested key path.
|
|
137
|
+
*
|
|
138
|
+
* @param record - The source record
|
|
139
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
140
|
+
* @returns A boolean, or `undefined`
|
|
141
|
+
*/
|
|
142
|
+
export declare function parseBooleanField(record: Record<string, unknown>, path: FieldPath): boolean | undefined;
|
|
143
|
+
/**
|
|
144
|
+
* Read and parse a `null` field from a record by key or nested key path.
|
|
145
|
+
*
|
|
146
|
+
* @remarks
|
|
147
|
+
* A successful parse returns `null` itself — distinct from the `undefined`
|
|
148
|
+
* failure sentinel, which also covers a missing field.
|
|
149
|
+
*
|
|
150
|
+
* @param record - The source record
|
|
151
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
152
|
+
* @returns `null` on a successful parse, or `undefined`
|
|
153
|
+
*/
|
|
154
|
+
export declare function parseNullField(record: Record<string, unknown>, path: FieldPath): null | undefined;
|
|
155
|
+
/**
|
|
156
|
+
* Read and parse a nested record field from a record by key or nested key path.
|
|
157
|
+
*
|
|
158
|
+
* @param record - The source record
|
|
159
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
160
|
+
* @returns A plain record, or `undefined`
|
|
161
|
+
*/
|
|
162
|
+
export declare function parseRecordField(record: Record<string, unknown>, path: FieldPath): Record<string, unknown> | undefined;
|
|
163
|
+
/**
|
|
164
|
+
* Read and parse an array field from a record by key or nested key path,
|
|
165
|
+
* optionally guarding elements.
|
|
166
|
+
*
|
|
167
|
+
* @param record - The source record
|
|
168
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
169
|
+
* @param guard - Optional element guard
|
|
170
|
+
* @returns An array, or `undefined`
|
|
171
|
+
*/
|
|
172
|
+
export declare function parseArrayField<T = unknown>(record: Record<string, unknown>, path: FieldPath, guard?: Guard<T>): readonly T[] | undefined;
|
|
173
|
+
/**
|
|
174
|
+
* Read and parse an enum field from a record by key or nested key path.
|
|
175
|
+
*
|
|
176
|
+
* @param record - The source record
|
|
177
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
178
|
+
* @param allowed - The permitted literal values
|
|
179
|
+
* @returns The matched literal, or `undefined`
|
|
180
|
+
*/
|
|
181
|
+
export declare function parseEnumField<const T extends string | number | boolean>(record: Record<string, unknown>, path: FieldPath, allowed: readonly T[]): T | undefined;
|
|
182
|
+
/**
|
|
183
|
+
* Read and parse a JSON-value field from a record by key or nested key path.
|
|
184
|
+
*
|
|
185
|
+
* @remarks
|
|
186
|
+
* Deep-gates the field's whole subtree via {@link parseJSONValue} — see that
|
|
187
|
+
* function's remarks for why this differs from the shallow
|
|
188
|
+
* {@link parseRecordField} / {@link parseArrayField}.
|
|
189
|
+
*
|
|
190
|
+
* @param record - The source record
|
|
191
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
192
|
+
* @returns The value, or `undefined`
|
|
193
|
+
*/
|
|
194
|
+
export declare function parseJSONValueField(record: Record<string, unknown>, path: FieldPath): JSONValue | undefined;
|
|
195
|
+
/**
|
|
196
|
+
* Parse a JSON string, returning `undefined` instead of throwing.
|
|
197
|
+
*
|
|
198
|
+
* @remarks
|
|
199
|
+
* The safe boundary for untrusted JSON text: a malformed string yields
|
|
200
|
+
* `undefined`, never an exception. Returns `unknown` — a successful parse proves
|
|
201
|
+
* nothing about shape, so narrow the result with a guard (or use
|
|
202
|
+
* {@link parseJSONAs}). A large document is not walked here; parsing is shallow
|
|
203
|
+
* and lazy validation is the caller's to compose.
|
|
204
|
+
*
|
|
205
|
+
* @param value - The JSON string to parse
|
|
206
|
+
* @returns The parsed value, or `undefined` when `value` is not valid JSON
|
|
207
|
+
*/
|
|
208
|
+
export declare function parseJSON(value: string): unknown;
|
|
209
|
+
/**
|
|
210
|
+
* Parse a JSON string and validate the result against a guard.
|
|
211
|
+
*
|
|
212
|
+
* @remarks
|
|
213
|
+
* The lazy, safe path from an untrusted string to a typed `T`: parse, then check
|
|
214
|
+
* the parsed value with the guard you bring — typically one composed from the
|
|
215
|
+
* combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is
|
|
216
|
+
* validated, so a large document is never walked in full unless the guard does.
|
|
217
|
+
*
|
|
218
|
+
* @param value - The JSON string to parse
|
|
219
|
+
* @param guard - The guard for the expected shape
|
|
220
|
+
* @returns The parsed value when it satisfies `guard`, otherwise `undefined`
|
|
221
|
+
*
|
|
222
|
+
* @example
|
|
223
|
+
* ```ts
|
|
224
|
+
* const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })
|
|
225
|
+
* parseJSONAs('{"host":"localhost","tags":["a"]}', isConfig) // { host: 'localhost', tags: ['a'] }
|
|
226
|
+
* parseJSONAs('{"host":"localhost"}', isConfig) // undefined — guard fails
|
|
227
|
+
* parseJSONAs('not json', isConfig) // undefined — never throws
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
export declare function parseJSONAs<T>(value: string, guard: Guard<T>): T | undefined;
|