@orkestrel/database 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 +36 -0
- package/dist/src/core/Clause.d.ts +30 -0
- package/dist/src/core/Cursor.d.ts +21 -0
- package/dist/src/core/Database.d.ts +80 -0
- package/dist/src/core/Query.d.ts +47 -0
- package/dist/src/core/Table.d.ts +69 -0
- package/dist/src/core/constants.d.ts +22 -0
- package/dist/src/core/drivers/MemoryDriver.d.ts +94 -0
- package/dist/src/core/errors.d.ts +38 -0
- package/dist/src/core/factories.d.ts +43 -0
- package/dist/src/core/helpers.d.ts +383 -0
- package/dist/src/core/index.d.ts +11 -0
- package/dist/src/core/index.js +3364 -0
- package/dist/src/core/index.js.map +1 -0
- package/dist/src/core/types.d.ts +739 -0
- package/dist/src/server/compilers.d.ts +169 -0
- package/dist/src/server/drivers/JSONDriver.d.ts +106 -0
- package/dist/src/server/factories.d.ts +31 -0
- package/dist/src/server/helpers.d.ts +222 -0
- package/dist/src/server/index.cjs +1014 -0
- package/dist/src/server/index.cjs.map +1 -0
- package/dist/src/server/index.d.ts +5 -0
- package/dist/src/server/types.d.ts +36 -0
- package/package.json +84 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#path","#memory","#schema","#load","#deferring","#flush","#meta","#chain","#serialize","#flushCount"],"sources":["../../../node_modules/@orkestrel/contract/dist/src/core/index.js","../../../src/server/helpers.ts","../../../src/server/compilers.ts","../../../src/server/drivers/JSONDriver.ts","../../../src/server/factories.ts"],"sourcesContent":["//#region src/core/constants.ts\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*/\nvar JSON_SCHEMA_TYPES = 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//#endregion\n//#region src/core/validators.ts\n/** Determine whether a value is `null`. */\nfunction isNull(value) {\n\treturn value === null;\n}\n/** Determine whether a value is `undefined`. */\nfunction isUndefined(value) {\n\treturn value === void 0;\n}\n/** Determine whether a value is defined (neither `null` nor `undefined`). */\nfunction isDefined(value) {\n\treturn value !== null && value !== void 0;\n}\n/** Determine whether a value is a string. */\nfunction isString(value) {\n\treturn typeof value === \"string\";\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*/\nfunction isNumber(value) {\n\treturn typeof value === \"number\";\n}\n/** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`). */\nfunction isFiniteNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n/** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers). */\nfunction isInteger(value) {\n\treturn Number.isInteger(value);\n}\n/** Determine whether a value is a boolean. */\nfunction isBoolean(value) {\n\treturn typeof value === \"boolean\";\n}\n/** Determine whether a value is exactly `true`. */\nfunction isTrue(value) {\n\treturn value === true;\n}\n/** Determine whether a value is exactly `false`. */\nfunction isFalse(value) {\n\treturn value === false;\n}\n/** Determine whether a value is a bigint. */\nfunction isBigInt(value) {\n\treturn typeof value === \"bigint\";\n}\n/** Determine whether a value is a symbol. */\nfunction isSymbol(value) {\n\treturn typeof value === \"symbol\";\n}\n/** Determine whether a value is callable. */\nfunction isFunction(value) {\n\treturn typeof value === \"function\";\n}\n/** Determine whether a value is a string or `null`. */\nfunction isNullableString(value) {\n\treturn value === null || isString(value);\n}\n/** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`). */\nfunction isNullableNumber(value) {\n\treturn value === null || isNumber(value);\n}\n/** Determine whether a value is a boolean or `null`. */\nfunction isNullableBoolean(value) {\n\treturn value === null || isBoolean(value);\n}\n/** Determine whether a value is a `Date`. */\nfunction isDate(value) {\n\treturn value instanceof Date;\n}\n/** Determine whether a value is a `RegExp`. */\nfunction isRegExp(value) {\n\treturn value instanceof RegExp;\n}\n/** Determine whether a value is an `Error`. */\nfunction isError(value) {\n\treturn value instanceof Error;\n}\n/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable). */\nfunction isPromise(value) {\n\treturn value instanceof Promise;\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*/\nfunction isPromiseLike(value) {\n\tif (!isObject(value)) return false;\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/** Determine whether a value is an `ArrayBuffer`. */\nfunction isArrayBuffer(value) {\n\treturn value instanceof ArrayBuffer;\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*/\nfunction isSharedArrayBuffer(value) {\n\treturn typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer;\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*/\nfunction isIterable(value) {\n\tif (isString(value)) return true;\n\tif (!isObject(value)) return false;\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.iterator)));\n\treturn outcome.success && outcome.value;\n}\n/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`). */\nfunction isAsyncIterable(value) {\n\tif (!isObject(value)) return false;\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)));\n\treturn outcome.success && outcome.value;\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*/\nfunction isObject(value) {\n\treturn typeof value === \"object\" && value !== null;\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*/\nfunction isRecord(value) {\n\tconst outcome = attempt(() => {\n\t\tif (!isObject(value) || isArray(value)) return false;\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/** Determine whether a value is a `Map`. */\nfunction isMap(value) {\n\treturn value instanceof Map;\n}\n/** Determine whether a value is a `Set`. */\nfunction isSet(value) {\n\treturn value instanceof Set;\n}\n/** Determine whether a value is a `WeakMap`. */\nfunction isWeakMap(value) {\n\treturn value instanceof WeakMap;\n}\n/** Determine whether a value is a `WeakSet`. */\nfunction isWeakSet(value) {\n\treturn value instanceof WeakSet;\n}\n/** Determine whether a value is an array. */\nfunction isArray(value) {\n\treturn Array.isArray(value);\n}\n/** Determine whether a value is a `DataView`. */\nfunction isDataView(value) {\n\treturn value instanceof DataView;\n}\n/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`). */\nfunction isArrayBufferView(value) {\n\treturn ArrayBuffer.isView(value);\n}\n/** Determine whether a value is an `Int8Array`. */\nfunction isInt8Array(value) {\n\treturn value instanceof Int8Array;\n}\n/** Determine whether a value is a `Uint8Array`. */\nfunction isUint8Array(value) {\n\treturn value instanceof Uint8Array;\n}\n/** Determine whether a value is a `Uint8ClampedArray`. */\nfunction isUint8ClampedArray(value) {\n\treturn value instanceof Uint8ClampedArray;\n}\n/** Determine whether a value is an `Int16Array`. */\nfunction isInt16Array(value) {\n\treturn value instanceof Int16Array;\n}\n/** Determine whether a value is a `Uint16Array`. */\nfunction isUint16Array(value) {\n\treturn value instanceof Uint16Array;\n}\n/** Determine whether a value is an `Int32Array`. */\nfunction isInt32Array(value) {\n\treturn value instanceof Int32Array;\n}\n/** Determine whether a value is a `Uint32Array`. */\nfunction isUint32Array(value) {\n\treturn value instanceof Uint32Array;\n}\n/** Determine whether a value is a `Float32Array`. */\nfunction isFloat32Array(value) {\n\treturn value instanceof Float32Array;\n}\n/** Determine whether a value is a `Float64Array`. */\nfunction isFloat64Array(value) {\n\treturn value instanceof Float64Array;\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*/\nfunction isBigInt64Array(value) {\n\treturn typeof BigInt64Array !== \"undefined\" && value instanceof BigInt64Array;\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*/\nfunction isBigUint64Array(value) {\n\treturn typeof BigUint64Array !== \"undefined\" && value instanceof BigUint64Array;\n}\n/** Determine whether a value is the empty string `''`. */\nfunction isEmptyString(value) {\n\treturn isString(value) && value.length === 0;\n}\n/** Determine whether a value is an empty array. */\nfunction isEmptyArray(value) {\n\treturn isArray(value) && value.length === 0;\n}\n/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys). */\nfunction isEmptyObject(value) {\n\tif (!isRecord(value)) return false;\n\treturn Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0;\n}\n/** Determine whether a value is an empty `Map`. */\nfunction isEmptyMap(value) {\n\treturn value instanceof Map && value.size === 0;\n}\n/** Determine whether a value is an empty `Set`. */\nfunction isEmptySet(value) {\n\treturn value instanceof Set && value.size === 0;\n}\n/** Determine whether a value is a non-empty string (at least one character). */\nfunction isNonEmptyString(value) {\n\treturn isString(value) && value.length > 0;\n}\n/** Determine whether a value is a non-empty array (at least one element). */\nfunction isNonEmptyArray(value) {\n\treturn isArray(value) && value.length > 0;\n}\n/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key). */\nfunction isNonEmptyObject(value) {\n\tif (!isRecord(value)) return false;\n\treturn Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0;\n}\n/** Determine whether a value is a non-empty `Map` (at least one entry). */\nfunction isNonEmptyMap(value) {\n\treturn value instanceof Map && value.size > 0;\n}\n/** Determine whether a value is a non-empty `Set` (at least one element). */\nfunction isNonEmptySet(value) {\n\treturn value instanceof Set && value.size > 0;\n}\n/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`). */\nfunction isZeroArg(value) {\n\treturn isFunction(value) && value.length === 0;\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*/\nfunction isAsyncFunction(value) {\n\treturn isFunction(value) && value.constructor?.name === \"AsyncFunction\";\n}\n/** Determine whether a value is a generator function (`function*`). */\nfunction isGeneratorFunction(value) {\n\treturn isFunction(value) && value.constructor?.name === \"GeneratorFunction\";\n}\n/** Determine whether a value is an async generator function (`async function*`). */\nfunction isAsyncGeneratorFunction(value) {\n\treturn isFunction(value) && value.constructor?.name === \"AsyncGeneratorFunction\";\n}\n/** Determine whether a value is a zero-argument async function. */\nfunction isZeroArgAsync(value) {\n\treturn isZeroArg(value) && isAsyncFunction(value);\n}\n/** Determine whether a value is a zero-argument generator function. */\nfunction isZeroArgGenerator(value) {\n\treturn isZeroArg(value) && isGeneratorFunction(value);\n}\n/** Determine whether a value is a zero-argument async generator function. */\nfunction isZeroArgAsyncGenerator(value) {\n\treturn isZeroArg(value) && isAsyncGeneratorFunction(value);\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*/\nfunction isConstructor(value) {\n\tif (!isFunction(value)) return false;\n\ttry {\n\t\tReflect.construct(String, [], value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\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*/\nfunction isJSONValue(value) {\n\tconst ancestors = /* @__PURE__ */ new WeakSet();\n\tconst check = (entry) => {\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* 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*/\nfunction isJSONPrimitive(value) {\n\treturn isNull(value) || isString(value) || isFiniteNumber(value) || isBoolean(value);\n}\n//#endregion\n//#region src/core/helpers.ts\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*/\nfunction attempt(callback) {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: callback()\n\t\t};\n\t} catch (reason) {\n\t\tif (reason instanceof Error) return {\n\t\t\tsuccess: false,\n\t\t\terror: reason\n\t\t};\n\t\tlet message = \"Unknown thrown value\";\n\t\ttry {\n\t\t\tmessage = String(reason);\n\t\t} catch {}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: new Error(message)\n\t\t};\n\t}\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*/\nfunction resolveField(record, path) {\n\tconst keys = isString(path) ? [path] : path;\n\tlet current = record;\n\tfor (const key of keys) {\n\t\tif (!isObject(current)) return void 0;\n\t\tconst container = current;\n\t\tconst outcome = attempt(() => Reflect.get(container, key));\n\t\tif (!outcome.success) return void 0;\n\t\tcurrent = outcome.value;\n\t}\n\treturn current;\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*/\nfunction seededRandom(seed) {\n\tlet state = seed >>> 0;\n\treturn () => {\n\t\tstate = state + 1831565813 >>> 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) / 4294967296;\n\t};\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*/\nfunction enumerableSymbolCount(value) {\n\tlet count = 0;\n\tfor (const symbol of Object.getOwnPropertySymbols(value)) if (Object.getOwnPropertyDescriptor(value, symbol)?.enumerable) count += 1;\n\treturn count;\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*/\nfunction schemaToParameters(schema) {\n\treturn isRecord(schema) ? schema : void 0;\n}\n//#endregion\n//#region src/core/combinators.ts\nfunction arrayOf(elementGuard) {\n\treturn (value) => {\n\t\tif (!isArray(value)) return false;\n\t\tconst outcome = attempt(() => value.every(elementGuard));\n\t\treturn outcome.success && outcome.value;\n\t};\n}\nfunction tupleOf(...guards) {\n\treturn (value) => {\n\t\tif (!isArray(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tif (value.length !== guards.length) return false;\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])) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\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*/\nfunction literalOf(...literals) {\n\treturn (value) => literals.some((literal) => Object.is(literal, value));\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*/\nfunction instanceOf(ctor) {\n\treturn (value) => isConstructor(ctor) && isObject(value) && value instanceof ctor;\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*/\nfunction enumOf(enumeration) {\n\tconst values = new Set(Object.values(enumeration));\n\treturn (value) => (isString(value) || isNumber(value)) && values.has(value);\n}\nfunction setOf(elementGuard) {\n\treturn (value) => {\n\t\tif (!isSet(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) if (!elementGuard(entry)) return false;\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\n}\nfunction mapOf(keyGuard, valueGuard) {\n\treturn (value) => {\n\t\tif (!isMap(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const [key, entryValue] of value) if (!keyGuard(key) || !valueGuard(entryValue)) return false;\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\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*/\nfunction recordOf(shape, optional) {\n\tconst allowed = /* @__PURE__ */ new Set();\n\tfor (const key in shape) if (Object.prototype.hasOwnProperty.call(shape, key)) allowed.add(key);\n\tconst optionalSet = new Set(optional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : []);\n\treturn (value) => {\n\t\tif (!isRecord(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const key of Object.keys(value)) if (!allowed.has(key)) return false;\n\t\t\tfor (const key in shape) {\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) continue;\n\t\t\t\tconst present = Object.hasOwn(value, key);\n\t\t\t\tif (!optionalSet.has(key) && !present) return false;\n\t\t\t\tif (present) {\n\t\t\t\t\tconst guard = shape[key];\n\t\t\t\t\tif (!guard(value[key])) return 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}\nfunction iterableOf(elementGuard) {\n\treturn (value) => {\n\t\tif (!isIterable(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) if (!elementGuard(entry)) return false;\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\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*/\nfunction keyOf(value) {\n\treturn (entry) => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry);\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*/\nfunction pickOf(shape, keys) {\n\tconst result = Object.create(null);\n\tfor (const key of keys) if (Object.prototype.hasOwnProperty.call(shape, key)) result[key] = shape[key];\n\treturn result;\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*/\nfunction omitOf(shape, keys) {\n\tconst skipped = /* @__PURE__ */ new Set();\n\tfor (const key of keys) skipped.add(key);\n\tconst result = Object.create(null);\n\tfor (const key in shape) {\n\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) continue;\n\t\tif (!skipped.has(key)) result[key] = shape[key];\n\t}\n\treturn result;\n}\nfunction andOf(left, right) {\n\treturn (value) => left(value) && right(value);\n}\nfunction orOf(left, right) {\n\treturn (value) => left(value) || right(value);\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*/\nfunction notOf(guard) {\n\treturn (value) => !guard(value);\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*/\nfunction complementOf(base, excluded) {\n\treturn (value) => {\n\t\tif (!base(value)) return false;\n\t\treturn !excluded(value);\n\t};\n}\nfunction unionOf(...guards) {\n\treturn (value) => guards.some((guard) => guard(value));\n}\nfunction intersectionOf(...guards) {\n\treturn (value) => guards.every((guard) => guard(value));\n}\nfunction whereOf(base, predicate) {\n\treturn (value) => {\n\t\tif (!base(value)) return false;\n\t\tconst outcome = attempt(() => predicate(value));\n\t\treturn outcome.success && outcome.value;\n\t};\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*/\nfunction lazyOf(thunk) {\n\treturn (value) => {\n\t\tconst outcome = attempt(() => thunk()(value));\n\t\treturn outcome.success && outcome.value;\n\t};\n}\nfunction transformOf(base, project, target) {\n\treturn (value) => {\n\t\tif (!base(value)) return false;\n\t\tconst outcome = attempt(() => project(value));\n\t\treturn outcome.success && target(outcome.value);\n\t};\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*/\nfunction boundsOf(min, max) {\n\treturn whereOf(isFiniteNumber, (value) => (min === void 0 || value >= min) && (max === void 0 || value <= max));\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*/\nfunction matchOf(pattern) {\n\treturn whereOf(isString, (value) => pattern.test(value));\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*/\nfunction stringOf(options) {\n\tconst min = options?.min;\n\tconst max = options?.max;\n\tconst pattern = options?.pattern;\n\tif (min === void 0 && max === void 0 && pattern === void 0) return isString;\n\tconst withinLength = boundsOf(min, max);\n\treturn whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || pattern.test(value)));\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*/\nfunction nullableOf(guard) {\n\treturn (value) => value === null || guard(value);\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*/\nfunction optionalOf(guard) {\n\treturn (value) => value === void 0 || guard(value);\n}\n//#endregion\n//#region src/core/parsers.ts\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*/\nfunction parseString(value) {\n\tif (isString(value)) return value;\n\tif (isFiniteNumber(value)) return String(value);\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*/\nfunction parseNumber(value) {\n\tif (typeof value === \"number\") return Number.isFinite(value) ? value : void 0;\n\tif (isString(value)) {\n\t\tif (value.trim() === \"\") return void 0;\n\t\tconst parsed = Number(value);\n\t\treturn Number.isFinite(parsed) ? parsed : void 0;\n\t}\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*/\nfunction parseInteger(value) {\n\tconst parsed = parseNumber(value);\n\tif (parsed === void 0) return void 0;\n\treturn Number.isInteger(parsed) ? parsed : void 0;\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*/\nfunction parseBoolean(value) {\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}\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*/\nfunction parseNull(value) {\n\treturn isNull(value) ? value : void 0;\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*/\nfunction parseRecord(value) {\n\treturn isRecord(value) ? value : void 0;\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*/\nfunction parseArray(value, guard) {\n\tif (!isArray(value)) return void 0;\n\tif (guard !== void 0 && !value.every(guard)) return void 0;\n\treturn value;\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*/\nfunction parseJSONValue(value) {\n\treturn isJSONValue(value) ? value : void 0;\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*/\nfunction parseEnum(value, allowed) {\n\tfor (const option of allowed) if (Object.is(value, option)) return option;\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*/\nfunction parseStringField(record, path) {\n\treturn parseString(resolveField(record, path));\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*/\nfunction parseNumberField(record, path) {\n\treturn parseNumber(resolveField(record, path));\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*/\nfunction parseIntegerField(record, path) {\n\treturn parseInteger(resolveField(record, path));\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*/\nfunction parseBooleanField(record, path) {\n\treturn parseBoolean(resolveField(record, path));\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*/\nfunction parseNullField(record, path) {\n\treturn parseNull(resolveField(record, path));\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*/\nfunction parseRecordField(record, path) {\n\treturn parseRecord(resolveField(record, path));\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*/\nfunction parseArrayField(record, path, guard) {\n\treturn parseArray(resolveField(record, path), guard);\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*/\nfunction parseEnumField(record, path, allowed) {\n\treturn parseEnum(resolveField(record, path), allowed);\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*/\nfunction parseJSONValueField(record, path) {\n\treturn parseJSONValue(resolveField(record, path));\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*/\nfunction parseJSON(value) {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn;\n\t}\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*/\nfunction parseJSONAs(value, guard) {\n\tconst parsed = parseJSON(value);\n\tif (parsed === void 0) return void 0;\n\treturn guard(parsed) ? parsed : void 0;\n}\n//#endregion\n//#region src/core/compilers.ts\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*/\nfunction validateShape(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\":\n\t\t\tif (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error(\"validateShape: a string shape has min greater than max\");\n\t\t\treturn;\n\t\tcase \"number\":\n\t\t\tif (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error(\"validateShape: a number shape has min greater than max\");\n\t\t\tif (shape.integer === true) {\n\t\t\t\tif (Math.ceil(shape.min ?? Number.NEGATIVE_INFINITY) > Math.floor(shape.max ?? Number.POSITIVE_INFINITY)) throw new Error(\"validateShape: an integer number shape has an empty integer range\");\n\t\t\t}\n\t\t\treturn;\n\t\tcase \"boolean\":\n\t\tcase \"null\":\n\t\tcase \"json\":\n\t\tcase \"raw\": return;\n\t\tcase \"literal\":\n\t\t\tif (shape.values.length === 0) throw new Error(\"validateShape: a literal shape needs at least one value\");\n\t\t\tfor (const value of shape.values) if (typeof value === \"number\" && !Number.isFinite(value)) throw new Error(\"validateShape: a literal shape may not contain non-finite number values\");\n\t\t\treturn;\n\t\tcase \"array\":\n\t\t\tif (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error(\"validateShape: an array shape has min greater than max\");\n\t\t\tvalidateShape(shape.items);\n\t\t\treturn;\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 === void 0) 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 !== void 0 && 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) throw new Error(\"validateShape: a union shape needs at least one variant\");\n\t\t\tfor (const variant of shape.variants) validateShape(variant);\n\t\t\treturn;\n\t\tcase \"optional\": throw new Error(\"validateShape: an optional shape may only appear as a direct object-property value\");\n\t\tcase \"nullable\":\n\t\t\tvalidateShape(shape.inner);\n\t\t\treturn;\n\t}\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*/\nfunction compileSchema(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\": return {\n\t\t\ttype: \"string\",\n\t\t\t...shape.min !== void 0 ? { minLength: shape.min } : {},\n\t\t\t...shape.max !== void 0 ? { maxLength: shape.max } : {},\n\t\t\t...shape.pattern !== void 0 ? { pattern: shape.pattern.source } : {},\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"number\": return {\n\t\t\ttype: shape.integer === true ? \"integer\" : \"number\",\n\t\t\t...shape.min !== void 0 ? { minimum: shape.min } : {},\n\t\t\t...shape.max !== void 0 ? { maximum: shape.max } : {},\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"boolean\": return {\n\t\t\ttype: \"boolean\",\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"null\": return {\n\t\t\ttype: \"null\",\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"json\": return { ...shape.description !== void 0 ? { description: shape.description } : {} };\n\t\tcase \"literal\": return {\n\t\t\tenum: [...shape.values],\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"array\": return {\n\t\t\ttype: \"array\",\n\t\t\titems: compileSchema(shape.items),\n\t\t\t...shape.min !== void 0 ? { minItems: shape.min } : {},\n\t\t\t...shape.max !== void 0 ? { maxItems: shape.max } : {},\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"object\": {\n\t\t\tconst properties = {};\n\t\t\tconst required = [];\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 === void 0) 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 = extra === true ? true : extra !== void 0 && extra !== false ? compileSchema(extra) : 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 !== void 0 ? { description: shape.description } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"union\": return {\n\t\t\t...shape.mode === \"oneOf\" ? { oneOf: shape.variants.map((variant) => compileSchema(variant)) } : { anyOf: shape.variants.map((variant) => compileSchema(variant)) },\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"optional\": return compileSchema(shape.inner);\n\t\tcase \"nullable\": return { anyOf: [compileSchema(shape.inner), { type: \"null\" }] };\n\t\tcase \"raw\": return shape.schema;\n\t}\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*/\nfunction compileGuard(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\": return stringOf({\n\t\t\tmin: shape.min,\n\t\t\tmax: shape.max,\n\t\t\tpattern: shape.pattern\n\t\t});\n\t\tcase \"number\": {\n\t\t\tconst base = shape.integer === true ? isInteger : isFiniteNumber;\n\t\t\tif (shape.min === void 0 && shape.max === void 0) return base;\n\t\t\treturn shape.integer === true ? intersectionOf(isInteger, boundsOf(shape.min, shape.max)) : boundsOf(shape.min, shape.max);\n\t\t}\n\t\tcase \"boolean\": return isBoolean;\n\t\tcase \"null\": return isNull;\n\t\tcase \"json\": return isJSONValue;\n\t\tcase \"literal\": return literalOf(...shape.values);\n\t\tcase \"array\": {\n\t\t\tconst base = arrayOf(compileGuard(shape.items));\n\t\t\tif (shape.min === void 0 && shape.max === void 0) 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\tconst map = Object.create(null);\n\t\t\tconst optionalKeys = [];\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 === void 0) 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 map[key] = compileGuard(child);\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties;\n\t\t\tif (extra === void 0 || extra === false) return optionalKeys.length > 0 ? recordOf(map, optionalKeys) : recordOf(map);\n\t\t\tconst additional = extra === true ? void 0 : compileGuard(extra);\n\t\t\tconst required = Object.keys(map).filter((key) => !optionalKeys.includes(key));\n\t\t\treturn (value) => {\n\t\t\t\tif (!isRecord(value)) return false;\n\t\t\t\tfor (const key of required) if (!Object.hasOwn(value, key)) return false;\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] : void 0;\n\t\t\t\t\t\tif (guard !== void 0) {\n\t\t\t\t\t\t\tif (!guard(value[key])) return false;\n\t\t\t\t\t\t} else if (additional !== void 0 && !additional(value[key])) return false;\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\": return unionOf(...shape.variants.map((variant) => compileGuard(variant)));\n\t\tcase \"optional\": return orOf(isUndefined, compileGuard(shape.inner));\n\t\tcase \"nullable\": return nullableOf(compileGuard(shape.inner));\n\t\tcase \"raw\": return (_value) => true;\n\t}\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*/\nfunction compileParser(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\": {\n\t\t\tif (shape.min === void 0 && shape.max === void 0 && shape.pattern === void 0) return parseString;\n\t\t\tconst guard = stringOf({\n\t\t\t\tmin: shape.min,\n\t\t\t\tmax: shape.max,\n\t\t\t\tpattern: shape.pattern\n\t\t\t});\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = parseString(value);\n\t\t\t\treturn parsed !== void 0 && guard(parsed) ? parsed : void 0;\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 === void 0 && shape.max === void 0) return base;\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 !== void 0 && within(parsed) ? parsed : void 0;\n\t\t\t};\n\t\t}\n\t\tcase \"boolean\": return parseBoolean;\n\t\tcase \"null\": return (value) => value === null ? null : void 0;\n\t\tcase \"json\": return (value) => isJSONValue(value) ? value : void 0;\n\t\tcase \"literal\": {\n\t\t\tconst allowed = new Set(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};\n\t\t}\n\t\tcase \"array\": {\n\t\t\tconst item = compileParser(shape.items);\n\t\t\tconst unbounded = shape.min === void 0 && shape.max === void 0;\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max);\n\t\t\treturn (value) => {\n\t\t\t\tif (!isArray(value)) return void 0;\n\t\t\t\tconst result = [];\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 === void 0) return void 0;\n\t\t\t\t\tresult.push(parsed);\n\t\t\t\t}\n\t\t\t\treturn unbounded || withinLength(result.length) ? result : void 0;\n\t\t\t};\n\t\t}\n\t\tcase \"object\": {\n\t\t\tconst entries = [];\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 === void 0) continue;\n\t\t\t\tconst optional = child.type === \"optional\";\n\t\t\t\tentries.push({\n\t\t\t\t\tkey,\n\t\t\t\t\tparse: compileParser(optional ? child.inner : child),\n\t\t\t\t\toptional\n\t\t\t\t});\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 = extra === void 0 || extra === false || extra === true ? void 0 : compileParser(extra);\n\t\t\tconst open = extra === true || additional !== void 0;\n\t\t\treturn (value) => {\n\t\t\t\tconst record = parseRecord(value);\n\t\t\t\tif (record === void 0) return void 0;\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\tconst result = 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 === void 0) {\n\t\t\t\t\t\t\tif (entry.optional) continue;\n\t\t\t\t\t\t\treturn;\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 === void 0) return void 0;\n\t\t\t\t\t\tresult[entry.key] = parsed;\n\t\t\t\t\t}\n\t\t\t\t\tif (open) for (const key of Object.keys(record)) {\n\t\t\t\t\t\tif (known.has(key)) continue;\n\t\t\t\t\t\tif (additional === void 0) result[key] = record[key];\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst parsed = additional(record[key]);\n\t\t\t\t\t\t\tif (parsed === void 0) return void 0;\n\t\t\t\t\t\t\tresult[key] = parsed;\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 : void 0;\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\tfor (const variant of variants) if (variant.guard(value)) return value;\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 !== void 0 && variant.guard(parsed)) return parsed;\n\t\t\t\t}\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 === void 0 ? void 0 : 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\": return (value) => value;\n\t}\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*/\nfunction compileGenerator(shape, random = seededRandom(Date.now())) {\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) value += alphabet[Math.floor(random() * 36)];\n\t\t\tif (shape.pattern !== void 0 && !shape.pattern.test(value)) throw new Error(\"compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way\");\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\": return random() >= .5;\n\t\tcase \"null\": return 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() >= .5;\n\t\t\tif (pick === 2) return Math.floor(random() * 1e3);\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) value += alphabet[Math.floor(random() * 26)];\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\treturn { value: Math.floor(random() * 1e3) };\n\t\t}\n\t\tcase \"literal\":\n\t\t\tif (shape.values.length === 0) throw new Error(\"compileGenerator: a literal shape needs at least one value\");\n\t\t\treturn shape.values[Math.floor(random() * shape.values.length)];\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 = [];\n\t\t\tfor (let index = 0; index < length; index += 1) result.push(compileGenerator(shape.items, random));\n\t\t\treturn result;\n\t\t}\n\t\tcase \"object\": {\n\t\t\tconst result = {};\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 === void 0) continue;\n\t\t\t\tif (child.type === \"optional\" && random() < .3) continue;\n\t\t\t\tresult[key] = compileGenerator(child, random);\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties;\n\t\t\tif (extra !== void 0 && 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) throw new Error(\"compileGenerator: a union shape needs at least one variant\");\n\t\t\treturn compileGenerator(shape.variants[Math.floor(random() * shape.variants.length)], random);\n\t\tcase \"optional\": return compileGenerator(shape.inner, random);\n\t\tcase \"nullable\": return random() < .2 ? null : compileGenerator(shape.inner, random);\n\t\tcase \"raw\": throw new Error(\"compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way\");\n\t}\n}\nfunction createContract(shape) {\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) {\n\t\t\treturn parser(value);\n\t\t},\n\t\tgenerate(random) {\n\t\t\treturn compileGenerator(shape, random);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/core/shapers.ts\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*/\nfunction stringShape(options) {\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* Build a numeric {@link NumberShape}.\n*\n* @param options - Optional bounds (`min` / `max`), `integer`, and `description`\n* @returns A number shape\n*/\nfunction numberShape(options) {\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* 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*/\nfunction integerShape(options) {\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* Build a {@link BooleanShape}.\n*\n* @param options - Optional `description`\n* @returns A boolean shape\n*/\nfunction booleanShape(options) {\n\treturn {\n\t\ttype: \"boolean\",\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build a {@link NullShape}.\n*\n* @param options - Optional `description`\n* @returns A null shape\n*/\nfunction nullShape(options) {\n\treturn {\n\t\ttype: \"null\",\n\t\tdescription: options?.description\n\t};\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*/\nfunction literalShape(values, options) {\n\treturn {\n\t\ttype: \"literal\",\n\t\tvalues,\n\t\tdescription: options?.description\n\t};\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*/\nfunction arrayShape(items, options) {\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* 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*/\nfunction objectShape(properties, options) {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties,\n\t\tadditionalProperties: options?.additionalProperties,\n\t\tdescription: options?.description\n\t};\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*/\nfunction recordShape(values, options) {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {},\n\t\tadditionalProperties: values,\n\t\tdescription: options?.description\n\t};\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*/\nfunction unionShape(...variants) {\n\treturn {\n\t\ttype: \"union\",\n\t\tvariants\n\t};\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*/\nfunction oneOfShape(...variants) {\n\treturn {\n\t\ttype: \"union\",\n\t\tvariants,\n\t\tmode: \"oneOf\"\n\t};\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*/\nfunction optionalShape(inner) {\n\treturn {\n\t\ttype: \"optional\",\n\t\tinner\n\t};\n}\n/**\n* Wrap a shape so it may be `null`.\n*\n* @param inner - The wrapped shape\n* @returns A nullable shape\n*/\nfunction nullableShape(inner) {\n\treturn {\n\t\ttype: \"nullable\",\n\t\tinner\n\t};\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*/\nfunction jsonShape(options) {\n\treturn {\n\t\ttype: \"json\",\n\t\tdescription: options?.description\n\t};\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*/\nfunction rawShape(schema) {\n\treturn {\n\t\ttype: \"raw\",\n\t\tschema\n\t};\n}\n//#endregion\nexport { JSON_SCHEMA_TYPES, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, compileGenerator, compileGuard, compileParser, compileSchema, complementOf, createContract, enumOf, enumerableSymbolCount, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isConstructor, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterableOf, jsonShape, keyOf, lazyOf, literalOf, literalShape, mapOf, matchOf, notOf, nullShape, nullableOf, nullableShape, numberShape, objectShape, omitOf, oneOfShape, optionalOf, optionalShape, orOf, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pickOf, rawShape, recordOf, recordShape, resolveField, schemaToParameters, seededRandom, setOf, stringOf, stringShape, transformOf, tupleOf, unionOf, unionShape, validateShape, whereOf };\n\n//# sourceMappingURL=index.js.map","import type { AggregateFunction, ColumnType, Row, TableSchema } from '@src/core'\nimport type { FieldPath } from '@orkestrel/contract'\nimport type { SQLiteRow, SQLiteValue } from './types.js'\nimport { isString } from '@orkestrel/contract'\nimport { randomUUID } from 'node:crypto'\n\n// The server's key-minting `KeyFunction` implementation — `core` mints no keys\n// itself (AGENTS §1: cross-environment code touches no `node:*`), so a server\n// consumer wires this in as `DatabaseOptions.key`.\n//\n// Below it: the SQLite ↔ JS bridge for the driver. Every helper is pure and\n// total — it narrows with `typeof` / `instanceof`, never `as` (AGENTS §1, §14):\n// a value that does not fit its column's storage type encodes to `null` rather\n// than throwing, and `decodeValue` is the exact inverse. `encodeRow` /\n// `decodeRow` lift the per-cell codecs across a whole schema; the SQL\n// identifier / type helpers (`quote`, `columnSQL`, `fieldColumn`) build the\n// static parts of a statement. `schemaToTable` / `schemaToIndexes` are pure\n// projections of the CREATE TABLE / CREATE INDEX DDL a SQLite driver's `open`\n// issues. This module speaks pure strings/values only — it imports no SQLite\n// package.\n\n/**\n * Generate a fresh unique key — a v4 UUID string, backed by `node:crypto`.\n *\n * @remarks\n * Supply this as {@link import('@src/core').DatabaseOptions.key} so a table mints\n * a key when a written row lacks its primary-key value. Strings work as keys on\n * every backend; supply your own key values directly to use numeric keys instead.\n *\n * @returns A new UUID string\n *\n * @example\n * ```ts\n * const db = createDatabase({ driver, tables, key: generateKey })\n * ```\n */\nexport function generateKey(): string {\n\treturn randomUUID()\n}\n\n// === SQL identifiers & types\n\n/**\n * Map a portable {@link ColumnType} to its SQLite column type.\n *\n * @remarks\n * `text` / `json` → `TEXT` (JSON is stored as text and read back with\n * `json_extract` for nested-field queries); `integer` / `boolean` → `INTEGER`\n * (a boolean stores `1` / `0`); `real` → `REAL`; `blob` → `BLOB`. No `NOT NULL`\n * is ever emitted — the contract validates required-ness; the database is just\n * storage (AGENTS §14, the typed layer above imposes the shape).\n *\n * @param type - The portable column type\n * @returns The SQLite column type keyword\n *\n * @example\n * ```ts\n * columnSQL('integer') // 'INTEGER'\n * columnSQL('json') // 'TEXT'\n * ```\n */\nexport function columnSQL(type: ColumnType): string {\n\tswitch (type) {\n\t\tcase 'text':\n\t\tcase 'json':\n\t\t\treturn 'TEXT'\n\t\tcase 'integer':\n\t\tcase 'boolean':\n\t\t\treturn 'INTEGER'\n\t\tcase 'real':\n\t\t\treturn 'REAL'\n\t\tcase 'blob':\n\t\t\treturn 'BLOB'\n\t}\n}\n\n/**\n * Quote a SQL identifier (a table or column name) so any characters are literal.\n *\n * @remarks\n * Wraps the name in double quotes and doubles any embedded quote — the standard\n * SQL identifier-quoting that lets a column named `order` or `from` be referenced\n * safely. Identifiers cannot be bound as parameters, so they are quoted instead.\n *\n * @param identifier - The raw identifier\n * @returns The double-quoted identifier\n *\n * @example\n * ```ts\n * quote('order') // '\"order\"'\n * ```\n */\nexport function quote(identifier: string): string {\n\treturn '\"' + identifier.replaceAll('\"', '\"\"') + '\"'\n}\n\n/**\n * Compile a {@link FieldPath} to the SQL expression that reads it.\n *\n * @remarks\n * A single string is ONE column — `quote(path)`. An array descends a JSON column:\n * the first element is the (quoted) column, the rest a `json_extract` path\n * (`json_extract(\"payload\", '$.user.id')`), matching the guide's nested-field\n * examples (simple identifier keys). The string's value is never split on `.`\n * (AGENTS — `FieldPath` semantics): a dotted string is one column literally.\n *\n * @param path - The field path (a column, or a column + nested keys)\n * @returns The SQL expression selecting the value\n *\n * @example\n * ```ts\n * fieldColumn('payload') // '\"payload\"'\n * fieldColumn(['payload', 'user', 'id']) // 'json_extract(\"payload\", \\'$.user.id\\')'\n * ```\n */\nexport function fieldColumn(path: FieldPath): string {\n\tif (isString(path)) return quote(path)\n\tconst rest = path\n\t\t.slice(1)\n\t\t.map((key) => '.' + key.replaceAll(\"'\", \"''\"))\n\t\t.join('')\n\treturn 'json_extract(' + quote(path[0]) + \", '$\" + rest + \"')\"\n}\n\n/**\n * Compile an {@link AggregateFunction} over a {@link FieldPath} to its SQL\n * aggregate expression — the SELECT body the SQLite driver's native `aggregate`\n * runs.\n *\n * @remarks\n * `count` → `COUNT(*)` (counting all matched ROWS, not non-null column values —\n * mirroring the engine's `computeAggregate('count')`, which is `rows.length`); the\n * numeric aggregates wrap the column's read expression (a flat column, or a nested\n * `json_extract` path) in `SUM` / `AVG` / `MIN` / `MAX`. Over zero matched rows\n * `COUNT(*)` is `0` and the numeric aggregates are SQL `NULL` (→ `undefined`),\n * matching the engine.\n *\n * @param operation - The aggregate to compute\n * @param column - The column (or nested path) to aggregate\n * @returns The SQL aggregate expression\n *\n * @example\n * ```ts\n * aggregateSQL('count', 'age') // 'COUNT(*)'\n * aggregateSQL('sum', 'age') // 'SUM(\"age\")'\n * aggregateSQL('average', ['payload', 'score']) // 'AVG(json_extract(\"payload\", \\'$.score\\'))'\n * ```\n */\nexport function aggregateSQL(operation: AggregateFunction, column: FieldPath): string {\n\tswitch (operation) {\n\t\tcase 'count':\n\t\t\treturn 'COUNT(*)'\n\t\tcase 'sum':\n\t\t\treturn 'SUM(' + fieldColumn(column) + ')'\n\t\tcase 'average':\n\t\t\treturn 'AVG(' + fieldColumn(column) + ')'\n\t\tcase 'minimum':\n\t\t\treturn 'MIN(' + fieldColumn(column) + ')'\n\t\tcase 'maximum':\n\t\t\treturn 'MAX(' + fieldColumn(column) + ')'\n\t}\n}\n\n// === Value codecs\n\n/**\n * Encode a JS value to its stored {@link SQLiteValue} for a column's type.\n *\n * @remarks\n * The forward half of the bridge, total (AGENTS §14): a value that does not fit\n * its column's storage type encodes to `null` rather than throwing. A `boolean`\n * column stores `1` / `0` (and `null` / `undefined` → `null`); a `json` column\n * stores `JSON.stringify` (or `null` for `null` / `undefined`); `integer` /\n * `real` keep a `number` / `bigint`, else `null`; `text` keeps a `string`, else\n * `null`; `blob` keeps a `Uint8Array`, else `null`. Narrowed with `typeof` /\n * `instanceof`, never `as`.\n *\n * @param value - The JS value to store\n * @param type - The column's portable storage type\n * @returns The value SQLite stores\n *\n * @example\n * ```ts\n * encodeValue(true, 'boolean') // 1\n * encodeValue({ a: 1 }, 'json') // '{\"a\":1}'\n * ```\n */\nexport function encodeValue(value: unknown, type: ColumnType): SQLiteValue {\n\tswitch (type) {\n\t\tcase 'boolean':\n\t\t\treturn value === undefined || value === null ? null : value === true ? 1 : 0\n\t\tcase 'json':\n\t\t\treturn value === undefined || value === null ? null : JSON.stringify(value)\n\t\tcase 'integer':\n\t\tcase 'real':\n\t\t\treturn typeof value === 'number' || typeof value === 'bigint' ? value : null\n\t\tcase 'text':\n\t\t\treturn typeof value === 'string' ? value : null\n\t\tcase 'blob':\n\t\t\treturn value instanceof Uint8Array ? value : null\n\t}\n}\n\n/**\n * Decode a stored {@link SQLiteValue} back to its JS value for a column's type —\n * the exact inverse of {@link encodeValue}.\n *\n * @remarks\n * A `boolean` column reads `1` / `0` back to `true` / `false` (a stored `null`\n * → `undefined`); a `json` column `JSON.parse`s a string (anything else →\n * `undefined`); every other type passes the value through, mapping a stored\n * `NULL` to `undefined`. NULL decodes to `undefined` so {@link decodeRow} can\n * omit absent columns.\n *\n * @param value - The stored SQLite value\n * @param type - The column's portable storage type\n * @returns The decoded JS value (`undefined` for a stored `NULL`)\n *\n * @example\n * ```ts\n * decodeValue(1, 'boolean') // true\n * decodeValue('{\"a\":1}', 'json') // { a: 1 }\n * ```\n */\nexport function decodeValue(value: SQLiteValue, type: ColumnType): unknown {\n\tswitch (type) {\n\t\tcase 'boolean':\n\t\t\treturn value === null ? undefined : value !== 0\n\t\tcase 'json':\n\t\t\treturn typeof value === 'string' ? JSON.parse(value) : undefined\n\t\tdefault:\n\t\t\treturn value === null ? undefined : value\n\t}\n}\n\n/**\n * Encode a whole {@link Row} to a {@link SQLiteRow} by its table's schema.\n *\n * @remarks\n * Encodes each declared column's value with {@link encodeValue}; columns the row\n * does not carry encode from `undefined` (so they store `null`). Only the\n * schema's columns appear in the result — an extra row key is dropped.\n *\n * @param row - The JS row to store\n * @param schema - The table's schema\n * @returns The storable SQLite row\n *\n * @example\n * ```ts\n * encodeRow({ id: 'u1', active: true }, schema) // { id: 'u1', active: 1, ... }\n * ```\n */\nexport function encodeRow(row: Row, schema: TableSchema): SQLiteRow {\n\tconst result: SQLiteRow = {}\n\tfor (const column of schema.columns) {\n\t\tresult[column.name] = encodeValue(row[column.name], column.type)\n\t}\n\treturn result\n}\n\n/**\n * Decode a stored {@link SQLiteRow} back to a {@link Row} by its table's schema.\n *\n * @remarks\n * Decodes each declared column with {@link decodeValue} and **omits** any column\n * whose decoded value is `undefined` — so an absent / `NULL` optional column does\n * not surface as `{ bio: undefined }`, matching how the contract's optional\n * columns expect absence. A known, documented edge: a non-optional `nullableShape`\n * column storing `null` round-trips to absent (a `null` cell decodes to\n * `undefined`, and an `undefined` value is omitted).\n *\n * @param row - The stored SQLite row\n * @param schema - The table's schema\n * @returns The decoded JS row (absent columns omitted)\n *\n * @example\n * ```ts\n * decodeRow({ id: 'u1', active: 1, bio: null }, schema) // { id: 'u1', active: true }\n * ```\n */\nexport function decodeRow(row: SQLiteRow, schema: TableSchema): Row {\n\tconst result: Row = {}\n\tfor (const column of schema.columns) {\n\t\tconst decoded = decodeValue(row[column.name], column.type)\n\t\tif (decoded !== undefined) result[column.name] = decoded\n\t}\n\treturn result\n}\n\n// === DDL projections\n\n/**\n * Project a {@link TableSchema} to the `CREATE TABLE IF NOT EXISTS` statement a\n * SQLite driver's `open` issues for it.\n *\n * @remarks\n * Each column compiles to `<quoted name> <columnSQL(type)>`; the statement ends\n * with `PRIMARY KEY (<quoted primary>)`. No `NOT NULL` is emitted — the contract\n * validates required-ness, the database is just storage (AGENTS §14).\n *\n * @param schema - The table's schema\n * @returns The `CREATE TABLE IF NOT EXISTS …` statement\n *\n * @example\n * ```ts\n * schemaToTable(schema)\n * // 'CREATE TABLE IF NOT EXISTS \"users\" (\"id\" TEXT, \"age\" INTEGER, PRIMARY KEY (\"id\"))'\n * ```\n */\nexport function schemaToTable(schema: TableSchema): string {\n\tconst columns = schema.columns.map((column) => quote(column.name) + ' ' + columnSQL(column.type))\n\treturn (\n\t\t'CREATE TABLE IF NOT EXISTS ' +\n\t\tquote(schema.name) +\n\t\t' (' +\n\t\tcolumns.join(', ') +\n\t\t', PRIMARY KEY (' +\n\t\tquote(schema.primary) +\n\t\t'))'\n\t)\n}\n\n/**\n * Project a {@link TableSchema} to the `CREATE INDEX IF NOT EXISTS` statements a\n * SQLite driver's `open` issues for its declared indexes.\n *\n * @remarks\n * One statement per index group; the index name is `idx_<table>_<columns joined\n * by _>`, matching the driver's naming so a repeated `open` is idempotent.\n *\n * @param schema - The table's schema\n * @returns One `CREATE INDEX IF NOT EXISTS …` statement per declared index\n *\n * @example\n * ```ts\n * schemaToIndexes(schema)\n * // ['CREATE INDEX IF NOT EXISTS \"idx_users_name\" ON \"users\" (\"name\")']\n * ```\n */\nexport function schemaToIndexes(schema: TableSchema): readonly string[] {\n\treturn schema.indexes.map(\n\t\t(group) =>\n\t\t\t'CREATE INDEX IF NOT EXISTS ' +\n\t\t\tquote('idx_' + schema.name + '_' + group.join('_')) +\n\t\t\t' ON ' +\n\t\t\tquote(schema.name) +\n\t\t\t' (' +\n\t\t\tgroup.map(quote).join(', ') +\n\t\t\t')',\n\t)\n}\n","import type { ColumnType, Condition, Criteria, Order, TableSchema } from '@src/core'\nimport type { CompiledSQL, SQLiteValue } from './types.js'\nimport { isString } from '@orkestrel/contract'\nimport { encodeValue, fieldColumn, quote } from './helpers.js'\n\n// The `Criteria` → parameterized SQL compiler — the native-query payoff. It turns\n// a portable `Criteria` (the same one the core engine's `applyCriteria` folds)\n// into the `WHERE` / `ORDER BY` / `LIMIT` tail of a `SELECT`, with bound `?`\n// params in clause order. Its WHERE fold parenthesizes LEFT-TO-RIGHT to match the\n// engine's `matchesCriteria` exactly (NOT SQL's AND-over-OR precedence), so a\n// native read and an engine read agree on every query (the parity test). Branches\n// are centralized and public per AGENTS §5 — no operator logic buried in closures.\n// This module speaks pure strings/values only — it imports no SQLite package.\n\n/**\n * Escape `\\`, `%`, and `_` (each with a leading `\\`) so a `starts` / `ends`\n * operand is matched literally under the `LIKE … ESCAPE '\\'` clause.\n *\n * @param text - The raw operand text\n * @returns The text with LIKE metacharacters escaped\n *\n * @example\n * ```ts\n * escapeLike('50%_off') // '50\\\\%\\\\_off'\n * ```\n */\nexport function escapeLike(text: string): string {\n\treturn text.replaceAll('\\\\', '\\\\\\\\').replaceAll('%', '\\\\%').replaceAll('_', '\\\\_')\n}\n\n/**\n * The declared storage type of a flat (string) column, read from the schema.\n *\n * @param column - The column name\n * @param schema - The table's schema\n * @returns The column's {@link ColumnType}, or `undefined` if the schema does not carry it\n *\n * @example\n * ```ts\n * declaredType('age', schema) // 'integer'\n * ```\n */\nexport function declaredType(column: string, schema: TableSchema): ColumnType | undefined {\n\treturn schema.columns.find((candidate) => candidate.name === column)?.type\n}\n\n/**\n * The storage type a nested (`json_extract`) operand encodes as, derived from its\n * RUNTIME value — NOT `json`.\n *\n * @remarks\n * `json_extract` returns the unquoted, natively-typed scalar (a JSON boolean as\n * `1` / `0`, a number as-is, a string as-is), so the operand must encode to that\n * same scalar to compare. A boolean → `'boolean'` (→ `1` / `0`); a number →\n * `'integer'` / `'real'`; a bigint → `'integer'`; a string → `'text'`; `null` /\n * `undefined` → `'text'` (encodes to `null`); an object / array → `'json'` (the\n * edge of comparing against a json subtree).\n *\n * @param value - The runtime operand value\n * @returns The {@link ColumnType} to encode it as\n *\n * @example\n * ```ts\n * valueType(true) // 'boolean'\n * valueType(9) // 'integer'\n * ```\n */\nexport function valueType(value: unknown): ColumnType {\n\tif (typeof value === 'boolean') return 'boolean'\n\tif (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'real'\n\tif (typeof value === 'bigint') return 'integer'\n\tif (typeof value === 'object' && value !== null) return 'json'\n\treturn 'text'\n}\n\n/**\n * Compile one condition to its `<column> <operator>` SQL fragment and the params\n * it binds.\n *\n * @remarks\n * Every operand is run through `encodeValue`, so a bound value matches the SQL\n * the column side compiles to. A flat column encodes operands with its DECLARED\n * schema type (a flat `json` column → `JSON.stringify`); a nested `FieldPath`\n * encodes each operand as the NATIVE scalar `json_extract` returns, derived from\n * the operand's runtime type (per-operand, since `between` / `any` / `none` can\n * mix types). `any` / `none` collapse an empty list to a constant (`0` matches\n * nothing, `1` matches all) with no params. A nested field with a null/undefined\n * operand under `equals` / `not` compiles to `IS NULL` / `IS NOT NULL` (no bound\n * param) instead of `= ?` / `!= ?`, matching the engine's treatment of a\n * present-but-null nested value.\n *\n * @param condition - The condition to compile\n * @param schema - The table's schema (for declared column types)\n * @returns The SQL fragment and its bound parameters\n *\n * @example\n * ```ts\n * fragment({ column: 'age', operator: 'above', values: [18], connector: 'and' }, schema)\n * // { sql: '\"age\" > ?', params: [18] }\n * ```\n */\nexport function fragment(condition: Condition, schema: TableSchema): CompiledSQL {\n\tconst column = fieldColumn(condition.column)\n\tconst nested = !isString(condition.column)\n\tconst declared = isString(condition.column) ? declaredType(condition.column, schema) : undefined\n\tconst encode = (value: unknown): SQLiteValue =>\n\t\tencodeValue(value, nested ? valueType(value) : (declared ?? 'json'))\n\tconst first = condition.values[0]\n\tconst second = condition.values[1]\n\t// A nested (`json_extract`) field with a null/undefined operand under\n\t// `equals` / `not`: `json_extract` collapses a stored JSON `null` to SQL\n\t// `NULL`, and `<col> = ?` / `!= ?` binding `NULL` never matches under SQL's\n\t// three-valued logic — so compile `IS NULL` / `IS NOT NULL` (no bound param)\n\t// to match the engine, which treats a present-but-null nested value as equal\n\t// to `null`. This is NESTED-ONLY: a flat null column is left as `= ?` / `!= ?`\n\t// (a null flat column decodes to absent, so the engine and `= NULL` already\n\t// agree on matching nothing).\n\tconst nullOperand = nested && (first === null || first === undefined)\n\tswitch (condition.operator) {\n\t\tcase 'equals':\n\t\t\tif (nullOperand) return { sql: column + ' IS NULL', params: [] }\n\t\t\treturn { sql: column + ' = ?', params: [encode(first)] }\n\t\tcase 'not':\n\t\t\tif (nullOperand) return { sql: column + ' IS NOT NULL', params: [] }\n\t\t\treturn { sql: column + ' != ?', params: [encode(first)] }\n\t\tcase 'above':\n\t\t\treturn { sql: column + ' > ?', params: [encode(first)] }\n\t\tcase 'below':\n\t\t\treturn { sql: column + ' < ?', params: [encode(first)] }\n\t\tcase 'from':\n\t\t\treturn { sql: column + ' >= ?', params: [encode(first)] }\n\t\tcase 'to':\n\t\t\treturn { sql: column + ' <= ?', params: [encode(first)] }\n\t\tcase 'between':\n\t\t\treturn { sql: column + ' BETWEEN ? AND ?', params: [encode(first), encode(second)] }\n\t\tcase 'like':\n\t\t\treturn { sql: column + ' LIKE ?', params: [encode(first)] }\n\t\tcase 'glob':\n\t\t\treturn { sql: column + ' GLOB ?', params: [encode(first)] }\n\t\tcase 'starts':\n\t\t\treturn {\n\t\t\t\tsql: column + \" LIKE ? ESCAPE '\\\\'\",\n\t\t\t\tparams: [(isString(first) ? escapeLike(first) : '') + '%'],\n\t\t\t}\n\t\tcase 'ends':\n\t\t\treturn {\n\t\t\t\tsql: column + \" LIKE ? ESCAPE '\\\\'\",\n\t\t\t\tparams: ['%' + (isString(first) ? escapeLike(first) : '')],\n\t\t\t}\n\t\tcase 'any':\n\t\t\tif (condition.values.length === 0) return { sql: '0', params: [] }\n\t\t\treturn {\n\t\t\t\tsql: column + ' IN (' + condition.values.map(() => '?').join(', ') + ')',\n\t\t\t\tparams: condition.values.map(encode),\n\t\t\t}\n\t\tcase 'none':\n\t\t\tif (condition.values.length === 0) return { sql: '1', params: [] }\n\t\t\treturn {\n\t\t\t\tsql: column + ' NOT IN (' + condition.values.map(() => '?').join(', ') + ')',\n\t\t\t\tparams: condition.values.map(encode),\n\t\t\t}\n\t\tcase 'absent':\n\t\t\treturn { sql: column + ' IS NULL', params: [] }\n\t\tcase 'present':\n\t\t\treturn { sql: column + ' IS NOT NULL', params: [] }\n\t}\n}\n\n/**\n * Fold the conditions into one WHERE clause, parenthesizing progressively\n * left-to-right so the grouping matches the engine's `matchesCriteria` fold.\n *\n * @remarks\n * The first condition's connector is ignored, per the {@link Condition} types.\n *\n * @param conditions - The conditions to fold\n * @param schema - The table's schema\n * @returns The `WHERE …` clause and its bound parameters, or an empty clause for zero conditions\n *\n * @example\n * ```ts\n * compileWhere([{ column: 'age', operator: 'from', values: [18], connector: 'and' }], schema)\n * // { sql: 'WHERE \"age\" >= ?', params: [18] }\n * ```\n */\nexport function compileWhere(conditions: readonly Condition[], schema: TableSchema): CompiledSQL {\n\tif (conditions.length === 0) return { sql: '', params: [] }\n\tconst head = fragment(conditions[0], schema)\n\tlet clause = head.sql\n\tconst params: SQLiteValue[] = [...head.params]\n\tfor (let index = 1; index < conditions.length; index += 1) {\n\t\tconst next = fragment(conditions[index], schema)\n\t\tconst operator = conditions[index].connector === 'or' ? 'OR' : 'AND'\n\t\tclause = '(' + clause + ' ' + operator + ' ' + next.sql + ')'\n\t\tparams.push(...next.params)\n\t}\n\treturn { sql: 'WHERE ' + clause, params }\n}\n\n/**\n * Compile the ORDER BY clause from the order terms, always ending with the\n * primary key as the final determinant.\n *\n * @remarks\n * The native `records` read then resolves ties in key order, matching a\n * primary-key-ordered `scan` and the core engine's stable `sortRows` over a\n * key-ordered scan (and IndexedDB's key-ordered reads), so a native read equals\n * the scan path (AGENTS §21 / §22 native ↔ engine parity). SQLite without an\n * `ORDER BY` returns rowid (insertion) order, and an explicit order alone breaks\n * ties by rowid too — both diverge from every key-ordered backend. The\n * tie-breaker is ASCENDING regardless of the explicit directions: the engine's\n * stable sort runs over key-ascending input, so equal rows stay in\n * ascending-key order whichever way the explicit terms point. Skipped when the\n * primary is already an explicit order term (no double-append).\n *\n * @param order - The explicit order terms, or `undefined`\n * @param schema - The table's schema (for the primary key)\n * @returns The `ORDER BY …` clause, or an empty string when there is nothing to order by\n *\n * @example\n * ```ts\n * compileOrder([{ column: 'age', direction: 'descending' }], schema)\n * // 'ORDER BY \"age\" DESC, \"id\"'\n * ```\n */\nexport function compileOrder(order: readonly Order[] | undefined, schema: TableSchema): string {\n\tconst terms = (order ?? []).map(\n\t\t(term) => fieldColumn(term.column) + (term.direction === 'descending' ? ' DESC' : ' ASC'),\n\t)\n\tconst ordersByPrimary = (order ?? []).some(\n\t\t(term) => isString(term.column) && term.column === schema.primary,\n\t)\n\tif (!ordersByPrimary) terms.push(quote(schema.primary))\n\treturn terms.length === 0 ? '' : 'ORDER BY ' + terms.join(', ')\n}\n\n/**\n * Compile the LIMIT / OFFSET clause.\n *\n * @remarks\n * An offset without a limit uses `LIMIT -1` (SQLite's \"no limit\") so OFFSET is\n * still honored.\n *\n * @param limit - The maximum row count, or `undefined`\n * @param offset - The row count to skip, or `undefined`\n * @returns The `LIMIT …` clause and its bound parameters, or an empty clause when neither is set\n *\n * @example\n * ```ts\n * compilePage(undefined, 5) // { sql: 'LIMIT -1 OFFSET ?', params: [5] }\n * ```\n */\nexport function compilePage(limit: number | undefined, offset: number | undefined): CompiledSQL {\n\tif (limit !== undefined && offset !== undefined) {\n\t\treturn { sql: 'LIMIT ? OFFSET ?', params: [limit, offset] }\n\t}\n\tif (limit !== undefined) return { sql: 'LIMIT ?', params: [limit] }\n\tif (offset !== undefined) return { sql: 'LIMIT -1 OFFSET ?', params: [offset] }\n\treturn { sql: '', params: [] }\n}\n\n/**\n * Compile a {@link Criteria} into the SQL clause that follows a table name, with\n * its bound parameters in clause order.\n *\n * @remarks\n * The driver's native `records` / `count` path: it assembles\n * `[where, orderBy, limitOffset]` (each possibly empty) into one clause so a\n * `SELECT * FROM <table> <clause>` runs the whole read in the engine instead of\n * over a JS `scan`. The WHERE fold is parenthesized **left-to-right** to mirror\n * the core engine's `matchesCriteria` (not SQL's native AND-over-OR precedence),\n * so a native and an engine read return identical rows. Each operand is encoded\n * via `encodeValue`: a flat column uses its declared schema type, while a nested\n * `FieldPath` (a `json_extract` read) encodes each operand as the native scalar\n * the extract returns — derived from the operand's runtime type — so it compares.\n * The 15 operators map per the databases guide's operator table, with\n * `starts` / `ends` using `LIKE … ESCAPE '\\'` and an empty `any` / `none` list\n * collapsing to a constant. A `undefined` criteria (or one with no parts)\n * compiles to an empty clause.\n *\n * @param criteria - The read specification, or `undefined` for all rows\n * @param schema - The table's schema (column types for operand encoding)\n * @returns The SQL tail and its bound parameters\n *\n * @example\n * ```ts\n * compileCriteria({ conditions: [{ column: 'age', operator: 'from', values: [18], connector: 'and' }] }, schema)\n * // { sql: 'WHERE \"age\" >= ? ORDER BY \"id\"', params: [18] }\n * ```\n */\nexport function compileCriteria(criteria: Criteria | undefined, schema: TableSchema): CompiledSQL {\n\tconst where = compileWhere(criteria?.conditions ?? [], schema)\n\tconst orderBy = compileOrder(criteria?.order, schema)\n\tconst page = compilePage(criteria?.limit, criteria?.offset)\n\tconst sql = [where.sql, orderBy, page.sql].filter((part) => part !== '').join(' ')\n\treturn { sql, params: [...where.params, ...page.params] }\n}\n","import type {\n\tColumnSchema,\n\tColumnType,\n\tCriteria,\n\tDriverInterface,\n\tDriverMeta,\n\tKey,\n\tMigration,\n\tRow,\n\tTableSchema,\n\tTransactionInterface,\n} from '@src/core'\nimport { DatabaseError, MemoryDriver, extractKey } from '@src/core'\nimport { isArray, isBoolean, isRecord, isString } from '@orkestrel/contract'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\n/**\n * A persistent {@link DriverInterface} backed by a single JSON file — the\n * reference {@link MemoryDriver} plus file load / flush.\n *\n * @remarks\n * A decorator, not a reimplementation: every primitive delegates to an inner\n * {@link MemoryDriver}, so querying, key-order `scan` / `keys`, and capture-replay\n * `snapshot` are inherited unchanged — this layer adds only persistence. `open`\n * loads the file into memory; every mutation (`write` / `delete` / `clear`) flushes\n * the whole store back. The file is one JSON object, `{ meta?: DriverMeta, tables: {\n * [name]: rows } }` — `meta` is present only once the store has been `stamp`ed\n * (an unstamped store serializes the old `{ tables }` shape, preserving\n * backward compatibility); a per-table array of rows, each row carrying its own\n * primary (the table contract), so the key is recovered on load with\n * {@link extractKey} and the file need not store it. The parsed JSON crosses the\n * boundary as `unknown` and is narrowed with {@link isRecord} / {@link extractKey},\n * never asserted (AGENTS §14): a missing, corrupt, or wrong-shaped file starts\n * empty rather than throwing, and a malformed row (or malformed `meta`) is\n * skipped/dropped rather than thrown on. It is scan-only — it implements none of\n * the optional native `records` / `count` / `aggregate` hooks, so the core engine\n * over `scan` answers every query. For development, small datasets, and portable /\n * inspectable data; for large or concurrent workloads reach for a SQLite-backed\n * driver.\n *\n * A failure in the write path ({@link JSONDriver.#serialize} — `mkdir` /\n * `writeFile` / `rename`) is wrapped and rethrown as `DatabaseError` `DRIVER`,\n * carrying the target `path` in its context; the read path ({@link\n * JSONDriver.#load}) tolerance above is a separate, deliberate contract and is\n * never touched by this wrapping.\n */\nexport class JSONDriver implements DriverInterface {\n\treadonly #path: string\n\treadonly #memory = new MemoryDriver()\n\t#schema: readonly TableSchema[] = []\n\t#meta: DriverMeta | undefined\n\t#flushCount = 0\n\t// Serializes #flush calls — each queued flush awaits the prior one before\n\t// serializing state, so the persisted snapshot always reflects the latest\n\t// memory state (see #flush @remarks).\n\t#chain: Promise<void> = Promise.resolve()\n\t// Set while a transaction() handle is active — suppresses #flush from\n\t// write/delete/clear so N mutations under the handle cost one file write\n\t// (on commit) instead of N (see transaction @remarks). Cleared by\n\t// commit/rollback, which is also how double-settle is detected.\n\t#deferring = false\n\n\tconstructor(path: string) {\n\t\tthis.#path = path\n\t}\n\n\tasync open(schema: readonly TableSchema[]): Promise<void> {\n\t\tthis.#schema = schema\n\t\tawait this.#memory.open(schema)\n\t\tawait this.#load()\n\t}\n\n\tasync close(): Promise<void> {\n\t\tawait this.#memory.close()\n\t}\n\n\tasync read(table: string, key: Key): Promise<Row | undefined> {\n\t\treturn this.#memory.read(table, key)\n\t}\n\n\tasync write(table: string, key: Key, row: Row): Promise<void> {\n\t\tawait this.#memory.write(table, key, row)\n\t\tif (!this.#deferring) await this.#flush()\n\t}\n\n\tasync delete(table: string, key: Key): Promise<boolean> {\n\t\tconst removed = await this.#memory.delete(table, key)\n\t\tif (!this.#deferring) await this.#flush()\n\t\treturn removed\n\t}\n\n\tkeys(table: string): Promise<readonly Key[]> {\n\t\treturn this.#memory.keys(table)\n\t}\n\n\tscan(table: string): AsyncIterable<Row> {\n\t\treturn this.#memory.scan(table)\n\t}\n\n\t/**\n\t * Natively filtered lazy iteration — delegates to the inner {@link MemoryDriver}.\n\t *\n\t * @remarks\n\t * Semantics are the memory driver's own: `criteria.conditions` filters, `offset`\n\t * / `limit` page lazily, and `criteria.order` is ignored (streaming yields key\n\t * order; sorted output is `records()`'s job).\n\t *\n\t * @param table - The table to stream\n\t * @param criteria - The filter / offset / limit to apply lazily\n\t */\n\tstream(table: string, criteria: Criteria): AsyncIterable<Row> {\n\t\treturn this.#memory.stream(table, criteria)\n\t}\n\n\tasync clear(table: string): Promise<void> {\n\t\tawait this.#memory.clear(table)\n\t\tif (!this.#deferring) await this.#flush()\n\t}\n\n\t/**\n\t * Begin a native transaction — flush-coalescing over the inner {@link MemoryDriver}.\n\t *\n\t * @remarks\n\t * Single-writer: throws `DatabaseError` `CONFLICT` if a transaction is already\n\t * active — this driver does not support nesting. On begin, captures the inner\n\t * memory rollback thunk via `#memory.snapshot()` and suppresses per-mutation\n\t * `#flush` — `write` / `delete` / `clear` still mutate memory but no longer\n\t * touch the file, so N mutations under the handle cost ONE file write instead\n\t * of N. `commit()` releases the suppression and performs that one atomic\n\t * `#flush()`, persisting the transaction's net state. `rollback()` restores\n\t * memory via the captured snapshot thunk, then `#flush()`s so the file reflects\n\t * the restored state. Outside a transaction, behavior is unchanged — every\n\t * mutation flushes on its own. Calling `commit` / `rollback` a second time (on\n\t * either method, in either order) throws `DatabaseError` `CONFLICT`.\n\t *\n\t * @returns A {@link TransactionInterface} handle to `commit` or `rollback`\n\t */\n\tasync transaction(): Promise<TransactionInterface> {\n\t\tif (this.#deferring) {\n\t\t\tthrow new DatabaseError('CONFLICT', 'A transaction is already active on this driver', {})\n\t\t}\n\t\tconst rollback = await this.#memory.snapshot()\n\t\tthis.#deferring = true\n\t\tlet settled = false\n\t\treturn {\n\t\t\tcommit: async () => {\n\t\t\t\tif (settled) {\n\t\t\t\t\tthrow new DatabaseError('CONFLICT', 'Transaction already settled', {})\n\t\t\t\t}\n\t\t\t\tsettled = true\n\t\t\t\tthis.#deferring = false\n\t\t\t\tawait this.#flush()\n\t\t\t},\n\t\t\trollback: async () => {\n\t\t\t\tif (settled) {\n\t\t\t\t\tthrow new DatabaseError('CONFLICT', 'Transaction already settled', {})\n\t\t\t\t}\n\t\t\t\tsettled = true\n\t\t\t\tawait rollback()\n\t\t\t\tthis.#deferring = false\n\t\t\t\tawait this.#flush()\n\t\t\t},\n\t\t}\n\t}\n\n\tasync snapshot(tables?: readonly string[]): Promise<() => Promise<void>> {\n\t\tconst rollback = await this.#memory.snapshot(tables)\n\t\t// Restore the in-memory state, then re-persist it — the file was rewritten\n\t\t// on each write during the scope, so a rollback must flush the restored state.\n\t\treturn async () => {\n\t\t\tawait rollback()\n\t\t\tawait this.#flush()\n\t\t}\n\t}\n\n\tasync meta(): Promise<DriverMeta | undefined> {\n\t\treturn this.#meta\n\t}\n\n\t/**\n\t * Persist `meta` verbatim for a later `meta()` to return.\n\t *\n\t * @remarks\n\t * Respects the same defer-flush suppression as `write` / `delete` / `clear`\n\t * (see {@link JSONDriver.transaction} @remarks) — stamping inside an active\n\t * transaction updates memory but does not flush until the transaction settles.\n\t *\n\t * @param meta - The {@link DriverMeta} to persist\n\t */\n\tasync stamp(meta: DriverMeta): Promise<void> {\n\t\tthis.#meta = meta\n\t\tif (!this.#deferring) await this.#flush()\n\t}\n\n\t/**\n\t * Apply a {@link Migration} plan by delegating to the inner {@link MemoryDriver},\n\t * then persist the migrated state.\n\t *\n\t * @remarks\n\t * The inner `MemoryDriver.migrate` applies each step (adding/removing tables,\n\t * adding/removing columns from stored rows, no-op index steps) and throws\n\t * `DatabaseError` `MIGRATION` for a step referencing an unknown table — that\n\t * error propagates untouched. `table.add` / `table.remove` steps also update\n\t * this driver's own declared `#schema`, mirroring the bookkeeping `open` does,\n\t * so a subsequent `#flush` / `#load` round-trip includes (or drops) the table.\n\t * A successful migration ends with one atomic `#flush()` so the new state\n\t * survives a close and reopen. A multi-step plan applies its steps\n\t * sequentially and is NOT atomic — a failure partway through a plan leaves\n\t * the earlier steps already applied.\n\t *\n\t * @param plan - The migration plan to apply\n\t */\n\tasync migrate(plan: Migration): Promise<void> {\n\t\tawait this.#memory.migrate?.(plan)\n\t\tlet schema = this.#schema\n\t\tfor (const step of plan.steps) {\n\t\t\tif (step.operation === 'table.add') {\n\t\t\t\tschema = schema.some((table) => table.name === step.table.name)\n\t\t\t\t\t? schema\n\t\t\t\t\t: [...schema, step.table]\n\t\t\t} else if (step.operation === 'table.remove') {\n\t\t\t\tschema = schema.filter((table) => table.name !== step.table)\n\t\t\t}\n\t\t}\n\t\tthis.#schema = schema\n\t\tawait this.#flush()\n\t}\n\n\t// === Private\n\n\t// Load the file into memory; a missing / corrupt / wrong-shaped file starts\n\t// empty (never throws). Each entry is narrowed via isRecord and its key recovered\n\t// with extractKey from the schema's primary column; bad entries are skipped. A\n\t// `meta` block is narrowed with the same tolerance — a malformed or absent\n\t// `meta` leaves #meta undefined (unstamped) rather than throwing, which is how\n\t// an old-format file (no `meta` key) is distinguished from a stamped one.\n\tasync #load(): Promise<void> {\n\t\tlet raw: string\n\t\ttry {\n\t\t\traw = await readFile(this.#path, 'utf-8')\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw)\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\tif (!isRecord(parsed) || !isRecord(parsed.tables)) return\n\t\tconst tables = parsed.tables\n\t\tfor (const table of this.#schema) {\n\t\t\tconst rows = tables[table.name]\n\t\t\tif (!Array.isArray(rows)) continue\n\t\t\tfor (const entry of rows) {\n\t\t\t\tif (!isRecord(entry)) continue\n\t\t\t\tconst key = extractKey(entry, table.primary)\n\t\t\t\tif (key === undefined) continue\n\t\t\t\tawait this.#memory.write(table.name, key, entry)\n\t\t\t}\n\t\t}\n\t\t// The closed set of portable column types (mirrors core's ColumnType union) —\n\t\t// used to narrow a loaded meta's column.type without trusting the file.\n\t\tconst COLUMN_TYPES: readonly ColumnType[] = [\n\t\t\t'text',\n\t\t\t'integer',\n\t\t\t'real',\n\t\t\t'boolean',\n\t\t\t'json',\n\t\t\t'blob',\n\t\t]\n\t\tconst isColumnType = (value: unknown): value is ColumnType =>\n\t\t\tisString(value) && COLUMN_TYPES.some((type) => type === value)\n\t\tconst isColumnSchema = (value: unknown): value is ColumnSchema =>\n\t\t\tisRecord(value) &&\n\t\t\tisString(value.name) &&\n\t\t\tisColumnType(value.type) &&\n\t\t\tisBoolean(value.nullable)\n\t\tconst isIndexGroup = (value: unknown): value is readonly string[] =>\n\t\t\tisArray(value) && value.every(isString)\n\t\tconst isTableSchema = (value: unknown): value is TableSchema =>\n\t\t\tisRecord(value) &&\n\t\t\tisString(value.name) &&\n\t\t\tisString(value.primary) &&\n\t\t\tisArray(value.columns) &&\n\t\t\tvalue.columns.every(isColumnSchema) &&\n\t\t\tisArray(value.indexes) &&\n\t\t\tvalue.indexes.every(isIndexGroup)\n\t\tif (isRecord(parsed.meta)) {\n\t\t\tconst version = parsed.meta.version\n\t\t\tconst schema = parsed.meta.schema\n\t\t\tif (\n\t\t\t\ttypeof version === 'number' &&\n\t\t\t\tNumber.isFinite(version) &&\n\t\t\t\tisArray(schema) &&\n\t\t\t\tschema.every(isTableSchema)\n\t\t\t) {\n\t\t\t\tthis.#meta = { version, schema }\n\t\t\t}\n\t\t}\n\t}\n\n\t// Queue a flush behind #chain — see #flush @remarks for why.\n\tasync #flush(): Promise<void> {\n\t\tconst next = this.#chain.then(() => this.#serialize())\n\t\t// Swallow so a failed flush doesn't leave #chain permanently rejected and\n\t\t// block every later flush; the caller of THIS #flush still observes the\n\t\t// rejection via `next` below.\n\t\tthis.#chain = next.catch(() => {})\n\t\tawait next\n\t}\n\n\t// Drain every declared table's rows from memory (in key order) and write the\n\t// whole store back as one pretty-printed JSON object, creating the directory.\n\t//\n\t// @remarks\n\t// Written atomically: the payload lands in a sibling temp file (same directory,\n\t// so the platform rename is atomic) and is then renamed onto `#path`. A crash\n\t// mid-flush can no longer truncate or corrupt the previous good file — POSIX\n\t// `rename` replaces the destination in one indivisible step, so a reader always\n\t// sees either the old file or the fully-written new one, never a partial write.\n\t// `#flush` serializes calls to this method through `#chain` — each flush AWAITS\n\t// its predecessor before draining `#memory` and writing, so the payload always\n\t// reflects the latest memory state. Without this, overlapping flushes triggered\n\t// by non-awaited concurrent mutations could serialize out of order and persist a\n\t// stale snapshot as the \"latest\" file. `meta` is included in the payload only\n\t// once the store has been stamped, so an unstamped store keeps serializing the\n\t// old `{ tables }` shape (backward compat). Any failure in this write path\n\t// (`mkdir` / `writeFile` / `rename`) is wrapped as `DatabaseError` `DRIVER`\n\t// carrying `path` in its context, after the temp-file cleanup below runs.\n\tasync #serialize(): Promise<void> {\n\t\tconst tables: Record<string, readonly Row[]> = {}\n\t\tfor (const table of this.#schema) {\n\t\t\tconst rows: Row[] = []\n\t\t\tfor await (const row of this.#memory.scan(table.name)) rows.push(row)\n\t\t\ttables[table.name] = rows\n\t\t}\n\t\tthis.#flushCount += 1\n\t\tconst temp = `${this.#path}.${process.pid}.${this.#flushCount}.tmp`\n\t\tconst payload = this.#meta === undefined ? { tables } : { meta: this.#meta, tables }\n\t\ttry {\n\t\t\tawait mkdir(dirname(this.#path), { recursive: true })\n\t\t\tawait writeFile(temp, JSON.stringify(payload, null, 2), 'utf-8')\n\t\t\tawait rename(temp, this.#path)\n\t\t} catch (error) {\n\t\t\tawait rm(temp, { force: true }).catch(() => {})\n\t\t\tthrow new DatabaseError('DRIVER', 'Failed to persist the database file', {\n\t\t\t\tpath: this.#path,\n\t\t\t\tcause: error,\n\t\t\t})\n\t\t}\n\t}\n}\n","import type { DriverInterface } from '@src/core'\nimport { JSONDriver } from './drivers/JSONDriver.js'\n\n/**\n * Create a persistent JSON-file {@link DriverInterface} for the core database layer.\n *\n * @remarks\n * Pass it to `createDatabase` from `@src/core` to run the whole typed database +\n * relations stack against a single JSON file instead of memory — the `Database` /\n * `Table` / `Query` / relations API is unchanged; only where the bytes live changes.\n * The driver is the reference `MemoryDriver` plus JSON-file persistence: `open` loads\n * the file, every mutation flushes the whole store back, and querying runs through\n * the core engine over `scan` (it is scan-only — no native `records` / `count` /\n * `aggregate`). A missing, corrupt, or wrong-shaped file starts empty rather than\n * throwing.\n *\n * @param path - The JSON file path data is loaded from and flushed to\n * @returns A {@link DriverInterface} backed by a JSON file\n *\n * @example\n * ```ts\n * import { createDatabase } from '@orkestrel/database'\n * import { stringShape } from '@orkestrel/contract'\n * import { createJSONDriver } from '@orkestrel/database/server'\n *\n * const db = createDatabase({\n * \tdriver: createJSONDriver('data/app.json'),\n * \ttables: { users: { id: stringShape(), name: stringShape() } },\n * })\n * await db.table('users').set({ id: 'u1', name: 'Ada' }) // persisted to app.json\n * ```\n */\nexport function createJSONDriver(path: string): DriverInterface {\n\treturn new JSONDriver(path)\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;;AAmBwB,OAAO,OAAO;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAgBD,SAAS,SAAS,OAAO;CACxB,OAAO,OAAO,UAAU;AACzB;;AAmBA,SAAS,UAAU,OAAO;CACzB,OAAO,OAAO,UAAU;AACzB;;;;;;;;AA2GA,SAAS,SAAS,OAAO;CACxB,OAAO,OAAO,UAAU,YAAY,UAAU;AAC/C;;;;;;;;;;;;;;;;;;;AAmBA,SAAS,SAAS,OAAO;CACxB,MAAM,UAAU,cAAc;EAC7B,IAAI,CAAC,SAAS,KAAK,KAAK,QAAQ,KAAK,GAAG,OAAO;EAC/C,MAAM,YAAY,OAAO,eAAe,KAAK;EAC7C,OAAO,cAAc,QAAQ,OAAO,eAAe,SAAS,MAAM;CACnE,CAAC;CACD,OAAO,QAAQ,WAAW,QAAQ;AACnC;;AAkBA,SAAS,QAAQ,OAAO;CACvB,OAAO,MAAM,QAAQ,KAAK;AAC3B;;;;;;;;;;;;;;;;;;;;;;;;AA6PA,SAAS,QAAQ,UAAU;CAC1B,IAAI;EACH,OAAO;GACN,SAAS;GACT,OAAO,SAAS;EACjB;CACD,SAAS,QAAQ;EAChB,IAAI,kBAAkB,OAAO,OAAO;GACnC,SAAS;GACT,OAAO;EACR;EACA,IAAI,UAAU;EACd,IAAI;GACH,UAAU,OAAO,MAAM;EACxB,QAAQ,CAAC;EACT,OAAO;GACN,SAAS;GACT,OAAO,IAAI,MAAM,OAAO;EACzB;CACD;AACD;;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,GAAG,KAAK,KAAK,GAAG;GACpE,OAAO,MAAM,QAAQ;EACtB;EACA,KAAKQ,eAAe;EACpB,MAAM,OAAO,GAAG,KAAKT,MAAM,GAAG,QAAQ,IAAI,GAAG,KAAKS,YAAY;EAC9D,MAAM,UAAU,KAAKH,UAAU,KAAA,IAAY,EAAE,OAAO,IAAI;GAAE,MAAM,KAAKA;GAAO;EAAO;EACnF,IAAI;GACH,OAAA,GAAA,iBAAA,MAAA,EAAA,GAAA,UAAA,QAAA,CAAoB,KAAKN,KAAK,GAAG,EAAE,WAAW,KAAK,CAAC;GACpD,OAAA,GAAA,iBAAA,UAAA,CAAgB,MAAM,KAAK,UAAU,SAAS,MAAM,CAAC,GAAG,OAAO;GAC/D,OAAA,GAAA,iBAAA,OAAA,CAAa,MAAM,KAAKA,KAAK;EAC9B,SAAS,OAAO;GACf,OAAA,GAAA,iBAAA,GAAA,CAAS,MAAM,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;GAC9C,MAAM,IAAI,UAAA,cAAc,UAAU,uCAAuC;IACxE,MAAM,KAAKA;IACX,OAAO;GACR,CAAC;EACF;CACD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACjUA,SAAgB,iBAAiB,MAA+B;CAC/D,OAAO,IAAI,WAAW,IAAI;AAC3B"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The value domain a SQLite binding accepts as a bound parameter and returns
|
|
3
|
+
* from a row.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* Mirrors SQLite's storage classes (`NULL`, `INTEGER`, `REAL`, `TEXT`, `BLOB`)
|
|
7
|
+
* at the TypeScript boundary: `null`, `number` / `bigint` for integer and
|
|
8
|
+
* floating-point values, `string` for text, and `Uint8Array` for blobs. This
|
|
9
|
+
* type is pure — it names the shape a value must have to cross the binding,
|
|
10
|
+
* independent of any concrete sqlite package (`node:sqlite`, `better-sqlite3`,
|
|
11
|
+
* etc.), so a driver can encode/decode against it without importing one.
|
|
12
|
+
*/
|
|
13
|
+
export type SQLiteValue = null | number | bigint | string | Uint8Array;
|
|
14
|
+
/**
|
|
15
|
+
* One row as a SQLite binding returns it — a plain object keyed by column name.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* Every column value is a {@link SQLiteValue}. The SQLite driver decodes each
|
|
19
|
+
* raw row into this shape before handing it to the core query engine; nothing
|
|
20
|
+
* above the driver ever sees SQLite's native row representation directly.
|
|
21
|
+
*/
|
|
22
|
+
export type SQLiteRow = Record<string, SQLiteValue>;
|
|
23
|
+
/**
|
|
24
|
+
* A parameterized SQL fragment or statement plus its bind values.
|
|
25
|
+
*
|
|
26
|
+
* @remarks
|
|
27
|
+
* Produced by the pure SQL compilers (`compilers.ts`) that turn a core
|
|
28
|
+
* `Criteria` (or a table definition) into SQL text with `?` placeholders, and
|
|
29
|
+
* consumed by the SQLite driver, which runs `sql` with `params` bound in
|
|
30
|
+
* order — no further assembly. Keeping `sql` and `params` together prevents
|
|
31
|
+
* the two from drifting apart across compile and execute.
|
|
32
|
+
*/
|
|
33
|
+
export interface CompiledSQL {
|
|
34
|
+
readonly sql: string;
|
|
35
|
+
readonly params: readonly SQLiteValue[];
|
|
36
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@orkestrel/database",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "A typed database abstraction for the @orkestrel line — a single core engine over pluggable storage drivers. Part of the @orkestrel line.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"database",
|
|
7
|
+
"driver",
|
|
8
|
+
"query",
|
|
9
|
+
"server",
|
|
10
|
+
"storage",
|
|
11
|
+
"typescript"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/orkestrel/database#readme",
|
|
14
|
+
"bugs": "https://github.com/orkestrel/database/issues",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/orkestrel/database.git"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"README.md"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"main": "./dist/src/core/index.js",
|
|
27
|
+
"types": "./dist/src/core/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/src/core/index.d.ts",
|
|
31
|
+
"import": "./dist/src/core/index.js",
|
|
32
|
+
"default": "./dist/src/core/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./server": {
|
|
35
|
+
"types": "./dist/src/server/index.d.ts",
|
|
36
|
+
"require": "./dist/src/server/index.cjs",
|
|
37
|
+
"default": "./dist/src/server/index.cjs"
|
|
38
|
+
},
|
|
39
|
+
"./package.json": "./package.json"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"clean": "node -e \"try{require('node:fs').rmSync('dist',{recursive:true,force:true})}catch{}\"",
|
|
46
|
+
"copy": "node -e \"const fs=require('node:fs'),p=require('node:path'),a=process.argv[1],b=process.argv[2];fs.mkdirSync(p.dirname(b),{recursive:true});fs.cpSync(a,b,{force:true});console.log('Copied: '+a+' to '+b)\"",
|
|
47
|
+
"tmp:txt": "node -e \"const fs=require('node:fs'),p=require('node:path');function walk(d){for(const e of fs.readdirSync(d,{withFileTypes:true})){const f=p.join(d,e.name);if(e.isDirectory()){walk(f)}else if(!e.name.endsWith('.md')&&!e.name.endsWith('.txt')){const t=f+'.txt';if(!fs.existsSync(t)){fs.renameSync(f,t)}else{console.warn('Skipping '+f+' — target exists: '+t)}}}}try{walk('tmp')}catch(e){if(e.code!=='ENOENT')throw e}\"",
|
|
48
|
+
"lint": "oxlint --config .oxlintrc.json --fix .",
|
|
49
|
+
"check": "tsc --noEmit --project tsconfig.json",
|
|
50
|
+
"check:src": "npm run check:src:core && npm run check:src:server",
|
|
51
|
+
"check:src:core": "tsc --noEmit -p configs/src/tsconfig.core.json",
|
|
52
|
+
"check:src:server": "tsc --noEmit -p configs/src/tsconfig.server.json",
|
|
53
|
+
"format": "oxfmt --config .oxfmtrc.json --write .",
|
|
54
|
+
"format:check": "oxfmt --config .oxfmtrc.json --check .",
|
|
55
|
+
"lint:check": "oxlint --config .oxlintrc.json .",
|
|
56
|
+
"test": "npm run test:src && npm run test:guides",
|
|
57
|
+
"test:src": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:core --project src:server",
|
|
58
|
+
"test:src:core": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:core",
|
|
59
|
+
"test:src:server": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:server",
|
|
60
|
+
"test:guides": "vitest run --config vite.config.ts --reporter=dot --project guides",
|
|
61
|
+
"build": "npm run clean && npm run build:src",
|
|
62
|
+
"build:src": "npm run build:src:core && npm run build:src:server",
|
|
63
|
+
"build:src:core": "vite build --config configs/src/vite.core.config.ts && tsc -p configs/src/tsconfig.core.json",
|
|
64
|
+
"build:src:server": "vite build --config configs/src/vite.server.config.ts && tsc -p configs/src/tsconfig.server.json",
|
|
65
|
+
"prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run check && npm run build && npm test"
|
|
66
|
+
},
|
|
67
|
+
"dependencies": {
|
|
68
|
+
"@orkestrel/abort": "^0.0.1",
|
|
69
|
+
"@orkestrel/contract": "^0.0.1",
|
|
70
|
+
"@orkestrel/emitter": "^0.0.1"
|
|
71
|
+
},
|
|
72
|
+
"devDependencies": {
|
|
73
|
+
"@orkestrel/guide": "^0.0.1",
|
|
74
|
+
"@types/node": "^26.1.1",
|
|
75
|
+
"oxfmt": "^0.58.0",
|
|
76
|
+
"oxlint": "^1.73.0",
|
|
77
|
+
"typescript": "^6.0.3",
|
|
78
|
+
"vite": "^8.1.4",
|
|
79
|
+
"vitest": "^4.1.10"
|
|
80
|
+
},
|
|
81
|
+
"engines": {
|
|
82
|
+
"node": ">=24"
|
|
83
|
+
}
|
|
84
|
+
}
|