@orkestrel/markdown 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#document"],"sources":["../../../src/core/constants.ts","../../../node_modules/@orkestrel/contract/dist/src/core/index.js","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/parsers.ts","../../../src/core/shapers.ts","../../../src/core/Markdown.ts","../../../src/core/factories.ts"],"sourcesContent":["/**\n * The URL schemes `renderHTML` permits on a link `href` - anything else (notably\n * `javascript:`, `data:`, `vbscript:`, `file:`) is dropped to an empty `href` so a\n * hostile link can never execute. Frozen, lower-case; a relative / anchor /\n * scheme-less `href` (no `scheme:` prefix) is always allowed.\n */\nexport const SAFE_URL_SCHEMES: ReadonlySet<string> = new Set(['http', 'https', 'mailto', 'tel'])\n\n/**\n * The maximum recursion depth the parse pipeline (`parseDocument` and its\n * `parsers.ts` helpers) and the `helpers.ts` traversal / render functions\n * (`renderHTML`, `renderMarkdown`, `walkNodes`, `foldNode`) honor before degrading to\n * literal text - bounds blockquote nesting, inline nesting (emphasis / links), and\n * traversal/render recursion so pathological or hostile input (deeply nested\n * blockquotes, runaway emphasis) cannot exhaust the call stack. Past this depth the\n * parser treats the remaining content as literal text instead of recursing further.\n */\nexport const MAX_DEPTH = 64\n","//#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 { Guard } from '@orkestrel/contract'\nimport type {\n\tBlockNode,\n\tBlockquoteNode,\n\tCodeBlockNode,\n\tCodeSpanNode,\n\tEmphasisNode,\n\tHeadingNode,\n\tInlineNode,\n\tLinkNode,\n\tListNode,\n\tMarkdownDocument,\n\tMarkdownNode,\n\tParagraphNode,\n\tTableNode,\n\tTextNode,\n\tThematicBreakNode,\n} from './types.js'\nimport {\n\tarrayOf,\n\tisBoolean,\n\tisEmptyString,\n\tisNumber,\n\tisString,\n\tliteralOf,\n\tlazyOf,\n\trecordOf,\n\tunionOf,\n} from '@orkestrel/contract'\nimport { splitTableRow } from './helpers.js'\n\n// AGENTS section 14: guards are total. This file owns two predicate families:\n// line / string structural predicates that test raw strings during parsing\n// (isWhitespace, isEscapable, isQuote, isFenceClose, isThematicBreak,\n// isTableStart), and node guards that narrow a MarkdownNode to one parsed\n// block / inline variant by its element tag.\n\n/**\n * Whether `character` is an inline whitespace character (space / tab / newline) - the\n * emphasis flanking rule's space test.\n *\n * @param character - The character to test\n * @returns `true` when it is inline whitespace\n */\nexport function isWhitespace(character: string): boolean {\n\treturn character === ' ' || character === '\\t' || character === '\\n'\n}\n\n/**\n * Whether `character` is escapable by a leading backslash - the ASCII punctuation\n * markdown gives meaning to (so `\\*` becomes `*` but `\\.` stays `\\.`).\n *\n * @param character - The single character after a backslash\n * @returns `true` when a backslash before it is an escape\n */\nexport function isEscapable(character: string): boolean {\n\treturn /[\\\\`*_{}[\\]()#+\\-.!>~|]/.test(character)\n}\n\n/**\n * Whether `line` is blank - empty, or containing only whitespace - the markdown\n * definition of a blank line that block parsing uses to separate paragraphs, skip\n * gaps, and end list continuations.\n *\n * @param line - The candidate line\n * @returns `true` when the line is blank\n */\nexport function isBlankLine(line: string): boolean {\n\treturn isEmptyString(line.trim())\n}\n\n/**\n * Whether `line` is a blockquote line (`>` optionally indented up to three spaces) -\n * its content is de-quoted by {@link stripQuote}.\n *\n * @param line - The candidate line\n * @returns `true` when the line begins a blockquote\n */\nexport function isQuote(line: string): boolean {\n\treturn /^\\s{0,3}>/.test(line)\n}\n\n/**\n * Whether `line` closes a fence opened by `marker` - the same fence character, a run\n * at least as long, and nothing else but surrounding whitespace.\n *\n * @param line - The candidate closing line\n * @param marker - The opening fence's marker run (from {@link extractFence})\n * @returns `true` when `line` closes the fence\n */\nexport function isFenceClose(line: string, marker: string): boolean {\n\tconst character = marker[0] === '~' ? '~' : '`'\n\tlet index = 0\n\twhile (index < line.length && isFenceWhitespace(line[index])) index++\n\tlet run = 0\n\twhile (index < line.length && line[index] === character) {\n\t\trun++\n\t\tindex++\n\t}\n\tif (run < marker.length) return false\n\twhile (index < line.length && isFenceWhitespace(line[index])) index++\n\treturn index === line.length\n}\n\n/**\n * Whether `character` is a regex-`\\s`-equivalent whitespace character - the\n * character class {@link isFenceClose}'s scan treats as surrounding padding.\n *\n * @param character - The single character to test, or `undefined` past the end of a line\n * @returns `true` when it is whitespace\n */\nexport function isFenceWhitespace(character: string | undefined): boolean {\n\treturn (\n\t\tcharacter === ' ' ||\n\t\tcharacter === '\\t' ||\n\t\tcharacter === '\\n' ||\n\t\tcharacter === '\\r' ||\n\t\tcharacter === '\\f' ||\n\t\tcharacter === '\\v'\n\t)\n}\n\n/**\n * Whether `line` is a thematic break (horizontal rule) - three or more of the SAME\n * marker `-`, `*`, or `_` (optionally space-separated) and nothing else (`---`,\n * `***`, `___`, `- - -`).\n *\n * @param line - The candidate line\n * @returns `true` when the line is a thematic break\n */\nexport function isThematicBreak(line: string): boolean {\n\tconst stripped = line.trim().replace(/\\s+/g, '')\n\tif (stripped.length < 3) return false\n\tconst marker = stripped[0]\n\tif (marker !== '-' && marker !== '*' && marker !== '_') return false\n\treturn [...stripped].every((character) => character === marker)\n}\n\n/**\n * Whether the pair (`header`, `delimiter`) opens a GFM table - `delimiter` is a row of\n * `|`-separated cells each matching `:?-+:?`, the GFM rule that a table requires a\n * header row IMMEDIATELY followed by a delimiter row.\n *\n * @param header - The candidate header line\n * @param delimiter - The line after it (the candidate delimiter)\n * @returns `true` when the two lines open a table\n */\nexport function isTableStart(header: string, delimiter: string | undefined): boolean {\n\tif (delimiter === undefined || !header.includes('|')) return false\n\tconst cells = splitTableRow(delimiter)\n\tif (cells.length === 0) return false\n\treturn cells.every((cell) => /^:?-+:?$/.test(cell.trim()))\n}\n\n// === Block guards\n\n/** Determine whether a node is a heading block. */\nexport function isHeadingNode(node: MarkdownNode): node is HeadingNode {\n\treturn node.element === 'heading'\n}\n\n/** Determine whether a node is a paragraph block. */\nexport function isParagraphNode(node: MarkdownNode): node is ParagraphNode {\n\treturn node.element === 'paragraph'\n}\n\n/** Determine whether a node is a list block. */\nexport function isListNode(node: MarkdownNode): node is ListNode {\n\treturn node.element === 'list'\n}\n\n/** Determine whether a node is a GFM table block. */\nexport function isTableNode(node: MarkdownNode): node is TableNode {\n\treturn node.element === 'table'\n}\n\n/** Determine whether a node is a fenced code block. */\nexport function isCodeBlockNode(node: MarkdownNode): node is CodeBlockNode {\n\treturn node.element === 'codeBlock'\n}\n\n/** Determine whether a node is a blockquote block. */\nexport function isBlockquoteNode(node: MarkdownNode): node is BlockquoteNode {\n\treturn node.element === 'blockquote'\n}\n\n/** Determine whether a node is a thematic break (horizontal rule) block. */\nexport function isThematicBreakNode(node: MarkdownNode): node is ThematicBreakNode {\n\treturn node.element === 'thematicBreak'\n}\n\n// === Inline guards\n\n/** Determine whether a node is a plain text run. */\nexport function isTextNode(node: MarkdownNode): node is TextNode {\n\treturn node.element === 'text'\n}\n\n/** Determine whether a node is an emphasis run (`*em*` / `**strong**`). */\nexport function isEmphasisNode(node: MarkdownNode): node is EmphasisNode {\n\treturn node.element === 'emphasis'\n}\n\n/**\n * Determine whether a node is an inline code span.\n *\n * @remarks\n * Narrows to {@link CodeSpanNode} - the node whose `element` discriminant is\n * `'codeSpan'`.\n */\nexport function isCodeSpanNode(node: MarkdownNode): node is CodeSpanNode {\n\treturn node.element === 'codeSpan'\n}\n\n/** Determine whether a node is a link. */\nexport function isLinkNode(node: MarkdownNode): node is LinkNode {\n\treturn node.element === 'link'\n}\n\n// === From-unknown AST guards\n//\n// The node guards above narrow an ALREADY-PARSED MarkdownNode by its `element`\n// tag. The guards below instead validate an arbitrary `unknown` value (untrusted\n// input - a deserialized AST, a value crossing a process/RPC boundary) against\n// the full node shape, field by field, composed from @orkestrel/contract\n// combinators. Each guard IS its own hoisted composed value (compiled once at\n// module init, not per call); inline<->block recursion (emphasis/link children,\n// list items, blockquote children) resolves through `lazyOf`, closing over the\n// exported guard names themselves - legal because `lazyOf`'s thunk resolves per\n// call, strictly after module init has assigned every export. @orkestrel/contract\n// guarantees guard totality (AGENTS §14): `lazyOf`, `unionOf`, `recordOf`, and\n// every built-in guard are throw-contained, so a hostile getter, a structural\n// cycle, or pathologically deep input returns `false` rather than throwing -\n// no additional `attempt` wrapping is needed here.\n\n/**\n * Determine whether an arbitrary value is a valid {@link InlineNode} - a text\n * run, emphasis, code span, or link, recursively validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is\n * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link InlineNode}\n *\n * @example\n * ```ts\n * import { isInlineNode } from '@orkestrel/markdown'\n *\n * isInlineNode({ element: 'text', value: 'hi' }) // true\n * isInlineNode({ element: 'text' }) // false - missing `value`\n * ```\n */\nexport const isInlineNode: Guard<InlineNode> = unionOf(\n\trecordOf({ element: literalOf('text'), value: isString }),\n\trecordOf({\n\t\telement: literalOf('emphasis'),\n\t\tstrong: isBoolean,\n\t\tchildren: arrayOf(lazyOf(() => isInlineNode)),\n\t}),\n\trecordOf({ element: literalOf('codeSpan'), value: isString }),\n\trecordOf({\n\t\telement: literalOf('link'),\n\t\thref: isString,\n\t\tchildren: arrayOf(lazyOf(() => isInlineNode)),\n\t}),\n)\n\n/**\n * Determine whether an arbitrary value is a valid {@link BlockNode} - a\n * heading, paragraph, list, table, code block, blockquote, or thematic break,\n * recursively validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is\n * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).\n * A list item's shape is inlined here (and in {@link isMarkdownNode}) rather\n * than named separately - it is used at exactly these two sites.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link BlockNode}\n *\n * @example\n * ```ts\n * import { isBlockNode } from '@orkestrel/markdown'\n *\n * isBlockNode({ element: 'thematicBreak' }) // true\n * isBlockNode({ element: 'heading' }) // false - missing `level` / `children`\n * ```\n */\nexport const isBlockNode: Guard<BlockNode> = unionOf(\n\trecordOf({ element: literalOf('heading'), level: isNumber, children: arrayOf(isInlineNode) }),\n\trecordOf({ element: literalOf('paragraph'), children: arrayOf(isInlineNode) }),\n\trecordOf({\n\t\telement: literalOf('list'),\n\t\tordered: isBoolean,\n\t\tstart: isNumber,\n\t\titems: arrayOf(\n\t\t\trecordOf({ element: literalOf('listItem'), children: arrayOf(lazyOf(() => isBlockNode)) }),\n\t\t),\n\t}),\n\trecordOf({\n\t\telement: literalOf('table'),\n\t\theader: arrayOf(arrayOf(isInlineNode)),\n\t\trows: arrayOf(arrayOf(arrayOf(isInlineNode))),\n\t\talign: arrayOf(literalOf('none', 'left', 'right', 'center')),\n\t}),\n\trecordOf({ element: literalOf('codeBlock'), lang: isString, code: isString }, ['lang']),\n\trecordOf({ element: literalOf('blockquote'), children: arrayOf(lazyOf(() => isBlockNode)) }),\n\trecordOf({ element: literalOf('thematicBreak') }),\n)\n\n/**\n * Determine whether an arbitrary value is a valid {@link MarkdownNode} - the\n * {@link MarkdownDocument} root, a {@link BlockNode}, a {@link ListItemNode}, or\n * an {@link InlineNode}, recursively validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is\n * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).\n * A list item's shape is inlined here (and in {@link isBlockNode}) rather than\n * named separately - it is used at exactly these two sites.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link MarkdownNode}\n *\n * @example\n * ```ts\n * import { isMarkdownNode } from '@orkestrel/markdown'\n *\n * isMarkdownNode({ element: 'text', value: 'hi' }) // true\n * isMarkdownNode({ element: 'bogus' }) // false\n * ```\n */\nexport const isMarkdownNode: Guard<MarkdownNode> = unionOf(\n\tlazyOf(() => isMarkdownDocument),\n\tlazyOf(() => isBlockNode),\n\trecordOf({ element: literalOf('listItem'), children: arrayOf(lazyOf(() => isBlockNode)) }),\n\tlazyOf(() => isInlineNode),\n)\n\n/**\n * Determine whether an arbitrary value is a valid {@link MarkdownDocument} -\n * the parsed-AST root {@link parseDocument} returns, recursively\n * validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`recordOf`, `arrayOf`) is throw-contained per the\n * `@orkestrel/contract` guard contract (AGENTS §14).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link MarkdownDocument}\n *\n * @example\n * ```ts\n * import { isMarkdownDocument } from '@orkestrel/markdown'\n *\n * isMarkdownDocument({ element: 'document', children: [] }) // true\n * isMarkdownDocument({ element: 'document' }) // false - missing `children`\n * ```\n */\nexport const isMarkdownDocument: Guard<MarkdownDocument> = recordOf({\n\telement: literalOf('document'),\n\tchildren: arrayOf(isBlockNode),\n})\n","import type {\n\tBlockNode,\n\tEmphasisNode,\n\tInlineNode,\n\tLinkNode,\n\tListItemNode,\n\tListItemParts,\n\tMarkdownDocument,\n\tMarkdownHandlers,\n\tMarkdownNode,\n\tMarkdownRewriteHandler,\n\tTableAlign,\n\tTableNode,\n} from './types.js'\nimport { MAX_DEPTH, SAFE_URL_SCHEMES } from './constants.js'\nimport {\n\tisBlockNode,\n\tisEscapable,\n\tisInlineNode,\n\tisQuote,\n\tisTableStart,\n\tisThematicBreak,\n\tisWhitespace,\n} from './validators.js'\nimport { isEmptyString, isNonEmptyArray, isNonEmptyString, parseInteger } from '@orkestrel/contract'\n\n// Markdown parsing + rendering leaves (pure, total, zero-dependency)\n//\n// The pure leaf primitives {@link parseDocument} composes: the line / block\n// scanners (headings, fences, list items, table rows, quotes, thematic breaks), the\n// inline `scan*` engine (emphasis / links / code with backslash escapes), and the HTML\n// escaping + URL-sanitization the renderer leans on. Every function is PURE, TOTAL, and\n// referentially transparent - malformed input degrades to text, never throws (AGENTS\n// §14) - so each is unit-tested in isolation. The ORCHESTRATION that threads these\n// together (the block / inline / render recursion) lives in parsers.ts's functions,\n// not here (AGENTS §5): a helper is a functional-core leaf, a method is the\n// composition. Inline scanning is index-based (no backtracking regex) so it is\n// linear-time - no ReDoS on adversarial input.\n\n// Text + line utilities\n\n/**\n * Normalize line endings to `\\n` and split a markdown document into its lines - CRLF\n * (`\\r\\n`) and bare CR (`\\r`) both collapse to `\\n` first, so a Windows-origin\n * document parses identically. A single trailing newline does not yield a final\n * empty line.\n *\n * @param markdown - The raw markdown source\n * @returns The document's lines, line-terminators stripped\n */\nexport function splitLines(markdown: string): readonly string[] {\n\tconst lines = markdown.replace(/\\r\\n?/g, '\\n').split('\\n')\n\tif (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()\n\treturn lines\n}\n\n/**\n * The count of leading space / tab characters on `line` (a tab counts as one) - the\n * indent that decides whether a list item's continuation belongs to the item.\n *\n * @param line - The line to measure\n * @returns The number of leading space / tab characters\n */\nexport function leadingIndent(line: string): number {\n\tlet count = 0\n\tfor (const character of line) {\n\t\tif (character === ' ' || character === '\\t') count += 1\n\t\telse break\n\t}\n\treturn count\n}\n\n// Block-level detection\n\n/**\n * Extract an ATX heading line (`#` … `######` followed by text) into its\n * `{ level, text }`, or `undefined` when `line` is not a heading. A run of more than 6\n * `#`s, or `#`s not followed by whitespace + text, is not a\n * heading; an optional closing `###` run is stripped.\n *\n * @param line - The candidate line\n * @returns The heading level (1–6) and its raw inline text, or `undefined`\n */\nexport function extractHeading(\n\tline: string,\n): { readonly level: number; readonly text: string } | undefined {\n\tconst match = /^(#{1,6})(?:\\s+(.*))?$/.exec(line.trimStart())\n\tif (!match || match[1] === undefined) return undefined\n\tconst level = match[1].length\n\tconst text = (match[2] ?? '').replace(/\\s+#+\\s*$/, '').trim()\n\treturn { level, text }\n}\n\n/**\n * Extract a fenced-code opening line (```` ``` ```` or `~~~`, optionally with an info\n * string) into its `{ marker, lang }`, or `undefined` when `line` is not a fence\n * opener. `marker` is the exact fence run (the closer must match the same character +\n * at least the same length); `lang` is the first word of the info string.\n *\n * @param line - The candidate line\n * @returns The fence marker run and its language tag, or `undefined`\n */\nexport function extractFence(\n\tline: string,\n): { readonly marker: string; readonly lang: string | undefined } | undefined {\n\tconst match = /^\\s*(`{3,}|~{3,})\\s*(.*)$/.exec(line)\n\tif (!match || match[1] === undefined) return undefined\n\tconst info = (match[2] ?? '').trim()\n\t// A backtick in a backtick fence's info string is invalid (ambiguous with a span).\n\tif (match[1].startsWith('`') && info.includes('`')) return undefined\n\tconst lang = isNonEmptyString(info) ? info.split(/\\s+/)[0] : undefined\n\treturn { marker: match[1], lang }\n}\n\n/**\n * Extract a list-item line (`-` / `*` / `+` bullet, or `1.` / `1)` ordinal, followed by\n * a space) into its {@link ListItemParts}, or `undefined` when `line` is not a list\n * item. `content` is the text after the marker; `marker` is the full marker-plus-space\n * width (for measuring a continuation's indent).\n *\n * @param line - The candidate line\n * @returns The list-item parts, or `undefined` when not a list item\n */\nexport function extractListItem(line: string): ListItemParts | undefined {\n\tconst unordered = /^(\\s*)([-*+])\\s+(.*)$/.exec(line)\n\tif (unordered && unordered[1] !== undefined) {\n\t\tconst indent = unordered[1].length\n\t\tconst content = unordered[3] ?? ''\n\t\treturn { ordered: false, start: 1, content, indent, marker: line.length - content.length }\n\t}\n\tconst ordered = /^(\\s*)(\\d{1,9})[.)]\\s+(.*)$/.exec(line)\n\tif (ordered && ordered[1] !== undefined && ordered[2] !== undefined) {\n\t\tconst indent = ordered[1].length\n\t\tconst content = ordered[3] ?? ''\n\t\treturn {\n\t\t\tordered: true,\n\t\t\tstart: parseInteger(ordered[2]) ?? 1,\n\t\t\tcontent,\n\t\t\tindent,\n\t\t\tmarker: line.length - content.length,\n\t\t}\n\t}\n\treturn undefined\n}\n\n/**\n * Strip one level of blockquote marker (`>` plus one optional following space) from a\n * blockquote line, so the de-quoted lines re-parse as nested blocks.\n *\n * @param line - A blockquote line (per {@link isQuote})\n * @returns The line with its leading `>` (and one space) removed\n */\nexport function stripQuote(line: string): string {\n\treturn line.replace(/^\\s{0,3}>\\s?/, '')\n}\n\n/**\n * Split one GFM table row into its cell strings - outer pipes are optional, an escaped\n * pipe (`\\|`) inside a cell is NOT a separator (it becomes a literal `|`), and the\n * empty leading / trailing cell produced by an outer `|` is dropped.\n *\n * @param row - The raw table row line\n * @returns The row's cells, in column order\n */\nexport function splitTableRow(row: string): readonly string[] {\n\tconst cells: string[] = []\n\tlet current = ''\n\tconst trimmed = row.trim()\n\tfor (let index = 0; index < trimmed.length; index += 1) {\n\t\tconst character = trimmed[index]\n\t\tif (character === '\\\\' && trimmed[index + 1] === '|') {\n\t\t\tcurrent += '|'\n\t\t\tindex += 1\n\t\t} else if (character === '|') {\n\t\t\tcells.push(current)\n\t\t\tcurrent = ''\n\t\t} else {\n\t\t\tcurrent += character\n\t\t}\n\t}\n\tcells.push(current)\n\tif (isNonEmptyArray<string>(cells) && isEmptyString((cells[0] ?? '').trim())) cells.shift()\n\tif (isNonEmptyArray<string>(cells) && isEmptyString((cells[cells.length - 1] ?? '').trim()))\n\t\tcells.pop()\n\treturn cells\n}\n\n/**\n * Derive the per-column {@link TableAlign} list from a GFM delimiter row - `:---`\n * left, `---:` right, `:---:` center, `---` none.\n *\n * @param delimiter - The table's delimiter row\n * @returns One alignment per column, in column order\n */\nexport function tableAlignments(delimiter: string): readonly TableAlign[] {\n\treturn splitTableRow(delimiter).map((cell) => {\n\t\tconst text = cell.trim()\n\t\tconst left = text.startsWith(':')\n\t\tconst right = text.endsWith(':')\n\t\tif (left && right) return 'center'\n\t\tif (right) return 'right'\n\t\tif (left) return 'left'\n\t\treturn 'none'\n\t})\n}\n\n// Block phase\n\n/**\n * Whether the line at `index` starts a NEW block kind (heading / fence / thematic\n * break / blockquote / list / table) - the paragraph collector stops at such a line\n * so a block following a paragraph without a blank line still parses (a trusted-input\n * caller writing a `##` heading directly under a paragraph, with no intervening blank\n * line).\n *\n * @param lines - The document's lines\n * @param index - The line index to test\n * @returns `true` when the line begins a different block\n */\nexport function startsBlock(lines: readonly string[], index: number): boolean {\n\tconst line = lines[index] ?? ''\n\treturn (\n\t\textractHeading(line) !== undefined ||\n\t\textractFence(line) !== undefined ||\n\t\tisThematicBreak(line) ||\n\t\tisQuote(line) ||\n\t\textractListItem(line) !== undefined ||\n\t\tisTableStart(line, lines[index + 1])\n\t)\n}\n\n// Inline phase\n\n/**\n * Resolve backslash escapes in a raw string to their literal characters - used for a\n * link `href` (which is not otherwise inline-parsed) and any plain text run.\n *\n * @param text - The raw text possibly carrying `\\x` escapes\n * @returns The text with escapable `\\x` reduced to `x`\n */\nexport function unescapeText(text: string): string {\n\tlet out = ''\n\tfor (let index = 0; index < text.length; index += 1) {\n\t\tconst character = text[index] ?? ''\n\t\tif (character === '\\\\' && isEscapable(text[index + 1] ?? '')) {\n\t\t\tout += text[index + 1] ?? ''\n\t\t\tindex += 1\n\t\t} else {\n\t\t\tout += character\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Merge adjacent text nodes into one - the inline scanner emits a text node per\n * unrecognized character, so coalescing keeps the AST clean and assertion-friendly.\n *\n * @param nodes - The inline nodes (possibly with adjacent text runs)\n * @returns The nodes with consecutive text nodes concatenated\n */\nexport function coalesceText(nodes: readonly InlineNode[]): readonly InlineNode[] {\n\tconst out: InlineNode[] = []\n\tfor (const node of nodes) {\n\t\tconst last = out[out.length - 1]\n\t\tif (node.element === 'text' && last !== undefined && last.element === 'text') {\n\t\t\tout[out.length - 1] = { element: 'text', value: last.value + node.value }\n\t\t} else {\n\t\t\tout.push(node)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Scan an inline code span at `start` (a `` ` ``-run … a matching `` ` ``-run of the\n * SAME length, the CommonMark rule that lets a span contain backticks). Returns the\n * span's literal text + end index, or `undefined` when no matching closer exists (it\n * then degrades to literal backticks).\n *\n * @param source - The inline source text\n * @param start - The index of the opening backtick\n * @param to - The exclusive end of the scan window\n * @returns The span text + end index, or `undefined`\n */\nexport function scanCode(\n\tsource: string,\n\tstart: number,\n\tto: number,\n): { readonly value: string; readonly end: number } | undefined {\n\tlet run = 0\n\twhile (start + run < to && source[start + run] === '`') run += 1\n\tconst open = '`'.repeat(run)\n\tlet search = start + run\n\tfor (;;) {\n\t\tconst closeAt = source.indexOf(open, search)\n\t\tif (closeAt === -1 || closeAt + run > to) return undefined\n\t\t// The closer must be EXACTLY `run` backticks (not bordered by another backtick).\n\t\tif (source[closeAt - 1] !== '`' && source[closeAt + run] !== '`') {\n\t\t\tlet value = source.slice(start + run, closeAt)\n\t\t\tif (\n\t\t\t\tvalue.length > 2 &&\n\t\t\t\tvalue.startsWith(' ') &&\n\t\t\t\tvalue.endsWith(' ') &&\n\t\t\t\tvalue.trim().length > 0\n\t\t\t) {\n\t\t\t\tvalue = value.slice(1, -1)\n\t\t\t}\n\t\t\treturn { value, end: closeAt + run }\n\t\t}\n\t\tsearch = closeAt + 1\n\t}\n}\n\n/**\n * Scan a link `[text](href)` at `start` - the text runs to a BALANCED `]`, then `(`\n * must immediately follow and the destination runs to the matching `)` (both respect\n * nested delimiters + escapes). Returns the link node, or `undefined` when the shape\n * does not hold (it then degrades to a literal `[`).\n *\n * @param source - The inline source text\n * @param start - The index of the opening `[`\n * @param to - The exclusive end of the scan window\n * @param depth - The current inline-recursion depth (defaults to 0 at the entry point);\n * at {@link MAX_DEPTH} the link's text children degrade to literal text instead of\n * recursing further\n * @returns The parsed {@link LinkNode} + end index, or `undefined`\n */\nexport function scanLink(\n\tsource: string,\n\tstart: number,\n\tto: number,\n\tdepth = 0,\n): { readonly node: LinkNode; readonly end: number } | undefined {\n\tlet bracketDepth = 0\n\tlet close = -1\n\tfor (let index = start; index < to; index += 1) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\') {\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '[') bracketDepth += 1\n\t\telse if (character === ']') {\n\t\t\tbracketDepth -= 1\n\t\t\tif (bracketDepth === 0) {\n\t\t\t\tclose = index\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif (close === -1 || source[close + 1] !== '(') return undefined\n\tlet parenDepth = 0\n\tlet parenClose = -1\n\tfor (let index = close + 1; index < to; index += 1) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\') {\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '(') parenDepth += 1\n\t\telse if (character === ')') {\n\t\t\tparenDepth -= 1\n\t\t\tif (parenDepth === 0) {\n\t\t\t\tparenClose = index\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif (parenClose === -1) return undefined\n\tconst href = unescapeText(source.slice(close + 2, parenClose).trim())\n\tconst children = scanInline(source, start + 1, close, depth + 1)\n\treturn { node: { element: 'link', href, children }, end: parenClose + 1 }\n}\n\n/**\n * Scan an emphasis run at `start` (`*` / `_`, doubled for strong) - finds the nearest\n * matching closing run of the same marker + width, requiring non-space immediately\n * inside both delimiters (the CommonMark flanking simplification that blocks `* x *`).\n * Returns the emphasis node, or `undefined` when no valid closer exists (it then\n * degrades to a literal marker).\n *\n * @param source - The inline source text\n * @param start - The index of the opening marker\n * @param to - The exclusive end of the scan window\n * @param depth - The current inline-recursion depth (defaults to 0 at the entry point);\n * at {@link MAX_DEPTH} the emphasis's children degrade to literal text instead of\n * recursing further\n * @returns The parsed {@link EmphasisNode} + end index, or `undefined`\n */\nexport function scanEmphasis(\n\tsource: string,\n\tstart: number,\n\tto: number,\n\tdepth = 0,\n): { readonly node: EmphasisNode; readonly end: number } | undefined {\n\tconst marker = source[start] ?? ''\n\tlet run = 0\n\twhile (start + run < to && source[start + run] === marker && run < 2) run += 1\n\tconst strong = run === 2\n\tconst openEnd = start + run\n\tif (openEnd >= to || isWhitespace(source[openEnd] ?? '')) return undefined\n\tlet index = openEnd\n\twhile (index < to) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\') {\n\t\t\tindex += 2\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '`') {\n\t\t\tconst span = scanCode(source, index, to)\n\t\t\tindex = span ? span.end : index + 1\n\t\t\tcontinue\n\t\t}\n\t\tif (character === marker) {\n\t\t\tlet closeRun = 0\n\t\t\twhile (index + closeRun < to && source[index + closeRun] === marker) closeRun += 1\n\t\t\tif (closeRun >= run && !isWhitespace(source[index - 1] ?? '')) {\n\t\t\t\treturn {\n\t\t\t\t\tnode: {\n\t\t\t\t\t\telement: 'emphasis',\n\t\t\t\t\t\tstrong,\n\t\t\t\t\t\tchildren: scanInline(source, openEnd, index, depth + 1),\n\t\t\t\t\t},\n\t\t\t\t\tend: index + run,\n\t\t\t\t}\n\t\t\t}\n\t\t\tindex += closeRun\n\t\t\tcontinue\n\t\t}\n\t\tindex += 1\n\t}\n\treturn undefined\n}\n\n/**\n * Scan the window `[from, to)` of `source` into inline nodes - the single recursive\n * engine the inline phase runs on (emphasis / link text recurse through it). Linear:\n * each character is consumed once; a failed construct emits its opening character as\n * text and advances by one, so there is no re-scan (no ReDoS).\n *\n * @param source - The inline source text\n * @param from - The inclusive start of the scan window\n * @param to - The exclusive end of the scan window\n * @param depth - The current inline-recursion depth (defaults to 0 at the entry point);\n * incremented by one on every recursive descent through {@link scanLink} /\n * {@link scanEmphasis}. At {@link MAX_DEPTH} the window is never scanned for markup -\n * it emits as a single literal text node - so pathological nesting (`[[[[…`,\n * `****…`) cannot exhaust the call stack.\n * @returns The parsed inline nodes (NOT yet coalesced)\n */\nexport function scanInline(\n\tsource: string,\n\tfrom: number,\n\tto: number,\n\tdepth = 0,\n): readonly InlineNode[] {\n\tif (depth >= MAX_DEPTH)\n\t\treturn from < to ? [{ element: 'text', value: source.slice(from, to) }] : []\n\tconst nodes: InlineNode[] = []\n\tlet index = from\n\tlet pending = ''\n\tconst flush = (): void => {\n\t\tif (pending.length > 0) {\n\t\t\tnodes.push({ element: 'text', value: pending })\n\t\t\tpending = ''\n\t\t}\n\t}\n\twhile (index < to) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\' && index + 1 < to && isEscapable(source[index + 1] ?? '')) {\n\t\t\tpending += source[index + 1] ?? ''\n\t\t\tindex += 2\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '`') {\n\t\t\tconst span = scanCode(source, index, to)\n\t\t\tif (span) {\n\t\t\t\tflush()\n\t\t\t\tnodes.push({ element: 'codeSpan', value: span.value })\n\t\t\t\tindex = span.end\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif (character === '[') {\n\t\t\tconst link = scanLink(source, index, to, depth)\n\t\t\tif (link) {\n\t\t\t\tflush()\n\t\t\t\tnodes.push(link.node)\n\t\t\t\tindex = link.end\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif (character === '*' || character === '_') {\n\t\t\tconst emphasis = scanEmphasis(source, index, to, depth)\n\t\t\tif (emphasis) {\n\t\t\t\tflush()\n\t\t\t\tnodes.push(emphasis.node)\n\t\t\t\tindex = emphasis.end\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tpending += character\n\t\tindex += 1\n\t}\n\tflush()\n\treturn nodes\n}\n\n// Rendering (AST HTML string)\n\n/**\n * HTML-escape text content - `&` / `<` / `>` / `\"` / `'` to their entities - so text\n * from a markdown document can never inject markup. The renderer applies this to every\n * text run, code body, and (escaped further) attribute value.\n *\n * @param text - The raw text\n * @returns The HTML-escaped text\n */\nexport function escapeHtml(text: string): string {\n\treturn text\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;')\n\t\t.replace(/'/g, '&#39;')\n}\n\n/**\n * Sanitize + HTML-attribute-escape a link `href` - a destination whose scheme is not\n * in {@link SAFE_URL_SCHEMES} (notably `javascript:` / `data:` / `vbscript:`), or that\n * is protocol-relative (`//host/path`, or a backslash variant a browser normalizes to\n * the same effect - `\\\\host`, `/\\host`, `\\/host` - inherits whatever scheme the\n * embedding page is served over, including an unsafe one), is dropped to an empty\n * string; a relative / anchor / scheme-less (and non-protocol-relative) destination\n * (including a SINGLE leading `/` or `\\`) is kept;\n * the surviving value is then HTML-escaped. Defence-in-depth against an XSS `href`,\n * even though the input is trusted.\n *\n * @param href - The raw link destination\n * @returns A safe, escaped `href` (empty when the scheme is unsafe or protocol-relative)\n */\nexport function sanitizeUrl(href: string): string {\n\t// Strip every whitespace + C0/C1 control codepoint (≤ U+0020 or U+007F–U+009F)\n\t// anywhere - a `java\\tscript:` / embedded-newline scheme-spoofing evasion - by\n\t// codepoint, not a control-character regex class (AGENTS §1: no disables).\n\tlet cleaned = ''\n\tfor (const character of href) {\n\t\tconst code = character.codePointAt(0) ?? 0\n\t\tif (code > 0x20 && !(code >= 0x7f && code <= 0x9f)) cleaned += character\n\t}\n\tif (/^[/\\\\]{2}/.exec(cleaned)) return ''\n\tconst scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleaned)\n\tif (scheme && scheme[1] !== undefined && !SAFE_URL_SCHEMES.has(scheme[1].toLowerCase())) return ''\n\treturn escapeHtml(cleaned)\n}\n\n/**\n * Render a {@link MarkdownNode} (typically a {@link MarkdownDocument}) to a safe HTML\n * string - the recursive AST → HTML engine (headings, paragraphs, lists, GFM tables,\n * fenced code, blockquotes, links, emphasis, inline code), escaping every text run and\n * sanitizing every link `href`.\n *\n * @remarks\n * Total: never throws. At {@link MAX_DEPTH} a value-bearing node (`text` / `codeSpan`)\n * degrades to its escaped `value`; any other node degrades to `''` instead of\n * recursing further, so pathologically deep input cannot exhaust the call stack. The\n * recursive engine and its per-shape sub-steps (inline concatenation, table cell,\n * tight list-item) are nested inner functions - the only exported surface is\n * `renderHTML` itself.\n *\n * @param node - The AST node to render (a full document, or any sub-node)\n * @returns The rendered, XSS-safe HTML string\n *\n * @example\n * ```ts\n * renderHTML({ element: 'document', children: [\n * { element: 'heading', level: 1, children: [{ element: 'text', value: 'Hi' }] },\n * ] })\n * // '<h1>Hi</h1>'\n * ```\n */\nexport function renderHTML(node: MarkdownNode): string {\n\tfunction render(current: MarkdownNode, depth: number): string {\n\t\tif (depth >= MAX_DEPTH)\n\t\t\treturn 'value' in current && typeof current.value === 'string'\n\t\t\t\t? escapeHtml(current.value)\n\t\t\t\t: ''\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\t\treturn current.children.map((child) => render(child, depth + 1)).join('\\n')\n\t\t\tcase 'heading':\n\t\t\t\treturn `<h${current.level}>${renderInline(current.children, depth)}</h${current.level}>`\n\t\t\tcase 'paragraph':\n\t\t\t\treturn `<p>${renderInline(current.children, depth)}</p>`\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn '<hr>'\n\t\t\tcase 'blockquote':\n\t\t\t\treturn `<blockquote>\\n${current.children.map((child) => render(child, depth + 1)).join('\\n')}\\n</blockquote>`\n\t\t\tcase 'codeBlock': {\n\t\t\t\tconst open =\n\t\t\t\t\tcurrent.lang === undefined\n\t\t\t\t\t\t? '<code>'\n\t\t\t\t\t\t: `<code class=\"language-${escapeHtml(current.lang)}\">`\n\t\t\t\treturn `<pre>${open}${escapeHtml(current.code)}</code></pre>`\n\t\t\t}\n\t\t\tcase 'list': {\n\t\t\t\tconst items = current.items.map((item) => render(item, depth + 1)).join('\\n')\n\t\t\t\tif (!current.ordered) return `<ul>\\n${items}\\n</ul>`\n\t\t\t\tconst start = current.start !== 1 ? ` start=\"${current.start}\"` : ''\n\t\t\t\treturn `<ol${start}>\\n${items}\\n</ol>`\n\t\t\t}\n\t\t\tcase 'listItem':\n\t\t\t\treturn `<li>${renderItem(current.children, depth)}</li>`\n\t\t\tcase 'table': {\n\t\t\t\tconst head = `<tr>${current.header.map((cell, column) => renderCell('th', cell, current.align[column], depth)).join('')}</tr>`\n\t\t\t\tconst body = current.rows\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t`<tr>${row.map((cell, column) => renderCell('td', cell, current.align[column], depth)).join('')}</tr>`,\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n')\n\t\t\t\tconst bodyHtml = isNonEmptyArray(current.rows) ? `\\n<tbody>\\n${body}\\n</tbody>` : ''\n\t\t\t\treturn `<table>\\n<thead>\\n${head}\\n</thead>${bodyHtml}\\n</table>`\n\t\t\t}\n\t\t\tcase 'text':\n\t\t\t\treturn escapeHtml(current.value)\n\t\t\tcase 'emphasis':\n\t\t\t\treturn current.strong\n\t\t\t\t\t? `<strong>${renderInline(current.children, depth + 1)}</strong>`\n\t\t\t\t\t: `<em>${renderInline(current.children, depth + 1)}</em>`\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn `<code>${escapeHtml(current.value)}</code>`\n\t\t\tcase 'link':\n\t\t\t\treturn `<a href=\"${sanitizeUrl(current.href)}\">${renderInline(current.children, depth + 1)}</a>`\n\t\t\tdefault:\n\t\t\t\treturn ''\n\t\t}\n\t}\n\n\tfunction renderInline(nodes: readonly InlineNode[], depth: number): string {\n\t\treturn nodes.map((child) => render(child, depth + 1)).join('')\n\t}\n\n\tfunction renderCell(\n\t\ttag: 'th' | 'td',\n\t\tcell: readonly InlineNode[],\n\t\talign: TableAlign | undefined,\n\t\tdepth: number,\n\t): string {\n\t\tconst style =\n\t\t\talign === 'left' || align === 'right' || align === 'center'\n\t\t\t\t? ` style=\"text-align:${align}\"`\n\t\t\t\t: ''\n\t\treturn `<${tag}${style}>${renderInline(cell, depth + 1)}</${tag}>`\n\t}\n\n\tfunction renderItem(children: readonly BlockNode[], depth: number): string {\n\t\tif (children.length === 1) {\n\t\t\tconst only = children[0]\n\t\t\tif (only !== undefined && only.element === 'paragraph')\n\t\t\t\treturn renderInline(only.children, depth)\n\t\t}\n\t\treturn children.map((child) => render(child, depth + 1)).join('\\n')\n\t}\n\n\treturn render(node, 0)\n}\n\n/**\n * Render a {@link MarkdownNode} to its CANONICAL markdown source - the inverse\n * projection of `renderHTML`, and the serializer a `parse(renderMarkdown(doc))`\n * round-trip is built on. Canonical forms: `*em*` / `**strong**` (underscore emphasis\n * normalizes to asterisks), `- ` bullets, `N. ` sequential ordinals (from the list's\n * `start`), `---` thematic breaks, fenced code blocks (backtick run widened past any\n * 3+ backtick run inside the body), ATX headings, `> `-prefixed blockquote lines, GFM\n * tables (1-space-padded cells, `\\|`-escaped pipes, an alignment delimiter row), and\n * `[text](href)` links. A `text` node's literal content is backslash-escaped wherever\n * it would otherwise re-parse as markup (AGENTS §14 parse↔render soundness).\n *\n * @remarks\n * Total: never throws. At {@link MAX_DEPTH} a value-bearing node degrades to its\n * escaped `value`; any other node degrades to `''`. Blocks are joined by exactly one\n * blank line; a document with zero blocks renders `''`.\n *\n * @param node - The AST node to render (a full document, or any sub-node)\n * @returns The canonical markdown source\n *\n * @example\n * ```ts\n * renderMarkdown({ element: 'document', children: [\n * { element: 'heading', level: 2, children: [{ element: 'text', value: 'Hi' }] },\n * ] })\n * // '## Hi'\n * ```\n */\nexport function renderMarkdown(node: MarkdownNode): string {\n\tfunction escapeText(value: string): string {\n\t\tlet out = ''\n\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\tconst character = value[index] ?? ''\n\t\t\tconst atLineStart = index === 0 || value[index - 1] === '\\n'\n\t\t\tif (\n\t\t\t\tcharacter === '\\\\' ||\n\t\t\t\tcharacter === '*' ||\n\t\t\t\tcharacter === '_' ||\n\t\t\t\tcharacter === '`' ||\n\t\t\t\tcharacter === '[' ||\n\t\t\t\tcharacter === ']'\n\t\t\t) {\n\t\t\t\tout += `\\\\${character}`\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (atLineStart) {\n\t\t\t\tif (character === '#' || character === '>') {\n\t\t\t\t\tout += `\\\\${character}`\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif ((character === '-' || character === '+') && (value[index + 1] ?? ' ') === ' ') {\n\t\t\t\t\tout += `\\\\${character}`\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (/[0-9]/.test(character)) {\n\t\t\t\t\tlet end = index\n\t\t\t\t\twhile (end < value.length && /[0-9]/.test(value[end] ?? '')) end += 1\n\t\t\t\t\tconst marker = value[end]\n\t\t\t\t\tif ((marker === '.' || marker === ')') && value[end + 1] === ' ') {\n\t\t\t\t\t\tout += `${value.slice(index, end)}\\\\${marker}`\n\t\t\t\t\t\tindex = end\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tout += character\n\t\t}\n\t\treturn out\n\t}\n\n\tfunction fenceFor(body: string, minimum: number): string {\n\t\tlet longest = 0\n\t\tlet run = 0\n\t\tfor (const character of body) {\n\t\t\tif (character === '`') {\n\t\t\t\trun += 1\n\t\t\t\tlongest = Math.max(longest, run)\n\t\t\t} else {\n\t\t\t\trun = 0\n\t\t\t}\n\t\t}\n\t\treturn '`'.repeat(Math.max(minimum, longest + 1))\n\t}\n\n\tfunction renderInline(nodes: readonly InlineNode[], depth: number): string {\n\t\treturn nodes.map((child) => render(child, depth + 1)).join('')\n\t}\n\n\tfunction renderBlocks(blocks: readonly BlockNode[], depth: number): string {\n\t\treturn blocks.map((block) => render(block, depth + 1)).join('\\n\\n')\n\t}\n\n\tfunction renderItem(item: ListItemNode, marker: string, depth: number): string {\n\t\tconst body = renderBlocks(item.children, depth + 1)\n\t\tconst pad = ' '.repeat(marker.length)\n\t\treturn body\n\t\t\t.split('\\n')\n\t\t\t.map((line, index) => (index === 0 ? marker + line : line === '' ? '' : pad + line))\n\t\t\t.join('\\n')\n\t}\n\n\tfunction renderCell(cell: readonly InlineNode[], depth: number): string {\n\t\treturn renderInline(cell, depth + 1).replace(/\\|/g, '\\\\|')\n\t}\n\n\tfunction renderTable(current: TableNode, depth: number): string {\n\t\tconst columns = current.header.length\n\t\tconst headerRow = `| ${current.header.map((cell) => renderCell(cell, depth)).join(' | ')} |`\n\t\tconst delimiterRow = `| ${current.align\n\t\t\t.map((align) => {\n\t\t\t\tif (align === 'left') return ':--'\n\t\t\t\tif (align === 'right') return '--:'\n\t\t\t\tif (align === 'center') return ':-:'\n\t\t\t\treturn '---'\n\t\t\t})\n\t\t\t.join(' | ')} |`\n\t\tconst bodyRows = current.rows.map((row) => {\n\t\t\tconst cells: string[] = []\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tconst cell = row[column]\n\t\t\t\tcells.push(cell === undefined ? '' : renderCell(cell, depth))\n\t\t\t}\n\t\t\treturn `| ${cells.join(' | ')} |`\n\t\t})\n\t\treturn [headerRow, delimiterRow, ...bodyRows].join('\\n')\n\t}\n\n\tfunction render(current: MarkdownNode, depth: number): string {\n\t\tif (depth >= MAX_DEPTH)\n\t\t\treturn 'value' in current && typeof current.value === 'string'\n\t\t\t\t? escapeText(current.value)\n\t\t\t\t: ''\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\t\treturn renderBlocks(current.children, depth)\n\t\t\tcase 'heading': {\n\t\t\t\tconst text = renderInline(current.children, depth)\n\t\t\t\t// A trailing `#` run reads back as an ATX closing sequence on reparse -\n\t\t\t\t// escape the FIRST `#` of that run so it can't be stripped. Only fire when\n\t\t\t\t// the char preceding the run isn't a backslash - escapeText already escapes\n\t\t\t\t// a line-start `#`, and re-escaping it here would double-escape (`## #` -> text\n\t\t\t\t// \"#\" -> escapeText \"\\#\" -> would become \"\\\\#\" and break round-trip).\n\t\t\t\tconst escaped = text.replace(/(^|[^\\\\])(#+)$/, (_match, pre: string, hashes: string) => {\n\t\t\t\t\tconst first = hashes[0] ?? ''\n\t\t\t\t\treturn `${pre}\\\\${first}${hashes.slice(1)}`\n\t\t\t\t})\n\t\t\t\treturn `${'#'.repeat(current.level)} ${escaped}`\n\t\t\t}\n\t\t\tcase 'paragraph':\n\t\t\t\treturn renderInline(current.children, depth)\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn '---'\n\t\t\tcase 'blockquote': {\n\t\t\t\tconst inner = renderBlocks(current.children, depth)\n\t\t\t\treturn inner\n\t\t\t\t\t.split('\\n')\n\t\t\t\t\t.map((line) => (line === '' ? '>' : `> ${line}`))\n\t\t\t\t\t.join('\\n')\n\t\t\t}\n\t\t\tcase 'codeBlock': {\n\t\t\t\tconst fence = fenceFor(current.code, 3)\n\t\t\t\tconst lang = current.lang === undefined ? '' : current.lang\n\t\t\t\treturn `${fence}${lang}\\n${current.code}\\n${fence}`\n\t\t\t}\n\t\t\tcase 'list': {\n\t\t\t\tlet ordinal = current.start\n\t\t\t\tconst items = current.items.map((item) => {\n\t\t\t\t\tconst marker = current.ordered ? `${ordinal++}. ` : '- '\n\t\t\t\t\treturn renderItem(item, marker, depth)\n\t\t\t\t})\n\t\t\t\treturn items.join('\\n')\n\t\t\t}\n\t\t\tcase 'listItem':\n\t\t\t\treturn renderBlocks(current.children, depth)\n\t\t\tcase 'table':\n\t\t\t\treturn renderTable(current, depth)\n\t\t\tcase 'text':\n\t\t\t\treturn escapeText(current.value)\n\t\t\tcase 'emphasis': {\n\t\t\t\tconst marker = current.strong ? '**' : '*'\n\t\t\t\treturn `${marker}${renderInline(current.children, depth)}${marker}`\n\t\t\t}\n\t\t\tcase 'codeSpan': {\n\t\t\t\tconst fence = fenceFor(current.value, 1)\n\t\t\t\tconst pad = current.value.startsWith('`') || current.value.endsWith('`') ? ' ' : ''\n\t\t\t\treturn `${fence}${pad}${current.value}${pad}${fence}`\n\t\t\t}\n\t\t\tcase 'link': {\n\t\t\t\t// Mirror scanLink's unescape - a href containing `\\`, `(`, or `)` must\n\t\t\t\t// round-trip through the same balanced-paren + backslash-escape scan.\n\t\t\t\tconst href = current.href.replace(/[\\\\()]/g, (character) => `\\\\${character}`)\n\t\t\t\treturn `[${renderInline(current.children, depth)}](${href})`\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn ''\n\t\t}\n\t}\n\n\treturn render(node, 0)\n}\n\n/**\n * Depth-first, pre-order, root-inclusive traversal of a {@link MarkdownNode} - yields\n * the node itself, then recurses into its children (block children, list items, table\n * header/row cells' inline nodes) in walk order.\n *\n * @remarks\n * Total: never throws. Descent stops at {@link MAX_DEPTH} (the node at the cap is\n * still yielded; its children are not) so pathologically deep input cannot exhaust\n * the call stack.\n *\n * @param node - The AST node to walk (a full document, or any sub-node)\n * @returns A generator yielding every visited node, pre-order\n *\n * @example\n * ```ts\n * const doc = { element: 'document', children: [{ element: 'thematicBreak' }] } as const\n * [...walkNodes(doc)].map((node) => node.element) // ['document', 'thematicBreak']\n * ```\n */\nexport function* walkNodes(node: MarkdownNode): Generator<MarkdownNode> {\n\tfunction* walk(current: MarkdownNode, depth: number): Generator<MarkdownNode> {\n\t\tyield current\n\t\tif (depth >= MAX_DEPTH) return\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\tcase 'heading':\n\t\t\tcase 'paragraph':\n\t\t\tcase 'blockquote':\n\t\t\tcase 'listItem':\n\t\t\tcase 'emphasis':\n\t\t\tcase 'link':\n\t\t\t\tfor (const child of current.children) yield* walk(child, depth + 1)\n\t\t\t\treturn\n\t\t\tcase 'list':\n\t\t\t\tfor (const item of current.items) yield* walk(item, depth + 1)\n\t\t\t\treturn\n\t\t\tcase 'table':\n\t\t\t\tfor (const cell of current.header) for (const inline of cell) yield* walk(inline, depth + 1)\n\t\t\t\tfor (const row of current.rows)\n\t\t\t\t\tfor (const cell of row) for (const inline of cell) yield* walk(inline, depth + 1)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\treturn\n\t\t}\n\t}\n\tyield* walk(node, 0)\n}\n\n/**\n * Fold a {@link MarkdownNode} into a `T` via a total catamorphism - children are\n * folded first (post-order), then the node's own {@link MarkdownHandler} is invoked\n * with the already-folded children.\n *\n * @remarks\n * **Table contract.** A {@link TableNode} has no single `children` array - its cells\n * live in `header` (one inline-node list per column) and `rows` (a list of such\n * rows). The `table` handler receives ONE folded `T` per inline node, flattened in\n * walk order across ALL cells - every header cell's inline nodes (column order), then\n * every body row's cells' inline nodes (row order, then column order) - and reads\n * `node.header[c].length` / `node.rows[r][c].length` off the table node itself to\n * recover cell boundaries within the flat list.\n *\n * Total: never throws. At `depth >= {@link MAX_DEPTH}` the node's handler is invoked\n * with an empty children list instead of recursing further.\n *\n * @param node - The AST node to fold\n * @param handlers - The total {@link MarkdownHandlers} table, one handler per element\n * @param depth - The starting recursion depth (pass `0` at the entry point)\n * @returns The folded `T`\n *\n * @example\n * ```ts\n * const countHandlers: MarkdownHandlers<number> = {\n * document: (_, children) => children.reduce((a, b) => a + b, 1),\n * // ...one handler per element, each summing its folded children\n * }\n * foldNode(document, countHandlers, 0) // total node count\n * ```\n */\nexport function foldNode<T>(node: MarkdownNode, handlers: MarkdownHandlers<T>, depth: number): T {\n\tfunction dispatch(current: MarkdownNode, children: readonly T[]): T {\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\t\treturn handlers.document(current, children)\n\t\t\tcase 'heading':\n\t\t\t\treturn handlers.heading(current, children)\n\t\t\tcase 'paragraph':\n\t\t\t\treturn handlers.paragraph(current, children)\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn handlers.thematicBreak(current, children)\n\t\t\tcase 'blockquote':\n\t\t\t\treturn handlers.blockquote(current, children)\n\t\t\tcase 'codeBlock':\n\t\t\t\treturn handlers.codeBlock(current, children)\n\t\t\tcase 'list':\n\t\t\t\treturn handlers.list(current, children)\n\t\t\tcase 'listItem':\n\t\t\t\treturn handlers.listItem(current, children)\n\t\t\tcase 'table':\n\t\t\t\treturn handlers.table(current, children)\n\t\t\tcase 'text':\n\t\t\t\treturn handlers.text(current, children)\n\t\t\tcase 'emphasis':\n\t\t\t\treturn handlers.emphasis(current, children)\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn handlers.codeSpan(current, children)\n\t\t\tcase 'link':\n\t\t\t\treturn handlers.link(current, children)\n\t\t}\n\t}\n\n\tfunction childNodes(current: MarkdownNode): readonly MarkdownNode[] {\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\tcase 'heading':\n\t\t\tcase 'paragraph':\n\t\t\tcase 'blockquote':\n\t\t\tcase 'listItem':\n\t\t\tcase 'emphasis':\n\t\t\tcase 'link':\n\t\t\t\treturn current.children\n\t\t\tcase 'list':\n\t\t\t\treturn current.items\n\t\t\tcase 'table': {\n\t\t\t\tconst header = current.header.flatMap((cell) => cell)\n\t\t\t\tconst rows = current.rows.flatMap((row) => row.flatMap((cell) => cell))\n\t\t\t\treturn [...header, ...rows]\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn []\n\t\t}\n\t}\n\n\tfunction fold(current: MarkdownNode, level: number): T {\n\t\tif (level >= MAX_DEPTH) return dispatch(current, [])\n\t\tconst children = childNodes(current).map((child) => fold(child, level + 1))\n\t\treturn dispatch(current, children)\n\t}\n\n\treturn fold(node, depth)\n}\n\n/**\n * Rewrite a {@link MarkdownDocument} bottom-up (copy-on-write) - each node's children\n * are rewritten first (post-order), then `rewrite` is applied to the node itself; the\n * document ROOT is never passed to `rewrite` (the `element: 'document'` invariant\n * always holds). A table's inline cells and a list's items ARE rewritten.\n *\n * @remarks\n * Never mutates `document` - every level is rebuilt into a fresh object/array, even\n * when `rewrite` returns its input unchanged. When `rewrite` returns a node whose\n * `element` does not fit the slot it was called for (a block slot handed a\n * non-{@link BlockNode}, an inline slot handed a non-{@link InlineNode}, a list-item\n * slot handed a non-`listItem`), the ill-fitting result is discarded and the\n * freshly-rebuilt (unrewritten-at-this-level) node is kept instead - `rewriteDocument`\n * stays total and never produces a structurally invalid document.\n *\n * Descent is capped at {@link MAX_DEPTH}, the same cap {@link walkNodes} and\n * {@link foldNode} observe: at `depth >= MAX_DEPTH` the subtree is passed through\n * UNCHANGED (by reference, not rebuilt, and `rewrite` is not invoked on it) instead of\n * recursing further, so a pathologically deep adopted document cannot exhaust the\n * call stack. {@link MarkdownInterface.map} inherits this cap since it delegates here.\n *\n * @param document - The document AST to rewrite\n * @param rewrite - The bottom-up {@link MarkdownRewriteHandler}\n * @returns A new, rewritten {@link MarkdownDocument}\n *\n * @example\n * ```ts\n * rewriteDocument(document, (node) =>\n * node.element === 'text' ? { element: 'text', value: node.value.toUpperCase() } : node,\n * )\n * ```\n */\nexport function rewriteDocument(\n\tdocument: MarkdownDocument,\n\trewrite: MarkdownRewriteHandler,\n): MarkdownDocument {\n\tfunction rewriteInline(node: InlineNode, depth: number): InlineNode {\n\t\tif (depth >= MAX_DEPTH) return node\n\t\tconst rebuilt = rebuildInline(node, depth)\n\t\tconst result = rewrite(rebuilt)\n\t\treturn isInlineNode(result) ? result : rebuilt\n\t}\n\n\tfunction rewriteBlock(node: BlockNode, depth: number): BlockNode {\n\t\tif (depth >= MAX_DEPTH) return node\n\t\tconst rebuilt = rebuildBlock(node, depth)\n\t\tconst result = rewrite(rebuilt)\n\t\treturn isBlockNode(result) ? result : rebuilt\n\t}\n\n\tfunction rewriteItem(item: ListItemNode, depth: number): ListItemNode {\n\t\tif (depth >= MAX_DEPTH) return item\n\t\tconst rebuilt: ListItemNode = {\n\t\t\telement: 'listItem',\n\t\t\tchildren: item.children.map((child) => rewriteBlock(child, depth + 1)),\n\t\t}\n\t\tconst result = rewrite(rebuilt)\n\t\treturn result.element === 'listItem' ? result : rebuilt\n\t}\n\n\tfunction rebuildInline(node: InlineNode, depth: number): InlineNode {\n\t\tswitch (node.element) {\n\t\t\tcase 'emphasis':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'link':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'text':\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn node\n\t\t}\n\t}\n\n\tfunction rebuildBlock(node: BlockNode, depth: number): BlockNode {\n\t\tswitch (node.element) {\n\t\t\tcase 'heading':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'paragraph':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'blockquote':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteBlock(child, depth + 1)) }\n\t\t\tcase 'list':\n\t\t\t\treturn { ...node, items: node.items.map((item) => rewriteItem(item, depth + 1)) }\n\t\t\tcase 'table':\n\t\t\t\treturn {\n\t\t\t\t\t...node,\n\t\t\t\t\theader: node.header.map((cell) => cell.map((inline) => rewriteInline(inline, depth + 1))),\n\t\t\t\t\trows: node.rows.map((row) =>\n\t\t\t\t\t\trow.map((cell) => cell.map((inline) => rewriteInline(inline, depth + 1))),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\tcase 'codeBlock':\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn node\n\t\t}\n\t}\n\n\treturn { element: 'document', children: document.children.map((child) => rewriteBlock(child, 0)) }\n}\n\n/**\n * Concatenate the `value` / `code` content of every descendant text / code-span /\n * code-block node under `node`, in walk order - the plain-text projection of an AST\n * (search indexing, word counts, a text-only preview).\n *\n * @remarks\n * Total: never throws. Descent stops at {@link MAX_DEPTH} (contributes `''` past the\n * cap instead of recursing further).\n *\n * @param node - The AST node to flatten (a full document, or any sub-node)\n * @returns The concatenated text content\n *\n * @example\n * ```ts\n * flattenText({ element: 'paragraph', children: [\n * { element: 'text', value: 'a ' },\n * { element: 'codeSpan', value: 'b' },\n * ] })\n * // 'a b'\n * ```\n */\nexport function flattenText(node: MarkdownNode): string {\n\tfunction flatten(current: MarkdownNode, depth: number): string {\n\t\tif (depth >= MAX_DEPTH) return ''\n\t\tswitch (current.element) {\n\t\t\tcase 'text':\n\t\t\t\treturn current.value\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn current.value\n\t\t\tcase 'codeBlock':\n\t\t\t\treturn current.code\n\t\t\tcase 'document':\n\t\t\tcase 'heading':\n\t\t\tcase 'paragraph':\n\t\t\tcase 'blockquote':\n\t\t\tcase 'listItem':\n\t\t\tcase 'emphasis':\n\t\t\tcase 'link':\n\t\t\t\treturn current.children.map((child) => flatten(child, depth + 1)).join('')\n\t\t\tcase 'list':\n\t\t\t\treturn current.items.map((item) => flatten(item, depth + 1)).join('')\n\t\t\tcase 'table': {\n\t\t\t\tconst header = current.header\n\t\t\t\t\t.map((cell) => cell.map((inline) => flatten(inline, depth + 1)).join(''))\n\t\t\t\t\t.join('')\n\t\t\t\tconst rows = current.rows\n\t\t\t\t\t.map((row) =>\n\t\t\t\t\t\trow.map((cell) => cell.map((inline) => flatten(inline, depth + 1)).join('')).join(''),\n\t\t\t\t\t)\n\t\t\t\t\t.join('')\n\t\t\t\treturn header + rows\n\t\t\t}\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn ''\n\t\t\tdefault:\n\t\t\t\treturn ''\n\t\t}\n\t}\n\treturn flatten(node, 0)\n}\n","import type {\n\tBlockNode,\n\tInlineNode,\n\tListItemNode,\n\tListNode,\n\tMarkdownDocument,\n\tTableAlign,\n\tTableNode,\n} from './types.js'\nimport {\n\tcoalesceText,\n\tleadingIndent,\n\textractFence,\n\textractHeading,\n\textractListItem,\n\tscanInline,\n\tsplitLines,\n\tsplitTableRow,\n\tstartsBlock,\n\tstripQuote,\n\ttableAlignments,\n} from './helpers.js'\nimport { isBlankLine, isFenceClose, isQuote, isTableStart, isThematicBreak } from './validators.js'\nimport { MAX_DEPTH } from './constants.js'\nimport { isNonEmptyArray } from '@orkestrel/contract'\n\n/**\n * Parses a run of markdown lines into a block AST, recursing into nested\n * blockquotes, list items, and depth-capped degrade paragraphs.\n *\n * @param lines - The markdown lines to parse.\n * @param depth - The current recursion depth (blockquotes/lists increment it).\n * @returns The parsed block nodes.\n */\nexport function parseBlocks(lines: readonly string[], depth: number): readonly BlockNode[] {\n\tif (depth >= MAX_DEPTH) {\n\t\treturn lines.length > 0\n\t\t\t? [{ element: 'paragraph', children: [{ element: 'text', value: lines.join('\\n') }] }]\n\t\t\t: []\n\t}\n\tconst blocks: BlockNode[] = []\n\tlet index = 0\n\twhile (index < lines.length) {\n\t\tconst line = lines[index] ?? ''\n\t\tif (isBlankLine(line)) {\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tconst fence = extractFence(line)\n\t\tif (fence) {\n\t\t\tconst body: string[] = []\n\t\t\tindex += 1\n\t\t\twhile (index < lines.length && !isFenceClose(lines[index] ?? '', fence.marker)) {\n\t\t\t\tbody.push(lines[index] ?? '')\n\t\t\t\tindex += 1\n\t\t\t}\n\t\t\tindex += 1 // step past the closing fence (a no-op past EOF)\n\t\t\tblocks.push({\n\t\t\t\telement: 'codeBlock',\n\t\t\t\t...(fence.lang === undefined ? {} : { lang: fence.lang }),\n\t\t\t\tcode: body.join('\\n'),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif (isThematicBreak(line)) {\n\t\t\tblocks.push({ element: 'thematicBreak' })\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tconst heading = extractHeading(line)\n\t\tif (heading) {\n\t\t\tblocks.push({\n\t\t\t\telement: 'heading',\n\t\t\t\tlevel: heading.level,\n\t\t\t\tchildren: parseInline(heading.text),\n\t\t\t})\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (isQuote(line)) {\n\t\t\tconst quoted: string[] = []\n\t\t\twhile (index < lines.length && isQuote(lines[index] ?? '')) {\n\t\t\t\tquoted.push(stripQuote(lines[index] ?? ''))\n\t\t\t\tindex += 1\n\t\t\t}\n\t\t\tblocks.push({ element: 'blockquote', children: parseBlocks(quoted, depth + 1) })\n\t\t\tcontinue\n\t\t}\n\t\tif (isTableStart(line, lines[index + 1])) {\n\t\t\tconst table = collectTable(lines, index)\n\t\t\tblocks.push(table.node)\n\t\t\tindex = table.next\n\t\t\tcontinue\n\t\t}\n\t\tif (extractListItem(line)) {\n\t\t\tconst list = collectList(lines, index, depth)\n\t\t\tblocks.push(list.node)\n\t\t\tindex = list.next\n\t\t\tcontinue\n\t\t}\n\t\tconst paragraph: string[] = []\n\t\twhile (\n\t\t\tindex < lines.length &&\n\t\t\t!isBlankLine(lines[index] ?? '') &&\n\t\t\t!(isNonEmptyArray(paragraph) && startsBlock(lines, index))\n\t\t) {\n\t\t\tparagraph.push((lines[index] ?? '').trim())\n\t\t\tindex += 1\n\t\t}\n\t\tblocks.push({ element: 'paragraph', children: parseInline(paragraph.join('\\n')) })\n\t}\n\treturn blocks\n}\n\n/**\n * Collects a GFM table starting at a header row, parsing the header, the\n * alignment row, and every contiguous body row that follows.\n *\n * @param lines - The markdown lines to scan.\n * @param start - The index of the header row.\n * @returns The parsed table node and the index of the first line after it.\n */\nexport function collectTable(\n\tlines: readonly string[],\n\tstart: number,\n): { readonly node: TableNode; readonly next: number } {\n\tconst headerCells = splitTableRow(lines[start] ?? '')\n\tconst columns = headerCells.length\n\tconst header = headerCells.map((cell) => parseInline(cell.trim()))\n\tconst align = tableAlignments(lines[start + 1] ?? '')\n\tconst padded: TableAlign[] = []\n\tfor (let column = 0; column < columns; column += 1) padded.push(align[column] ?? 'none')\n\tconst rows: (readonly InlineNode[])[][] = []\n\tlet index = start + 2\n\twhile (\n\t\tindex < lines.length &&\n\t\t!isBlankLine(lines[index] ?? '') &&\n\t\t(lines[index] ?? '').includes('|')\n\t) {\n\t\tconst cells = splitTableRow(lines[index] ?? '')\n\t\tconst row: (readonly InlineNode[])[] = []\n\t\tfor (let column = 0; column < columns; column += 1)\n\t\t\trow.push(parseInline((cells[column] ?? '').trim()))\n\t\trows.push(row)\n\t\tindex += 1\n\t}\n\treturn { node: { element: 'table', header, rows, align: padded }, next: index }\n}\n\n/**\n * Collects a list starting at the first item, gathering sibling items at the\n * same indent/ordering and recursing into each item's own block content.\n *\n * @param lines - The markdown lines to scan.\n * @param start - The index of the first list item.\n * @param depth - The current recursion depth (each item recurses at `depth + 1`).\n * @returns The parsed list node and the index of the first line after it.\n */\nexport function collectList(\n\tlines: readonly string[],\n\tstart: number,\n\tdepth: number,\n): { readonly node: ListNode; readonly next: number } {\n\tconst first = extractListItem(lines[start] ?? '')\n\tconst ordered = first?.ordered ?? false\n\tconst startOrdinal = first?.start ?? 1\n\tconst topIndent = first?.indent ?? 0\n\tconst items: ListItemNode[] = []\n\tlet index = start\n\twhile (index < lines.length) {\n\t\tconst parsed = extractListItem(lines[index] ?? '')\n\t\t// A sibling item shares the list's (top) indent + ordering; anything else stops\n\t\t// the top loop (a deeper item is a nested list, gathered as continuation below).\n\t\tif (!parsed || parsed.indent > topIndent || parsed.ordered !== ordered) break\n\t\tconst itemLines: string[] = [parsed.content]\n\t\tconst continuation = parsed.marker\n\t\tindex += 1\n\t\twhile (index < lines.length) {\n\t\t\tconst next = lines[index] ?? ''\n\t\t\tif (isBlankLine(next)) {\n\t\t\t\tconst after = lines[index + 1] ?? ''\n\t\t\t\tif (\n\t\t\t\t\tindex + 1 < lines.length &&\n\t\t\t\t\t!isBlankLine(after) &&\n\t\t\t\t\tleadingIndent(after) >= continuation\n\t\t\t\t) {\n\t\t\t\t\titemLines.push('')\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (leadingIndent(next) >= continuation) {\n\t\t\t\titemLines.push(next.slice(continuation))\n\t\t\t\tindex += 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (extractListItem(next) || startsBlock(lines, index)) break\n\t\t\titemLines.push(next.trim()) // a lazy paragraph-continuation line\n\t\t\tindex += 1\n\t\t}\n\t\titems.push({ element: 'listItem', children: parseBlocks(itemLines, depth + 1) })\n\t}\n\treturn { node: { element: 'list', ordered, start: startOrdinal, items }, next: index }\n}\n\n/**\n * Parses a markdown string into a typed {@link MarkdownDocument} AST via the\n * block phase.\n *\n * @param markdown - The markdown source to parse.\n * @returns The parsed document.\n */\nexport function parseDocument(markdown: string): MarkdownDocument {\n\treturn { element: 'document', children: parseBlocks(splitLines(markdown), 0) }\n}\n\n/**\n * Parses inline markdown text (emphasis, code spans, links) into inline AST\n * nodes, coalescing adjacent text runs.\n *\n * @param text - The inline markdown text to parse.\n * @returns The parsed inline nodes.\n */\nexport function parseInline(text: string): readonly InlineNode[] {\n\treturn coalesceText(scanInline(text, 0, text.length))\n}\n","import {\n\tbooleanShape,\n\tintegerShape,\n\tliteralShape,\n\tobjectShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\n\n// AGENTS section 14 / 4.6.1: shapers are `ContractShape` VALUES, not functions\n// or types - a JSON-Schema blueprint the compilers (factories.ts) turn into a\n// guard / parser / schema / generator in lockstep. Only the NON-recursive\n// parts of the markdown AST (types.ts) can be expressed here: a shape tree has\n// no lazy/self-referential node, so any type whose fields recurse into\n// `BlockNode` / `InlineNode` / `MarkdownNode` (EmphasisNode, LinkNode,\n// HeadingNode, ParagraphNode, ListItemNode, ListNode, TableNode,\n// BlockquoteNode, MarkdownDocument) is skipped here and stays guard-only\n// (validators.ts) via `lazyOf`.\n\n/**\n * The shape of a {@link TextNode} - a plain-text leaf inline run.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { textShape } from '@src/core'\n *\n * const text = createContract(textShape)\n * text.is({ element: 'text', value: 'hi' }) // true\n * ```\n */\nexport const textShape = objectShape({\n\telement: literalShape(['text']),\n\tvalue: stringShape(),\n})\n\n/**\n * The shape of a {@link CodeSpanNode} - an inline code span (`` `code` ``).\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { codeSpanShape } from '@src/core'\n *\n * const codeSpan = createContract(codeSpanShape)\n * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true\n * ```\n */\nexport const codeSpanShape = objectShape({\n\telement: literalShape(['codeSpan']),\n\tvalue: stringShape(),\n})\n\n/**\n * The shape of a {@link CodeBlockNode} - a fenced code block. `lang` is\n * optional (absent when the opening fence carries no info-string).\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { codeBlockShape } from '@src/core'\n *\n * const codeBlock = createContract(codeBlockShape)\n * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true\n * codeBlock.is({ element: 'codeBlock', code: 'x', lang: 'ts' }) // true\n * ```\n */\nexport const codeBlockShape = objectShape({\n\telement: literalShape(['codeBlock']),\n\tlang: optionalShape(stringShape()),\n\tcode: stringShape(),\n})\n\n/**\n * The shape of a {@link ThematicBreakNode} - a horizontal rule. Carries no\n * fields beyond its `element` discriminant.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { thematicBreakShape } from '@src/core'\n *\n * const thematicBreak = createContract(thematicBreakShape)\n * thematicBreak.is({ element: 'thematicBreak' }) // true\n * ```\n */\nexport const thematicBreakShape = objectShape({\n\telement: literalShape(['thematicBreak']),\n})\n\n/**\n * The shape of a {@link TableAlign} - the per-column GFM table alignment\n * literal.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { tableAlignShape } from '@src/core'\n *\n * const tableAlign = createContract(tableAlignShape)\n * tableAlign.is('left') // true\n * tableAlign.is('center') // true\n * tableAlign.is('top') // false\n * ```\n */\nexport const tableAlignShape = literalShape(['none', 'left', 'right', 'center'])\n\n/**\n * The shape of {@link ListItemParts} - the parsed parts of a single list-item\n * line the block phase's list detector returns. Fully non-recursive (no\n * nested node fields), so every field shapes directly.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { listItemPartsShape } from '@src/core'\n *\n * const listItemParts = createContract(listItemPartsShape)\n * listItemParts.is({ ordered: false, start: 1, content: 'hi', indent: 0, marker: 2 }) // true\n * ```\n */\nexport const listItemPartsShape = objectShape({\n\tordered: booleanShape(),\n\tstart: integerShape(),\n\tcontent: stringShape(),\n\tindent: integerShape(),\n\tmarker: integerShape(),\n})\n","import type {\n\tBlockNode,\n\tMarkdownDocument,\n\tMarkdownHandlers,\n\tMarkdownInterface,\n\tMarkdownNode,\n\tMarkdownRewriteHandler,\n} from './types.js'\nimport { foldNode, rewriteDocument, walkNodes } from './helpers.js'\nimport { parseDocument } from './parsers.js'\n\n/**\n * A stateful, parsed markdown document - wraps a typed {@link MarkdownDocument} AST\n * with the query (`find` / `filter` / `reduce` / iteration), rewrite (`map`), fold, and\n * streaming operations {@link MarkdownInterface} declares.\n *\n * @remarks\n * - **Construction.** Given a `string`, the constructor runs {@link parseDocument} (the\n * block phase then the inline phase) to build the AST. Given a {@link MarkdownDocument},\n * the document is adopted AS-IS and is NOT re-validated - a caller adopting an\n * untrusted value should gate it with `isMarkdownDocument` first.\n * - **Immutable.** {@link map} never mutates the stored AST - it returns a NEW `Markdown`\n * instance; the document root invariant (`element: 'document'`) always holds.\n * - **Traversal order.** {@link walk} and the `find` / `filter` / `reduce` queries built\n * on it walk the AST depth-first, pre-order, root-inclusive (via {@link walkNodes});\n * `stream` is shallow - only the document's direct block children.\n *\n * @example\n * ```ts\n * import { Markdown, isHeadingNode, renderMarkdown } from '@src/core'\n *\n * const markdown = new Markdown('# Title\\n\\nA **bold** [link](https://x.dev).')\n * const heading = markdown.find(isHeadingNode) // the HeadingNode, or undefined\n * const shouted = markdown.map((node) =>\n * node.element === 'text' ? { element: 'text', value: node.value.toUpperCase() } : node,\n * )\n * renderMarkdown(shouted.document) // '# TITLE\\n\\nA **BOLD** [LINK](https://x.dev).'\n * ```\n */\nexport class Markdown implements MarkdownInterface {\n\treadonly #document: MarkdownDocument\n\n\tconstructor(input: string | MarkdownDocument) {\n\t\tthis.#document = typeof input === 'string' ? parseDocument(input) : input\n\t}\n\n\t/** The stored {@link MarkdownDocument} AST root. */\n\tget document(): MarkdownDocument {\n\t\treturn this.#document\n\t}\n\n\t/**\n\t * THE deep traversal - a lazy, depth-first, pre-order, root-inclusive generator\n\t * over every {@link MarkdownNode} in the document. `find` / `filter` / `reduce`\n\t * all iterate this single traversal.\n\t *\n\t * @example\n\t * ```ts\n\t * for (const node of markdown.walk()) {\n\t * // every node, depth-first, pre-order, root-inclusive\n\t * }\n\t *\n\t * // also consumable by for-await - JS accepts a sync iterable in for-await\n\t * for await (const node of markdown.walk()) {\n\t * // same sequence, no separate async iterator needed\n\t * }\n\t * ```\n\t */\n\t*walk(): Generator<MarkdownNode> {\n\t\tyield* walkNodes(this.#document)\n\t}\n\n\t// Finds the first node (depth-first, pre-order) narrowed by a type guard.\n\tfind<T extends MarkdownNode>(guard: (node: MarkdownNode) => node is T): T | undefined\n\t// Finds the first node (depth-first, pre-order) matching a predicate.\n\tfind(predicate: (node: MarkdownNode) => boolean): MarkdownNode | undefined\n\tfind(predicate: (node: MarkdownNode) => boolean): MarkdownNode | undefined {\n\t\tfor (const node of this.walk()) if (predicate(node)) return node\n\t\treturn undefined\n\t}\n\n\t// Collects every node (depth-first, pre-order) narrowed by a type guard.\n\tfilter<T extends MarkdownNode>(guard: (node: MarkdownNode) => node is T): readonly T[]\n\t// Collects every node (depth-first, pre-order) matching a predicate.\n\tfilter(predicate: (node: MarkdownNode) => boolean): readonly MarkdownNode[]\n\tfilter(predicate: (node: MarkdownNode) => boolean): readonly MarkdownNode[] {\n\t\tconst out: MarkdownNode[] = []\n\t\tfor (const node of this.walk()) if (predicate(node)) out.push(node)\n\t\treturn out\n\t}\n\n\t/** Rewrites the AST bottom-up (copy-on-write) and returns a new {@link Markdown}. */\n\tmap(rewrite: MarkdownRewriteHandler): MarkdownInterface {\n\t\treturn new Markdown(rewriteDocument(this.#document, rewrite))\n\t}\n\n\t/** Folds the AST depth-first, pre-order into an accumulator. */\n\treduce<T>(callback: (accumulator: T, node: MarkdownNode) => T, initial: T): T {\n\t\tlet accumulator = initial\n\t\tfor (const node of this.walk()) accumulator = callback(accumulator, node)\n\t\treturn accumulator\n\t}\n\n\t/** Runs a total catamorphism over the document using a {@link MarkdownHandlers} table. */\n\tfold<T>(handlers: MarkdownHandlers<T>): T {\n\t\treturn foldNode(this.#document, handlers, 0)\n\t}\n\n\t/**\n\t * A web-standard {@link ReadableStream} over the document's top-level block nodes\n\t * (shallow, source order) - a fresh, pull-based source per call: one block is\n\t * enqueued per `pull`, so a slow reader's backpressure is respected. Cancellable,\n\t * async-iterable wherever the platform supports it (Node, Deno), and pipeable\n\t * through any {@link TransformStream} / {@link WritableStream}.\n\t *\n\t * @example\n\t * ```ts\n\t * // universal - works in every ReadableStream-supporting environment\n\t * const reader = markdown.stream().getReader()\n\t * for (let result = await reader.read(); !result.done; result = await reader.read()) {\n\t * console.log(result.value) // one BlockNode\n\t * }\n\t *\n\t * // Node / Deno / Firefox support async iteration of ReadableStream natively;\n\t * // other environments should use the reader loop above instead.\n\t * for await (const block of markdown.stream()) {\n\t * console.log(block)\n\t * }\n\t * ```\n\t */\n\tstream(): ReadableStream<BlockNode> {\n\t\tconst blocks = this.#document.children\n\t\tlet index = 0\n\t\treturn new ReadableStream<BlockNode>({\n\t\t\tpull(controller) {\n\t\t\t\tif (index < blocks.length) {\n\t\t\t\t\tcontroller.enqueue(blocks[index])\n\t\t\t\t\tindex += 1\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tCodeBlockNode,\n\tCodeSpanNode,\n\tMarkdownDocument,\n\tMarkdownInterface,\n\tTextNode,\n\tThematicBreakNode,\n} from './types.js'\nimport { createContract } from '@orkestrel/contract'\nimport { Markdown } from './Markdown.js'\nimport { codeBlockShape, codeSpanShape, textShape, thematicBreakShape } from './shapers.js'\n\n/**\n * Create a stateful markdown handle from a markdown string or an already-parsed\n * {@link MarkdownDocument} - a typed AST plus the query, rewrite, and fold operations\n * {@link MarkdownInterface} exposes.\n *\n * @remarks\n * Given a `string`, runs a block phase (headings / paragraphs / lists / GFM tables /\n * fenced code / blockquotes / thematic breaks) then an inline phase (emphasis /\n * inline code / links) to build a render-agnostic {@link MarkdownDocument}. Given a\n * {@link MarkdownDocument}, adopts it AS-IS without re-validation - gate an untrusted\n * value with `isMarkdownDocument` first. Pure + total parse (malformed markdown\n * degrades to text, never throws) and zero-dependency - a hand-written scanner, no\n * regex-only structural parse, linear-time (no ReDoS).\n *\n * @param input - A markdown string to parse, or an already-parsed {@link MarkdownDocument}\n * @returns A working {@link MarkdownInterface}\n *\n * @example\n * ```ts\n * import { createMarkdown } from '@src/core'\n *\n * const markdown = createMarkdown('# Hi\\n\\nRead the [guide](./guide.md).')\n * markdown.document.children[0] // { element: 'heading', ... }\n * ```\n */\nexport function createMarkdown(input: string | MarkdownDocument): MarkdownInterface {\n\treturn new Markdown(input)\n}\n\n/**\n * Compile the {@link textShape} into a {@link ContractInterface} for\n * {@link TextNode} - a guard, coercing parser, JSON Schema, and seeded\n * generator from one shape declaration (AGENTS §14).\n *\n * @returns A `TextNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createTextContract } from '@src/core'\n *\n * const text = createTextContract()\n * text.is({ element: 'text', value: 'hi' }) // true\n * ```\n */\nexport function createTextContract(): ContractInterface<TextNode> {\n\treturn createContract(textShape)\n}\n\n/**\n * Compile the {@link codeSpanShape} into a {@link ContractInterface} for\n * {@link CodeSpanNode} - a guard, coercing parser, JSON Schema, and seeded\n * generator from one shape declaration (AGENTS §14).\n *\n * @returns A `CodeSpanNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createCodeSpanContract } from '@src/core'\n *\n * const codeSpan = createCodeSpanContract()\n * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true\n * ```\n */\nexport function createCodeSpanContract(): ContractInterface<CodeSpanNode> {\n\treturn createContract(codeSpanShape)\n}\n\n/**\n * Compile the {@link codeBlockShape} into a {@link ContractInterface} for\n * {@link CodeBlockNode} - a guard, coercing parser, JSON Schema, and seeded\n * generator from one shape declaration (AGENTS §14).\n *\n * @returns A `CodeBlockNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createCodeBlockContract } from '@src/core'\n *\n * const codeBlock = createCodeBlockContract()\n * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true\n * ```\n */\nexport function createCodeBlockContract(): ContractInterface<CodeBlockNode> {\n\treturn createContract(codeBlockShape)\n}\n\n/**\n * Compile the {@link thematicBreakShape} into a {@link ContractInterface} for\n * {@link ThematicBreakNode} - a guard, coercing parser, JSON Schema, and\n * seeded generator from one shape declaration (AGENTS §14).\n *\n * @returns A `ThematicBreakNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createThematicBreakContract } from '@src/core'\n *\n * const thematicBreak = createThematicBreakContract()\n * thematicBreak.is({ element: 'thematicBreak' }) // true\n * ```\n */\nexport function createThematicBreakContract(): ContractInterface<ThematicBreakNode> {\n\treturn createContract(thematicBreakShape)\n}\n"],"x_google_ignoreList":[1],"mappings":";;;;;;;AAMA,IAAa,mCAAwC,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAU;AAAK,CAAC;;;;;;;;;;AAW/F,IAAa,YAAY;ACED,OAAO,OAAO;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAID,SAAS,OAAO,OAAO;CACtB,OAAO,UAAU;AAClB;;AAEA,SAAS,YAAY,OAAO;CAC3B,OAAO,UAAU,KAAK;AACvB;;AAMA,SAAS,SAAS,OAAO;CACxB,OAAO,OAAO,UAAU;AACzB;;;;;;;AAOA,SAAS,SAAS,OAAO;CACxB,OAAO,OAAO,UAAU;AACzB;;AAEA,SAAS,eAAe,OAAO;CAC9B,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AAC1D;;AAEA,SAAS,UAAU,OAAO;CACzB,OAAO,OAAO,UAAU,KAAK;AAC9B;;AAEA,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;;AAkEA,SAAS,cAAc,OAAO;CAC7B,OAAO,SAAS,KAAK,KAAK,MAAM,WAAW;AAC5C;;AAmBA,SAAS,iBAAiB,OAAO;CA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AAI,UAAU,IAAI,GAAG,IAAI,KAAK,IAAI;EAClE,OAAO;CACR;;CAGA,IAAI,SAAoD;EACvD,OAAO,IAAI,SAAS,gBAAgB,KAAKA,WAAW,OAAO,CAAC;CAC7D;;CAGA,OAAU,UAAqD,SAAe;EAC7E,IAAI,cAAc;EAClB,KAAK,MAAM,QAAQ,KAAK,KAAK,GAAG,cAAc,SAAS,aAAa,IAAI;EACxE,OAAO;CACR;;CAGA,KAAQ,UAAkC;EACzC,OAAO,SAAS,KAAKA,WAAW,UAAU,CAAC;CAC5C;;;;;;;;;;;;;;;;;;;;;;;CAwBA,SAAoC;EACnC,MAAM,SAAS,KAAKA,UAAU;EAC9B,IAAI,QAAQ;EACZ,OAAO,IAAI,eAA0B,EACpC,KAAK,YAAY;GAChB,IAAI,QAAQ,OAAO,QAAQ;IAC1B,WAAW,QAAQ,OAAO,MAAM;IAChC,SAAS;GACV,OACC,WAAW,MAAM;EAEnB,EACD,CAAC;CACF;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1GA,SAAgB,eAAe,OAAqD;CACnF,OAAO,IAAI,SAAS,KAAK;AAC1B;;;;;;;;;;;;;;;;AAiBA,SAAgB,qBAAkD;CACjE,OAAO,eAAe,SAAS;AAChC;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA0D;CACzE,OAAO,eAAe,aAAa;AACpC;;;;;;;;;;;;;;;;AAiBA,SAAgB,0BAA4D;CAC3E,OAAO,eAAe,cAAc;AACrC;;;;;;;;;;;;;;;;AAiBA,SAAgB,8BAAoE;CACnF,OAAO,eAAe,kBAAkB;AACzC"}
1
+ {"version":3,"file":"index.js","names":["#document"],"sources":["../../../src/core/constants.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/parsers.ts","../../../src/core/shapers.ts","../../../src/core/Markdown.ts","../../../src/core/factories.ts"],"sourcesContent":["/**\n * The URL schemes `renderHTML` permits on a link `href` - anything else (notably\n * `javascript:`, `data:`, `vbscript:`, `file:`) is dropped to an empty `href` so a\n * hostile link can never execute. Frozen, lower-case; a relative / anchor /\n * scheme-less `href` (no `scheme:` prefix) is always allowed.\n */\nexport const SAFE_URL_SCHEMES: ReadonlySet<string> = new Set(['http', 'https', 'mailto', 'tel'])\n\n/**\n * The maximum recursion depth the parse pipeline (`parseDocument` and its\n * `parsers.ts` helpers) and the `helpers.ts` traversal / render functions\n * (`renderHTML`, `renderMarkdown`, `walkNodes`, `foldNode`) honor before degrading to\n * literal text - bounds blockquote nesting, inline nesting (emphasis / links), and\n * traversal/render recursion so pathological or hostile input (deeply nested\n * blockquotes, runaway emphasis) cannot exhaust the call stack. Past this depth the\n * parser treats the remaining content as literal text instead of recursing further.\n */\nexport const MAX_DEPTH = 64\n","import type { Guard } from '@orkestrel/contract'\nimport type {\n\tBlockNode,\n\tBlockquoteNode,\n\tCodeBlockNode,\n\tCodeSpanNode,\n\tEmphasisNode,\n\tHeadingNode,\n\tInlineNode,\n\tLinkNode,\n\tListNode,\n\tMarkdownDocument,\n\tMarkdownNode,\n\tParagraphNode,\n\tTableNode,\n\tTextNode,\n\tThematicBreakNode,\n} from './types.js'\nimport {\n\tarrayOf,\n\tisBoolean,\n\tisEmptyString,\n\tisNumber,\n\tisString,\n\tliteralOf,\n\tlazyOf,\n\trecordOf,\n\tunionOf,\n} from '@orkestrel/contract'\nimport { splitTableRow } from './helpers.js'\n\n// AGENTS section 14: guards are total. This file owns two predicate families:\n// line / string structural predicates that test raw strings during parsing\n// (isWhitespace, isEscapable, isQuote, isFenceClose, isThematicBreak,\n// isTableStart), and node guards that narrow a MarkdownNode to one parsed\n// block / inline variant by its element tag.\n\n/**\n * Whether `character` is an inline whitespace character (space / tab / newline) - the\n * emphasis flanking rule's space test.\n *\n * @param character - The character to test\n * @returns `true` when it is inline whitespace\n *\n * @example\n * ```ts\n * isWhitespace(' ') // true\n * isWhitespace('a') // false\n * ```\n */\nexport function isWhitespace(character: string): boolean {\n\treturn character === ' ' || character === '\\t' || character === '\\n'\n}\n\n/**\n * Whether `character` is escapable by a leading backslash - the ASCII punctuation\n * markdown gives meaning to (so `\\*` becomes `*` but `\\.` stays `\\.`).\n *\n * @param character - The single character after a backslash\n * @returns `true` when a backslash before it is an escape\n *\n * @example\n * ```ts\n * isEscapable('*') // true\n * isEscapable('a') // false\n * ```\n */\nexport function isEscapable(character: string): boolean {\n\treturn /[\\\\`*_{}[\\]()#+\\-.!>~|]/.test(character)\n}\n\n/**\n * Whether `line` is blank - empty, or containing only whitespace - the markdown\n * definition of a blank line that block parsing uses to separate paragraphs, skip\n * gaps, and end list continuations.\n *\n * @param line - The candidate line\n * @returns `true` when the line is blank\n *\n * @example\n * ```ts\n * isBlankLine(' ') // true\n * ```\n */\nexport function isBlankLine(line: string): boolean {\n\treturn isEmptyString(line.trim())\n}\n\n/**\n * Whether `line` is a blockquote line (`>` optionally indented up to three spaces) -\n * its content is de-quoted by {@link stripQuote}.\n *\n * @param line - The candidate line\n * @returns `true` when the line begins a blockquote\n *\n * @example\n * ```ts\n * isQuote('> quoted') // true\n * ```\n */\nexport function isQuote(line: string): boolean {\n\treturn /^\\s{0,3}>/.test(line)\n}\n\n/**\n * Whether `line` closes a fence opened by `marker` - the same fence character, a run\n * at least as long, and nothing else but surrounding whitespace.\n *\n * @param line - The candidate closing line\n * @param marker - The opening fence's marker run (from {@link extractFence})\n * @returns `true` when `line` closes the fence\n *\n * @example\n * ```ts\n * isFenceClose('```', '```') // true\n * ```\n */\nexport function isFenceClose(line: string, marker: string): boolean {\n\tconst character = marker[0] === '~' ? '~' : '`'\n\tlet index = 0\n\twhile (index < line.length && isFenceWhitespace(line[index])) index++\n\tlet run = 0\n\twhile (index < line.length && line[index] === character) {\n\t\trun++\n\t\tindex++\n\t}\n\tif (run < marker.length) return false\n\twhile (index < line.length && isFenceWhitespace(line[index])) index++\n\treturn index === line.length\n}\n\n/**\n * Whether `character` is a regex-`\\s`-equivalent whitespace character - the\n * character class {@link isFenceClose}'s scan treats as surrounding padding.\n *\n * @param character - The single character to test, or `undefined` past the end of a line\n * @returns `true` when it is whitespace\n *\n * @example\n * ```ts\n * isFenceWhitespace(' ') // true\n * isFenceWhitespace(undefined) // false\n * ```\n */\nexport function isFenceWhitespace(character: string | undefined): boolean {\n\treturn (\n\t\tcharacter === ' ' ||\n\t\tcharacter === '\\t' ||\n\t\tcharacter === '\\n' ||\n\t\tcharacter === '\\r' ||\n\t\tcharacter === '\\f' ||\n\t\tcharacter === '\\v'\n\t)\n}\n\n/**\n * Whether `line` is a thematic break (horizontal rule) - three or more of the SAME\n * marker `-`, `*`, or `_` (optionally space-separated) and nothing else (`---`,\n * `***`, `___`, `- - -`).\n *\n * @param line - The candidate line\n * @returns `true` when the line is a thematic break\n *\n * @example\n * ```ts\n * isThematicBreak('---') // true\n * ```\n */\nexport function isThematicBreak(line: string): boolean {\n\tconst stripped = line.trim().replace(/\\s+/g, '')\n\tif (stripped.length < 3) return false\n\tconst marker = stripped[0]\n\tif (marker !== '-' && marker !== '*' && marker !== '_') return false\n\treturn [...stripped].every((character) => character === marker)\n}\n\n/**\n * Whether the pair (`header`, `delimiter`) opens a GFM table - `delimiter` is a row of\n * `|`-separated cells each matching `:?-+:?`, the GFM rule that a table requires a\n * header row IMMEDIATELY followed by a delimiter row.\n *\n * @param header - The candidate header line\n * @param delimiter - The line after it (the candidate delimiter)\n * @returns `true` when the two lines open a table\n *\n * @example\n * ```ts\n * isTableStart('| a |', '| - |') // true\n * ```\n */\nexport function isTableStart(header: string, delimiter: string | undefined): boolean {\n\tif (delimiter === undefined || !header.includes('|')) return false\n\tconst cells = splitTableRow(delimiter)\n\tif (cells.length === 0) return false\n\treturn cells.every((cell) => /^:?-+:?$/.test(cell.trim()))\n}\n\n// === Block guards\n\n/** Determine whether a node is a heading block. */\nexport function isHeadingNode(node: MarkdownNode): node is HeadingNode {\n\treturn node.element === 'heading'\n}\n\n/**\n * Determine whether a node is a paragraph block.\n *\n * @example\n * ```ts\n * isParagraphNode({ element: 'paragraph', children: [] }) // true\n * ```\n */\nexport function isParagraphNode(node: MarkdownNode): node is ParagraphNode {\n\treturn node.element === 'paragraph'\n}\n\n/**\n * Determine whether a node is a list block.\n *\n * @example\n * ```ts\n * isListNode({ element: 'list', ordered: false, start: 1, items: [] }) // true\n * ```\n */\nexport function isListNode(node: MarkdownNode): node is ListNode {\n\treturn node.element === 'list'\n}\n\n/** Determine whether a node is a GFM table block. */\nexport function isTableNode(node: MarkdownNode): node is TableNode {\n\treturn node.element === 'table'\n}\n\n/**\n * Determine whether a node is a fenced code block.\n *\n * @example\n * ```ts\n * isCodeBlockNode({ element: 'codeBlock', code: 'x' }) // true\n * ```\n */\nexport function isCodeBlockNode(node: MarkdownNode): node is CodeBlockNode {\n\treturn node.element === 'codeBlock'\n}\n\n/**\n * Determine whether a node is a blockquote block.\n *\n * @example\n * ```ts\n * isBlockquoteNode({ element: 'blockquote', children: [] }) // true\n * ```\n */\nexport function isBlockquoteNode(node: MarkdownNode): node is BlockquoteNode {\n\treturn node.element === 'blockquote'\n}\n\n/**\n * Determine whether a node is a thematic break (horizontal rule) block.\n *\n * @example\n * ```ts\n * isThematicBreakNode({ element: 'thematicBreak' }) // true\n * ```\n */\nexport function isThematicBreakNode(node: MarkdownNode): node is ThematicBreakNode {\n\treturn node.element === 'thematicBreak'\n}\n\n// === Inline guards\n\n/**\n * Determine whether a node is a plain text run.\n *\n * @example\n * ```ts\n * isTextNode({ element: 'text', value: 'hi' }) // true\n * ```\n */\nexport function isTextNode(node: MarkdownNode): node is TextNode {\n\treturn node.element === 'text'\n}\n\n/**\n * Determine whether a node is an emphasis run (`*em*` / `**strong**`).\n *\n * @example\n * ```ts\n * isEmphasisNode({ element: 'emphasis', strong: false, children: [] }) // true\n * ```\n */\nexport function isEmphasisNode(node: MarkdownNode): node is EmphasisNode {\n\treturn node.element === 'emphasis'\n}\n\n/**\n * Determine whether a node is an inline code span.\n *\n * @remarks\n * Narrows to {@link CodeSpanNode} - the node whose `element` discriminant is\n * `'codeSpan'`.\n *\n * @example\n * ```ts\n * isCodeSpanNode({ element: 'codeSpan', value: 'x' }) // true\n * ```\n */\nexport function isCodeSpanNode(node: MarkdownNode): node is CodeSpanNode {\n\treturn node.element === 'codeSpan'\n}\n\n/** Determine whether a node is a link. */\nexport function isLinkNode(node: MarkdownNode): node is LinkNode {\n\treturn node.element === 'link'\n}\n\n// === From-unknown AST guards\n//\n// The node guards above narrow an ALREADY-PARSED MarkdownNode by its `element`\n// tag. The guards below instead validate an arbitrary `unknown` value (untrusted\n// input - a deserialized AST, a value crossing a process/RPC boundary) against\n// the full node shape, field by field, composed from @orkestrel/contract\n// combinators. Each guard IS its own hoisted composed value (compiled once at\n// module init, not per call); inline<->block recursion (emphasis/link children,\n// list items, blockquote children) resolves through `lazyOf`, closing over the\n// exported guard names themselves - legal because `lazyOf`'s thunk resolves per\n// call, strictly after module init has assigned every export. @orkestrel/contract\n// guarantees guard totality (AGENTS §14): `lazyOf`, `unionOf`, `recordOf`, and\n// every built-in guard are throw-contained, so a hostile getter, a structural\n// cycle, or pathologically deep input returns `false` rather than throwing -\n// no additional `attempt` wrapping is needed here.\n\n/**\n * Determine whether an arbitrary value is a valid {@link InlineNode} - a text\n * run, emphasis, code span, or link, recursively validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is\n * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link InlineNode}\n *\n * @example\n * ```ts\n * import { isInlineNode } from '@orkestrel/markdown'\n *\n * isInlineNode({ element: 'text', value: 'hi' }) // true\n * isInlineNode({ element: 'text' }) // false - missing `value`\n * ```\n */\nexport const isInlineNode: Guard<InlineNode> = unionOf(\n\trecordOf({ element: literalOf('text'), value: isString }),\n\trecordOf({\n\t\telement: literalOf('emphasis'),\n\t\tstrong: isBoolean,\n\t\tchildren: arrayOf(lazyOf(() => isInlineNode)),\n\t}),\n\trecordOf({ element: literalOf('codeSpan'), value: isString }),\n\trecordOf({\n\t\telement: literalOf('link'),\n\t\thref: isString,\n\t\tchildren: arrayOf(lazyOf(() => isInlineNode)),\n\t}),\n)\n\n/**\n * Determine whether an arbitrary value is a valid {@link BlockNode} - a\n * heading, paragraph, list, table, code block, blockquote, or thematic break,\n * recursively validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is\n * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).\n * A list item's shape is inlined here (and in {@link isMarkdownNode}) rather\n * than named separately - it is used at exactly these two sites.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link BlockNode}\n *\n * @example\n * ```ts\n * import { isBlockNode } from '@orkestrel/markdown'\n *\n * isBlockNode({ element: 'thematicBreak' }) // true\n * isBlockNode({ element: 'heading' }) // false - missing `level` / `children`\n * ```\n */\nexport const isBlockNode: Guard<BlockNode> = unionOf(\n\trecordOf({ element: literalOf('heading'), level: isNumber, children: arrayOf(isInlineNode) }),\n\trecordOf({ element: literalOf('paragraph'), children: arrayOf(isInlineNode) }),\n\trecordOf({\n\t\telement: literalOf('list'),\n\t\tordered: isBoolean,\n\t\tstart: isNumber,\n\t\titems: arrayOf(\n\t\t\trecordOf({ element: literalOf('listItem'), children: arrayOf(lazyOf(() => isBlockNode)) }),\n\t\t),\n\t}),\n\trecordOf({\n\t\telement: literalOf('table'),\n\t\theader: arrayOf(arrayOf(isInlineNode)),\n\t\trows: arrayOf(arrayOf(arrayOf(isInlineNode))),\n\t\talign: arrayOf(literalOf('none', 'left', 'right', 'center')),\n\t}),\n\trecordOf({ element: literalOf('codeBlock'), lang: isString, code: isString }, ['lang']),\n\trecordOf({ element: literalOf('blockquote'), children: arrayOf(lazyOf(() => isBlockNode)) }),\n\trecordOf({ element: literalOf('thematicBreak') }),\n)\n\n/**\n * Determine whether an arbitrary value is a valid {@link MarkdownNode} - the\n * {@link MarkdownDocument} root, a {@link BlockNode}, a {@link ListItemNode}, or\n * an {@link InlineNode}, recursively validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`unionOf`, `recordOf`, `arrayOf`, `lazyOf`) is\n * throw-contained per the `@orkestrel/contract` guard contract (AGENTS §14).\n * A list item's shape is inlined here (and in {@link isBlockNode}) rather than\n * named separately - it is used at exactly these two sites.\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link MarkdownNode}\n *\n * @example\n * ```ts\n * import { isMarkdownNode } from '@orkestrel/markdown'\n *\n * isMarkdownNode({ element: 'text', value: 'hi' }) // true\n * isMarkdownNode({ element: 'bogus' }) // false\n * ```\n */\nexport const isMarkdownNode: Guard<MarkdownNode> = unionOf(\n\tlazyOf(() => isMarkdownDocument),\n\tlazyOf(() => isBlockNode),\n\trecordOf({ element: literalOf('listItem'), children: arrayOf(lazyOf(() => isBlockNode)) }),\n\tlazyOf(() => isInlineNode),\n)\n\n/**\n * Determine whether an arbitrary value is a valid {@link MarkdownDocument} -\n * the parsed-AST root {@link parseDocument} returns, recursively\n * validated.\n *\n * @remarks\n * Total: never throws, even on cyclic or pathologically deep input - every\n * combinator involved (`recordOf`, `arrayOf`) is throw-contained per the\n * `@orkestrel/contract` guard contract (AGENTS §14).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a well-formed {@link MarkdownDocument}\n *\n * @example\n * ```ts\n * import { isMarkdownDocument } from '@orkestrel/markdown'\n *\n * isMarkdownDocument({ element: 'document', children: [] }) // true\n * isMarkdownDocument({ element: 'document' }) // false - missing `children`\n * ```\n */\nexport const isMarkdownDocument: Guard<MarkdownDocument> = recordOf({\n\telement: literalOf('document'),\n\tchildren: arrayOf(isBlockNode),\n})\n","import type {\n\tBlockNode,\n\tEmphasisNode,\n\tInlineNode,\n\tLinkNode,\n\tListItemNode,\n\tListItemParts,\n\tMarkdownDocument,\n\tMarkdownHandlers,\n\tMarkdownNode,\n\tMarkdownRewriteHandler,\n\tTableAlign,\n\tTableNode,\n} from './types.js'\nimport { MAX_DEPTH, SAFE_URL_SCHEMES } from './constants.js'\nimport {\n\tisBlockNode,\n\tisEscapable,\n\tisInlineNode,\n\tisQuote,\n\tisTableStart,\n\tisThematicBreak,\n\tisWhitespace,\n} from './validators.js'\nimport { isEmptyString, isNonEmptyArray, isNonEmptyString, parseInteger } from '@orkestrel/contract'\n\n// Markdown parsing + rendering leaves (pure, total, zero-dependency)\n//\n// The pure leaf primitives {@link parseDocument} composes: the line / block\n// scanners (headings, fences, list items, table rows, quotes, thematic breaks), the\n// inline `scan*` engine (emphasis / links / code with backslash escapes), and the HTML\n// escaping + URL-sanitization the renderer leans on. Every function is PURE, TOTAL, and\n// referentially transparent - malformed input degrades to text, never throws (AGENTS\n// §14) - so each is unit-tested in isolation. The ORCHESTRATION that threads these\n// together (the block / inline / render recursion) lives in parsers.ts's functions,\n// not here (AGENTS §5): a helper is a functional-core leaf, a method is the\n// composition. Inline scanning is index-based (no backtracking regex) so it is\n// linear-time - no ReDoS on adversarial input.\n\n// Text + line utilities\n\n/**\n * Normalize line endings to `\\n` and split a markdown document into its lines - CRLF\n * (`\\r\\n`) and bare CR (`\\r`) both collapse to `\\n` first, so a Windows-origin\n * document parses identically. A single trailing newline does not yield a final\n * empty line.\n *\n * @param markdown - The raw markdown source\n * @returns The document's lines, line-terminators stripped\n *\n * @example\n * ```ts\n * splitLines('a\\r\\nb\\nc') // ['a', 'b', 'c']\n * ```\n */\nexport function splitLines(markdown: string): readonly string[] {\n\tconst lines = markdown.replace(/\\r\\n?/g, '\\n').split('\\n')\n\tif (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()\n\treturn lines\n}\n\n/**\n * The count of leading space / tab characters on `line` (a tab counts as one) - the\n * indent that decides whether a list item's continuation belongs to the item.\n *\n * @param line - The line to measure\n * @returns The number of leading space / tab characters\n *\n * @example\n * ```ts\n * leadingIndent(' text') // 2\n * ```\n */\nexport function leadingIndent(line: string): number {\n\tlet count = 0\n\tfor (const character of line) {\n\t\tif (character === ' ' || character === '\\t') count += 1\n\t\telse break\n\t}\n\treturn count\n}\n\n// Block-level detection\n\n/**\n * Extract an ATX heading line (`#` … `######` followed by text) into its\n * `{ level, text }`, or `undefined` when `line` is not a heading. A run of more than 6\n * `#`s, or `#`s not followed by whitespace + text, is not a\n * heading; an optional closing `###` run is stripped.\n *\n * @param line - The candidate line\n * @returns The heading level (1–6) and its raw inline text, or `undefined`\n *\n * @example\n * ```ts\n * extractHeading('## Title') // { level: 2, text: 'Title' }\n * ```\n */\nexport function extractHeading(\n\tline: string,\n): { readonly level: number; readonly text: string } | undefined {\n\tconst match = /^(#{1,6})(?:\\s+(.*))?$/.exec(line.trimStart())\n\tif (!match || match[1] === undefined) return undefined\n\tconst level = match[1].length\n\tconst text = (match[2] ?? '').replace(/\\s+#+\\s*$/, '').trim()\n\treturn { level, text }\n}\n\n/**\n * Extract a fenced-code opening line (```` ``` ```` or `~~~`, optionally with an info\n * string) into its `{ marker, lang }`, or `undefined` when `line` is not a fence\n * opener. `marker` is the exact fence run (the closer must match the same character +\n * at least the same length); `lang` is the first word of the info string.\n *\n * @param line - The candidate line\n * @returns The fence marker run and its language tag, or `undefined`\n *\n * @example\n * ```ts\n * extractFence('```ts') // { marker: '```', lang: 'ts' }\n * ```\n */\nexport function extractFence(\n\tline: string,\n): { readonly marker: string; readonly lang: string | undefined } | undefined {\n\tconst match = /^\\s*(`{3,}|~{3,})\\s*(.*)$/.exec(line)\n\tif (!match || match[1] === undefined) return undefined\n\tconst info = (match[2] ?? '').trim()\n\t// A backtick in a backtick fence's info string is invalid (ambiguous with a span).\n\tif (match[1].startsWith('`') && info.includes('`')) return undefined\n\tconst lang = isNonEmptyString(info) ? info.split(/\\s+/)[0] : undefined\n\treturn { marker: match[1], lang }\n}\n\n/**\n * Extract a list-item line (`-` / `*` / `+` bullet, or `1.` / `1)` ordinal, followed by\n * a space) into its {@link ListItemParts}, or `undefined` when `line` is not a list\n * item. `content` is the text after the marker; `marker` is the full marker-plus-space\n * width (for measuring a continuation's indent).\n *\n * @param line - The candidate line\n * @returns The list-item parts, or `undefined` when not a list item\n *\n * @example\n * ```ts\n * extractListItem('- item') // { ordered: false, start: 1, content: 'item', indent: 0, marker: 2 }\n * ```\n */\nexport function extractListItem(line: string): ListItemParts | undefined {\n\tconst unordered = /^(\\s*)([-*+])\\s+(.*)$/.exec(line)\n\tif (unordered && unordered[1] !== undefined) {\n\t\tconst indent = unordered[1].length\n\t\tconst content = unordered[3] ?? ''\n\t\treturn { ordered: false, start: 1, content, indent, marker: line.length - content.length }\n\t}\n\tconst ordered = /^(\\s*)(\\d{1,9})[.)]\\s+(.*)$/.exec(line)\n\tif (ordered && ordered[1] !== undefined && ordered[2] !== undefined) {\n\t\tconst indent = ordered[1].length\n\t\tconst content = ordered[3] ?? ''\n\t\treturn {\n\t\t\tordered: true,\n\t\t\tstart: parseInteger(ordered[2]) ?? 1,\n\t\t\tcontent,\n\t\t\tindent,\n\t\t\tmarker: line.length - content.length,\n\t\t}\n\t}\n\treturn undefined\n}\n\n/**\n * Strip one level of blockquote marker (`>` plus one optional following space) from a\n * blockquote line, so the de-quoted lines re-parse as nested blocks.\n *\n * @param line - A blockquote line (per {@link isQuote})\n * @returns The line with its leading `>` (and one space) removed\n *\n * @example\n * ```ts\n * stripQuote('> text') // 'text'\n * ```\n */\nexport function stripQuote(line: string): string {\n\treturn line.replace(/^\\s{0,3}>\\s?/, '')\n}\n\n/**\n * Split one GFM table row into its cell strings - outer pipes are optional, an escaped\n * pipe (`\\|`) inside a cell is NOT a separator (it becomes a literal `|`), and the\n * empty leading / trailing cell produced by an outer `|` is dropped.\n *\n * @param row - The raw table row line\n * @returns The row's cells, in column order\n *\n * @example\n * ```ts\n * splitTableRow('|a|b|') // ['a', 'b']\n * ```\n */\nexport function splitTableRow(row: string): readonly string[] {\n\tconst cells: string[] = []\n\tlet current = ''\n\tconst trimmed = row.trim()\n\tfor (let index = 0; index < trimmed.length; index += 1) {\n\t\tconst character = trimmed[index]\n\t\tif (character === '\\\\' && trimmed[index + 1] === '|') {\n\t\t\tcurrent += '|'\n\t\t\tindex += 1\n\t\t} else if (character === '|') {\n\t\t\tcells.push(current)\n\t\t\tcurrent = ''\n\t\t} else {\n\t\t\tcurrent += character\n\t\t}\n\t}\n\tcells.push(current)\n\tif (isNonEmptyArray<string>(cells) && isEmptyString((cells[0] ?? '').trim())) cells.shift()\n\tif (isNonEmptyArray<string>(cells) && isEmptyString((cells[cells.length - 1] ?? '').trim()))\n\t\tcells.pop()\n\treturn cells\n}\n\n/**\n * Derive the per-column {@link TableAlign} list from a GFM delimiter row - `:---`\n * left, `---:` right, `:---:` center, `---` none.\n *\n * @param delimiter - The table's delimiter row\n * @returns One alignment per column, in column order\n *\n * @example\n * ```ts\n * tableAlignments('| :--- | ---: |') // ['left', 'right']\n * ```\n */\nexport function tableAlignments(delimiter: string): readonly TableAlign[] {\n\treturn splitTableRow(delimiter).map((cell) => {\n\t\tconst text = cell.trim()\n\t\tconst left = text.startsWith(':')\n\t\tconst right = text.endsWith(':')\n\t\tif (left && right) return 'center'\n\t\tif (right) return 'right'\n\t\tif (left) return 'left'\n\t\treturn 'none'\n\t})\n}\n\n// Block phase\n\n/**\n * Whether the line at `index` starts a NEW block kind (heading / fence / thematic\n * break / blockquote / list / table) - the paragraph collector stops at such a line\n * so a block following a paragraph without a blank line still parses (a trusted-input\n * caller writing a `##` heading directly under a paragraph, with no intervening blank\n * line).\n *\n * @param lines - The document's lines\n * @param index - The line index to test\n * @returns `true` when the line begins a different block\n *\n * @example\n * ```ts\n * startsBlock(['text', '## Heading'], 1) // true\n * ```\n */\nexport function startsBlock(lines: readonly string[], index: number): boolean {\n\tconst line = lines[index] ?? ''\n\treturn (\n\t\textractHeading(line) !== undefined ||\n\t\textractFence(line) !== undefined ||\n\t\tisThematicBreak(line) ||\n\t\tisQuote(line) ||\n\t\textractListItem(line) !== undefined ||\n\t\tisTableStart(line, lines[index + 1])\n\t)\n}\n\n// Inline phase\n\n/**\n * Resolve backslash escapes in a raw string to their literal characters - used for a\n * link `href` (which is not otherwise inline-parsed) and any plain text run.\n *\n * @param text - The raw text possibly carrying `\\x` escapes\n * @returns The text with escapable `\\x` reduced to `x`\n *\n * @example\n * ```ts\n * unescapeText('\\\\*hi\\\\*') // '*hi*'\n * ```\n */\nexport function unescapeText(text: string): string {\n\tlet out = ''\n\tfor (let index = 0; index < text.length; index += 1) {\n\t\tconst character = text[index] ?? ''\n\t\tif (character === '\\\\' && isEscapable(text[index + 1] ?? '')) {\n\t\t\tout += text[index + 1] ?? ''\n\t\t\tindex += 1\n\t\t} else {\n\t\t\tout += character\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Merge adjacent text nodes into one - the inline scanner emits a text node per\n * unrecognized character, so coalescing keeps the AST clean and assertion-friendly.\n *\n * @param nodes - The inline nodes (possibly with adjacent text runs)\n * @returns The nodes with consecutive text nodes concatenated\n *\n * @example\n * ```ts\n * coalesceText([{ element: 'text', value: 'a' }, { element: 'text', value: 'b' }])\n * // [{ element: 'text', value: 'ab' }]\n * ```\n */\nexport function coalesceText(nodes: readonly InlineNode[]): readonly InlineNode[] {\n\tconst out: InlineNode[] = []\n\tfor (const node of nodes) {\n\t\tconst last = out[out.length - 1]\n\t\tif (node.element === 'text' && last !== undefined && last.element === 'text') {\n\t\t\tout[out.length - 1] = { element: 'text', value: last.value + node.value }\n\t\t} else {\n\t\t\tout.push(node)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Scan an inline code span at `start` (a `` ` ``-run … a matching `` ` ``-run of the\n * SAME length, the CommonMark rule that lets a span contain backticks). Returns the\n * span's literal text + end index, or `undefined` when no matching closer exists (it\n * then degrades to literal backticks).\n *\n * @param source - The inline source text\n * @param start - The index of the opening backtick\n * @param to - The exclusive end of the scan window\n * @returns The span text + end index, or `undefined`\n *\n * @example\n * ```ts\n * scanCode('`code`', 0, 6) // { value: 'code', end: 6 }\n * ```\n */\nexport function scanCode(\n\tsource: string,\n\tstart: number,\n\tto: number,\n): { readonly value: string; readonly end: number } | undefined {\n\tlet run = 0\n\twhile (start + run < to && source[start + run] === '`') run += 1\n\tconst open = '`'.repeat(run)\n\tlet search = start + run\n\tfor (;;) {\n\t\tconst closeAt = source.indexOf(open, search)\n\t\tif (closeAt === -1 || closeAt + run > to) return undefined\n\t\t// The closer must be EXACTLY `run` backticks (not bordered by another backtick).\n\t\tif (source[closeAt - 1] !== '`' && source[closeAt + run] !== '`') {\n\t\t\tlet value = source.slice(start + run, closeAt)\n\t\t\tif (\n\t\t\t\tvalue.length > 2 &&\n\t\t\t\tvalue.startsWith(' ') &&\n\t\t\t\tvalue.endsWith(' ') &&\n\t\t\t\tvalue.trim().length > 0\n\t\t\t) {\n\t\t\t\tvalue = value.slice(1, -1)\n\t\t\t}\n\t\t\treturn { value, end: closeAt + run }\n\t\t}\n\t\tsearch = closeAt + 1\n\t}\n}\n\n/**\n * Scan a link `[text](href)` at `start` - the text runs to a BALANCED `]`, then `(`\n * must immediately follow and the destination runs to the matching `)` (both respect\n * nested delimiters + escapes). Returns the link node, or `undefined` when the shape\n * does not hold (it then degrades to a literal `[`).\n *\n * @param source - The inline source text\n * @param start - The index of the opening `[`\n * @param to - The exclusive end of the scan window\n * @param depth - The current inline-recursion depth (defaults to 0 at the entry point);\n * at {@link MAX_DEPTH} the link's text children degrade to literal text instead of\n * recursing further\n * @returns The parsed {@link LinkNode} + end index, or `undefined`\n *\n * @example\n * ```ts\n * scanLink('[text](url)', 0, 11)\n * // { node: { element: 'link', href: 'url', children: [...] }, end: 11 }\n * ```\n */\nexport function scanLink(\n\tsource: string,\n\tstart: number,\n\tto: number,\n\tdepth = 0,\n): { readonly node: LinkNode; readonly end: number } | undefined {\n\tlet bracketDepth = 0\n\tlet close = -1\n\tfor (let index = start; index < to; index += 1) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\') {\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '[') bracketDepth += 1\n\t\telse if (character === ']') {\n\t\t\tbracketDepth -= 1\n\t\t\tif (bracketDepth === 0) {\n\t\t\t\tclose = index\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif (close === -1 || source[close + 1] !== '(') return undefined\n\tlet parenDepth = 0\n\tlet parenClose = -1\n\tfor (let index = close + 1; index < to; index += 1) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\') {\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '(') parenDepth += 1\n\t\telse if (character === ')') {\n\t\t\tparenDepth -= 1\n\t\t\tif (parenDepth === 0) {\n\t\t\t\tparenClose = index\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif (parenClose === -1) return undefined\n\tconst href = unescapeText(source.slice(close + 2, parenClose).trim())\n\tconst children = scanInline(source, start + 1, close, depth + 1)\n\treturn { node: { element: 'link', href, children }, end: parenClose + 1 }\n}\n\n/**\n * Scan an emphasis run at `start` (`*` / `_`, doubled for strong) - finds the nearest\n * matching closing run of the same marker + width, requiring non-space immediately\n * inside both delimiters (the CommonMark flanking simplification that blocks `* x *`).\n * Returns the emphasis node, or `undefined` when no valid closer exists (it then\n * degrades to a literal marker).\n *\n * @param source - The inline source text\n * @param start - The index of the opening marker\n * @param to - The exclusive end of the scan window\n * @param depth - The current inline-recursion depth (defaults to 0 at the entry point);\n * at {@link MAX_DEPTH} the emphasis's children degrade to literal text instead of\n * recursing further\n * @returns The parsed {@link EmphasisNode} + end index, or `undefined`\n *\n * @example\n * ```ts\n * scanEmphasis('*em*', 0, 4)\n * // { node: { element: 'emphasis', strong: false, children: [...] }, end: 4 }\n * ```\n */\nexport function scanEmphasis(\n\tsource: string,\n\tstart: number,\n\tto: number,\n\tdepth = 0,\n): { readonly node: EmphasisNode; readonly end: number } | undefined {\n\tconst marker = source[start] ?? ''\n\tlet run = 0\n\twhile (start + run < to && source[start + run] === marker && run < 2) run += 1\n\tconst strong = run === 2\n\tconst openEnd = start + run\n\tif (openEnd >= to || isWhitespace(source[openEnd] ?? '')) return undefined\n\tlet index = openEnd\n\twhile (index < to) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\') {\n\t\t\tindex += 2\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '`') {\n\t\t\tconst span = scanCode(source, index, to)\n\t\t\tindex = span ? span.end : index + 1\n\t\t\tcontinue\n\t\t}\n\t\tif (character === marker) {\n\t\t\tlet closeRun = 0\n\t\t\twhile (index + closeRun < to && source[index + closeRun] === marker) closeRun += 1\n\t\t\tif (closeRun >= run && !isWhitespace(source[index - 1] ?? '')) {\n\t\t\t\treturn {\n\t\t\t\t\tnode: {\n\t\t\t\t\t\telement: 'emphasis',\n\t\t\t\t\t\tstrong,\n\t\t\t\t\t\tchildren: scanInline(source, openEnd, index, depth + 1),\n\t\t\t\t\t},\n\t\t\t\t\tend: index + run,\n\t\t\t\t}\n\t\t\t}\n\t\t\tindex += closeRun\n\t\t\tcontinue\n\t\t}\n\t\tindex += 1\n\t}\n\treturn undefined\n}\n\n/**\n * Scan the window `[from, to)` of `source` into inline nodes - the single recursive\n * engine the inline phase runs on (emphasis / link text recurse through it). Linear:\n * each character is consumed once; a failed construct emits its opening character as\n * text and advances by one, so there is no re-scan (no ReDoS).\n *\n * @param source - The inline source text\n * @param from - The inclusive start of the scan window\n * @param to - The exclusive end of the scan window\n * @param depth - The current inline-recursion depth (defaults to 0 at the entry point);\n * incremented by one on every recursive descent through {@link scanLink} /\n * {@link scanEmphasis}. At {@link MAX_DEPTH} the window is never scanned for markup -\n * it emits as a single literal text node - so pathological nesting (`[[[[…`,\n * `****…`) cannot exhaust the call stack.\n * @returns The parsed inline nodes (NOT yet coalesced)\n *\n * @example\n * ```ts\n * scanInline('hi *there*', 0, 10) // [{ element: 'text', value: 'hi ' }, { element: 'emphasis', ... }]\n * ```\n */\nexport function scanInline(\n\tsource: string,\n\tfrom: number,\n\tto: number,\n\tdepth = 0,\n): readonly InlineNode[] {\n\tif (depth >= MAX_DEPTH)\n\t\treturn from < to ? [{ element: 'text', value: source.slice(from, to) }] : []\n\tconst nodes: InlineNode[] = []\n\tlet index = from\n\tlet pending = ''\n\tconst flush = (): void => {\n\t\tif (pending.length > 0) {\n\t\t\tnodes.push({ element: 'text', value: pending })\n\t\t\tpending = ''\n\t\t}\n\t}\n\twhile (index < to) {\n\t\tconst character = source[index] ?? ''\n\t\tif (character === '\\\\' && index + 1 < to && isEscapable(source[index + 1] ?? '')) {\n\t\t\tpending += source[index + 1] ?? ''\n\t\t\tindex += 2\n\t\t\tcontinue\n\t\t}\n\t\tif (character === '`') {\n\t\t\tconst span = scanCode(source, index, to)\n\t\t\tif (span) {\n\t\t\t\tflush()\n\t\t\t\tnodes.push({ element: 'codeSpan', value: span.value })\n\t\t\t\tindex = span.end\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif (character === '[') {\n\t\t\tconst link = scanLink(source, index, to, depth)\n\t\t\tif (link) {\n\t\t\t\tflush()\n\t\t\t\tnodes.push(link.node)\n\t\t\t\tindex = link.end\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif (character === '*' || character === '_') {\n\t\t\tconst emphasis = scanEmphasis(source, index, to, depth)\n\t\t\tif (emphasis) {\n\t\t\t\tflush()\n\t\t\t\tnodes.push(emphasis.node)\n\t\t\t\tindex = emphasis.end\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tpending += character\n\t\tindex += 1\n\t}\n\tflush()\n\treturn nodes\n}\n\n// Rendering (AST HTML string)\n\n/**\n * HTML-escape text content - `&` / `<` / `>` / `\"` / `'` to their entities - so text\n * from a markdown document can never inject markup. The renderer applies this to every\n * text run, code body, and (escaped further) attribute value.\n *\n * @param text - The raw text\n * @returns The HTML-escaped text\n *\n * @example\n * ```ts\n * escapeHtml('<a>&\"\\'') // '&lt;a&gt;&amp;&quot;&#39;'\n * ```\n */\nexport function escapeHtml(text: string): string {\n\treturn text\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;')\n\t\t.replace(/'/g, '&#39;')\n}\n\n/**\n * Sanitize + HTML-attribute-escape a link `href` - a destination whose scheme is not\n * in {@link SAFE_URL_SCHEMES} (notably `javascript:` / `data:` / `vbscript:`), or that\n * is protocol-relative (`//host/path`, or a backslash variant a browser normalizes to\n * the same effect - `\\\\host`, `/\\host`, `\\/host` - inherits whatever scheme the\n * embedding page is served over, including an unsafe one), is dropped to an empty\n * string; a relative / anchor / scheme-less (and non-protocol-relative) destination\n * (including a SINGLE leading `/` or `\\`) is kept;\n * the surviving value is then HTML-escaped. Defence-in-depth against an XSS `href`,\n * even though the input is trusted.\n *\n * @param href - The raw link destination\n * @returns A safe, escaped `href` (empty when the scheme is unsafe or protocol-relative)\n *\n * @example\n * ```ts\n * sanitizeUrl('javascript:alert(1)') // ''\n * sanitizeUrl('/path') // '/path'\n * ```\n */\nexport function sanitizeUrl(href: string): string {\n\t// Strip every whitespace + C0/C1 control codepoint (≤ U+0020 or U+007F–U+009F)\n\t// anywhere - a `java\\tscript:` / embedded-newline scheme-spoofing evasion - by\n\t// codepoint, not a control-character regex class (AGENTS §1: no disables).\n\tlet cleaned = ''\n\tfor (const character of href) {\n\t\tconst code = character.codePointAt(0) ?? 0\n\t\tif (code > 0x20 && !(code >= 0x7f && code <= 0x9f)) cleaned += character\n\t}\n\tif (/^[/\\\\]{2}/.exec(cleaned)) return ''\n\tconst scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleaned)\n\tif (scheme && scheme[1] !== undefined && !SAFE_URL_SCHEMES.has(scheme[1].toLowerCase())) return ''\n\treturn escapeHtml(cleaned)\n}\n\n/**\n * Render a {@link MarkdownNode} (typically a {@link MarkdownDocument}) to a safe HTML\n * string - the recursive AST → HTML engine (headings, paragraphs, lists, GFM tables,\n * fenced code, blockquotes, links, emphasis, inline code), escaping every text run and\n * sanitizing every link `href`.\n *\n * @remarks\n * Total: never throws. At {@link MAX_DEPTH} a value-bearing node (`text` / `codeSpan`)\n * degrades to its escaped `value`; any other node degrades to `''` instead of\n * recursing further, so pathologically deep input cannot exhaust the call stack. The\n * recursive engine and its per-shape sub-steps (inline concatenation, table cell,\n * tight list-item) are nested inner functions - the only exported surface is\n * `renderHTML` itself.\n *\n * @param node - The AST node to render (a full document, or any sub-node)\n * @returns The rendered, XSS-safe HTML string\n *\n * @example\n * ```ts\n * renderHTML({ element: 'document', children: [\n * { element: 'heading', level: 1, children: [{ element: 'text', value: 'Hi' }] },\n * ] })\n * // '<h1>Hi</h1>'\n * ```\n */\nexport function renderHTML(node: MarkdownNode): string {\n\tfunction render(current: MarkdownNode, depth: number): string {\n\t\tif (depth >= MAX_DEPTH)\n\t\t\treturn 'value' in current && typeof current.value === 'string'\n\t\t\t\t? escapeHtml(current.value)\n\t\t\t\t: ''\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\t\treturn current.children.map((child) => render(child, depth + 1)).join('\\n')\n\t\t\tcase 'heading':\n\t\t\t\treturn `<h${current.level}>${renderInline(current.children, depth)}</h${current.level}>`\n\t\t\tcase 'paragraph':\n\t\t\t\treturn `<p>${renderInline(current.children, depth)}</p>`\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn '<hr>'\n\t\t\tcase 'blockquote':\n\t\t\t\treturn `<blockquote>\\n${current.children.map((child) => render(child, depth + 1)).join('\\n')}\\n</blockquote>`\n\t\t\tcase 'codeBlock': {\n\t\t\t\tconst open =\n\t\t\t\t\tcurrent.lang === undefined\n\t\t\t\t\t\t? '<code>'\n\t\t\t\t\t\t: `<code class=\"language-${escapeHtml(current.lang)}\">`\n\t\t\t\treturn `<pre>${open}${escapeHtml(current.code)}</code></pre>`\n\t\t\t}\n\t\t\tcase 'list': {\n\t\t\t\tconst items = current.items.map((item) => render(item, depth + 1)).join('\\n')\n\t\t\t\tif (!current.ordered) return `<ul>\\n${items}\\n</ul>`\n\t\t\t\tconst start = current.start !== 1 ? ` start=\"${current.start}\"` : ''\n\t\t\t\treturn `<ol${start}>\\n${items}\\n</ol>`\n\t\t\t}\n\t\t\tcase 'listItem':\n\t\t\t\treturn `<li>${renderItem(current.children, depth)}</li>`\n\t\t\tcase 'table': {\n\t\t\t\tconst head = `<tr>${current.header.map((cell, column) => renderCell('th', cell, current.align[column], depth)).join('')}</tr>`\n\t\t\t\tconst body = current.rows\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t`<tr>${row.map((cell, column) => renderCell('td', cell, current.align[column], depth)).join('')}</tr>`,\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n')\n\t\t\t\tconst bodyHtml = isNonEmptyArray(current.rows) ? `\\n<tbody>\\n${body}\\n</tbody>` : ''\n\t\t\t\treturn `<table>\\n<thead>\\n${head}\\n</thead>${bodyHtml}\\n</table>`\n\t\t\t}\n\t\t\tcase 'text':\n\t\t\t\treturn escapeHtml(current.value)\n\t\t\tcase 'emphasis':\n\t\t\t\treturn current.strong\n\t\t\t\t\t? `<strong>${renderInline(current.children, depth + 1)}</strong>`\n\t\t\t\t\t: `<em>${renderInline(current.children, depth + 1)}</em>`\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn `<code>${escapeHtml(current.value)}</code>`\n\t\t\tcase 'link':\n\t\t\t\treturn `<a href=\"${sanitizeUrl(current.href)}\">${renderInline(current.children, depth + 1)}</a>`\n\t\t\tdefault:\n\t\t\t\treturn ''\n\t\t}\n\t}\n\n\tfunction renderInline(nodes: readonly InlineNode[], depth: number): string {\n\t\treturn nodes.map((child) => render(child, depth + 1)).join('')\n\t}\n\n\tfunction renderCell(\n\t\ttag: 'th' | 'td',\n\t\tcell: readonly InlineNode[],\n\t\talign: TableAlign | undefined,\n\t\tdepth: number,\n\t): string {\n\t\tconst style =\n\t\t\talign === 'left' || align === 'right' || align === 'center'\n\t\t\t\t? ` style=\"text-align:${align}\"`\n\t\t\t\t: ''\n\t\treturn `<${tag}${style}>${renderInline(cell, depth + 1)}</${tag}>`\n\t}\n\n\tfunction renderItem(children: readonly BlockNode[], depth: number): string {\n\t\tif (children.length === 1) {\n\t\t\tconst only = children[0]\n\t\t\tif (only !== undefined && only.element === 'paragraph')\n\t\t\t\treturn renderInline(only.children, depth)\n\t\t}\n\t\treturn children.map((child) => render(child, depth + 1)).join('\\n')\n\t}\n\n\treturn render(node, 0)\n}\n\n/**\n * Render a {@link MarkdownNode} to its CANONICAL markdown source - the inverse\n * projection of `renderHTML`, and the serializer a `parse(renderMarkdown(doc))`\n * round-trip is built on. Canonical forms: `*em*` / `**strong**` (underscore emphasis\n * normalizes to asterisks), `- ` bullets, `N. ` sequential ordinals (from the list's\n * `start`), `---` thematic breaks, fenced code blocks (backtick run widened past any\n * 3+ backtick run inside the body), ATX headings, `> `-prefixed blockquote lines, GFM\n * tables (1-space-padded cells, `\\|`-escaped pipes, an alignment delimiter row), and\n * `[text](href)` links. A `text` node's literal content is backslash-escaped wherever\n * it would otherwise re-parse as markup (AGENTS §14 parse↔render soundness).\n *\n * @remarks\n * Total: never throws. At {@link MAX_DEPTH} a value-bearing node degrades to its\n * escaped `value`; any other node degrades to `''`. Blocks are joined by exactly one\n * blank line; a document with zero blocks renders `''`.\n *\n * @param node - The AST node to render (a full document, or any sub-node)\n * @returns The canonical markdown source\n *\n * @example\n * ```ts\n * renderMarkdown({ element: 'document', children: [\n * { element: 'heading', level: 2, children: [{ element: 'text', value: 'Hi' }] },\n * ] })\n * // '## Hi'\n * ```\n */\nexport function renderMarkdown(node: MarkdownNode): string {\n\tfunction escapeText(value: string): string {\n\t\tlet out = ''\n\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\tconst character = value[index] ?? ''\n\t\t\tconst atLineStart = index === 0 || value[index - 1] === '\\n'\n\t\t\tif (\n\t\t\t\tcharacter === '\\\\' ||\n\t\t\t\tcharacter === '*' ||\n\t\t\t\tcharacter === '_' ||\n\t\t\t\tcharacter === '`' ||\n\t\t\t\tcharacter === '[' ||\n\t\t\t\tcharacter === ']'\n\t\t\t) {\n\t\t\t\tout += `\\\\${character}`\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (atLineStart) {\n\t\t\t\tif (character === '#' || character === '>') {\n\t\t\t\t\tout += `\\\\${character}`\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif ((character === '-' || character === '+') && (value[index + 1] ?? ' ') === ' ') {\n\t\t\t\t\tout += `\\\\${character}`\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (/[0-9]/.test(character)) {\n\t\t\t\t\tlet end = index\n\t\t\t\t\twhile (end < value.length && /[0-9]/.test(value[end] ?? '')) end += 1\n\t\t\t\t\tconst marker = value[end]\n\t\t\t\t\tif ((marker === '.' || marker === ')') && value[end + 1] === ' ') {\n\t\t\t\t\t\tout += `${value.slice(index, end)}\\\\${marker}`\n\t\t\t\t\t\tindex = end\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tout += character\n\t\t}\n\t\treturn out\n\t}\n\n\tfunction fenceFor(body: string, minimum: number): string {\n\t\tlet longest = 0\n\t\tlet run = 0\n\t\tfor (const character of body) {\n\t\t\tif (character === '`') {\n\t\t\t\trun += 1\n\t\t\t\tlongest = Math.max(longest, run)\n\t\t\t} else {\n\t\t\t\trun = 0\n\t\t\t}\n\t\t}\n\t\treturn '`'.repeat(Math.max(minimum, longest + 1))\n\t}\n\n\tfunction renderInline(nodes: readonly InlineNode[], depth: number): string {\n\t\treturn nodes.map((child) => render(child, depth + 1)).join('')\n\t}\n\n\tfunction renderBlocks(blocks: readonly BlockNode[], depth: number): string {\n\t\treturn blocks.map((block) => render(block, depth + 1)).join('\\n\\n')\n\t}\n\n\tfunction renderItem(item: ListItemNode, marker: string, depth: number): string {\n\t\tconst body = renderBlocks(item.children, depth + 1)\n\t\tconst pad = ' '.repeat(marker.length)\n\t\treturn body\n\t\t\t.split('\\n')\n\t\t\t.map((line, index) => (index === 0 ? marker + line : line === '' ? '' : pad + line))\n\t\t\t.join('\\n')\n\t}\n\n\tfunction renderCell(cell: readonly InlineNode[], depth: number): string {\n\t\treturn renderInline(cell, depth + 1).replace(/\\|/g, '\\\\|')\n\t}\n\n\tfunction renderTable(current: TableNode, depth: number): string {\n\t\tconst columns = current.header.length\n\t\tconst headerRow = `| ${current.header.map((cell) => renderCell(cell, depth)).join(' | ')} |`\n\t\tconst delimiterRow = `| ${current.align\n\t\t\t.map((align) => {\n\t\t\t\tif (align === 'left') return ':--'\n\t\t\t\tif (align === 'right') return '--:'\n\t\t\t\tif (align === 'center') return ':-:'\n\t\t\t\treturn '---'\n\t\t\t})\n\t\t\t.join(' | ')} |`\n\t\tconst bodyRows = current.rows.map((row) => {\n\t\t\tconst cells: string[] = []\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tconst cell = row[column]\n\t\t\t\tcells.push(cell === undefined ? '' : renderCell(cell, depth))\n\t\t\t}\n\t\t\treturn `| ${cells.join(' | ')} |`\n\t\t})\n\t\treturn [headerRow, delimiterRow, ...bodyRows].join('\\n')\n\t}\n\n\tfunction render(current: MarkdownNode, depth: number): string {\n\t\tif (depth >= MAX_DEPTH)\n\t\t\treturn 'value' in current && typeof current.value === 'string'\n\t\t\t\t? escapeText(current.value)\n\t\t\t\t: ''\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\t\treturn renderBlocks(current.children, depth)\n\t\t\tcase 'heading': {\n\t\t\t\tconst text = renderInline(current.children, depth)\n\t\t\t\t// A trailing `#` run reads back as an ATX closing sequence on reparse -\n\t\t\t\t// escape the FIRST `#` of that run so it can't be stripped. Only fire when\n\t\t\t\t// the char preceding the run isn't a backslash - escapeText already escapes\n\t\t\t\t// a line-start `#`, and re-escaping it here would double-escape (`## #` -> text\n\t\t\t\t// \"#\" -> escapeText \"\\#\" -> would become \"\\\\#\" and break round-trip).\n\t\t\t\tconst escaped = text.replace(/(^|[^\\\\])(#+)$/, (_match, pre: string, hashes: string) => {\n\t\t\t\t\tconst first = hashes[0] ?? ''\n\t\t\t\t\treturn `${pre}\\\\${first}${hashes.slice(1)}`\n\t\t\t\t})\n\t\t\t\treturn `${'#'.repeat(current.level)} ${escaped}`\n\t\t\t}\n\t\t\tcase 'paragraph':\n\t\t\t\treturn renderInline(current.children, depth)\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn '---'\n\t\t\tcase 'blockquote': {\n\t\t\t\tconst inner = renderBlocks(current.children, depth)\n\t\t\t\treturn inner\n\t\t\t\t\t.split('\\n')\n\t\t\t\t\t.map((line) => (line === '' ? '>' : `> ${line}`))\n\t\t\t\t\t.join('\\n')\n\t\t\t}\n\t\t\tcase 'codeBlock': {\n\t\t\t\tconst fence = fenceFor(current.code, 3)\n\t\t\t\tconst lang = current.lang === undefined ? '' : current.lang\n\t\t\t\treturn `${fence}${lang}\\n${current.code}\\n${fence}`\n\t\t\t}\n\t\t\tcase 'list': {\n\t\t\t\tlet ordinal = current.start\n\t\t\t\tconst items = current.items.map((item) => {\n\t\t\t\t\tconst marker = current.ordered ? `${ordinal++}. ` : '- '\n\t\t\t\t\treturn renderItem(item, marker, depth)\n\t\t\t\t})\n\t\t\t\treturn items.join('\\n')\n\t\t\t}\n\t\t\tcase 'listItem':\n\t\t\t\treturn renderBlocks(current.children, depth)\n\t\t\tcase 'table':\n\t\t\t\treturn renderTable(current, depth)\n\t\t\tcase 'text':\n\t\t\t\treturn escapeText(current.value)\n\t\t\tcase 'emphasis': {\n\t\t\t\tconst marker = current.strong ? '**' : '*'\n\t\t\t\treturn `${marker}${renderInline(current.children, depth)}${marker}`\n\t\t\t}\n\t\t\tcase 'codeSpan': {\n\t\t\t\tconst fence = fenceFor(current.value, 1)\n\t\t\t\tconst pad = current.value.startsWith('`') || current.value.endsWith('`') ? ' ' : ''\n\t\t\t\treturn `${fence}${pad}${current.value}${pad}${fence}`\n\t\t\t}\n\t\t\tcase 'link': {\n\t\t\t\t// Mirror scanLink's unescape - a href containing `\\`, `(`, or `)` must\n\t\t\t\t// round-trip through the same balanced-paren + backslash-escape scan.\n\t\t\t\tconst href = current.href.replace(/[\\\\()]/g, (character) => `\\\\${character}`)\n\t\t\t\treturn `[${renderInline(current.children, depth)}](${href})`\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn ''\n\t\t}\n\t}\n\n\treturn render(node, 0)\n}\n\n/**\n * Depth-first, pre-order, root-inclusive traversal of a {@link MarkdownNode} - yields\n * the node itself, then recurses into its children (block children, list items, table\n * header/row cells' inline nodes) in walk order.\n *\n * @remarks\n * Total: never throws. Descent stops at {@link MAX_DEPTH} (the node at the cap is\n * still yielded; its children are not) so pathologically deep input cannot exhaust\n * the call stack.\n *\n * @param node - The AST node to walk (a full document, or any sub-node)\n * @returns A generator yielding every visited node, pre-order\n *\n * @example\n * ```ts\n * const doc = { element: 'document', children: [{ element: 'thematicBreak' }] } as const\n * [...walkNodes(doc)].map((node) => node.element) // ['document', 'thematicBreak']\n * ```\n */\nexport function* walkNodes(node: MarkdownNode): Generator<MarkdownNode> {\n\tfunction* walk(current: MarkdownNode, depth: number): Generator<MarkdownNode> {\n\t\tyield current\n\t\tif (depth >= MAX_DEPTH) return\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\tcase 'heading':\n\t\t\tcase 'paragraph':\n\t\t\tcase 'blockquote':\n\t\t\tcase 'listItem':\n\t\t\tcase 'emphasis':\n\t\t\tcase 'link':\n\t\t\t\tfor (const child of current.children) yield* walk(child, depth + 1)\n\t\t\t\treturn\n\t\t\tcase 'list':\n\t\t\t\tfor (const item of current.items) yield* walk(item, depth + 1)\n\t\t\t\treturn\n\t\t\tcase 'table':\n\t\t\t\tfor (const cell of current.header) for (const inline of cell) yield* walk(inline, depth + 1)\n\t\t\t\tfor (const row of current.rows)\n\t\t\t\t\tfor (const cell of row) for (const inline of cell) yield* walk(inline, depth + 1)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\treturn\n\t\t}\n\t}\n\tyield* walk(node, 0)\n}\n\n/**\n * Fold a {@link MarkdownNode} into a `T` via a total catamorphism - children are\n * folded first (post-order), then the node's own {@link MarkdownHandler} is invoked\n * with the already-folded children.\n *\n * @remarks\n * **Table contract.** A {@link TableNode} has no single `children` array - its cells\n * live in `header` (one inline-node list per column) and `rows` (a list of such\n * rows). The `table` handler receives ONE folded `T` per inline node, flattened in\n * walk order across ALL cells - every header cell's inline nodes (column order), then\n * every body row's cells' inline nodes (row order, then column order) - and reads\n * `node.header[c].length` / `node.rows[r][c].length` off the table node itself to\n * recover cell boundaries within the flat list.\n *\n * Total: never throws. At `depth >= {@link MAX_DEPTH}` the node's handler is invoked\n * with an empty children list instead of recursing further.\n *\n * @param node - The AST node to fold\n * @param handlers - The total {@link MarkdownHandlers} table, one handler per element\n * @param depth - The starting recursion depth (pass `0` at the entry point)\n * @returns The folded `T`\n *\n * @example\n * ```ts\n * const countHandlers: MarkdownHandlers<number> = {\n * document: (_, children) => children.reduce((a, b) => a + b, 1),\n * // ...one handler per element, each summing its folded children\n * }\n * foldNode(document, countHandlers, 0) // total node count\n * ```\n */\nexport function foldNode<T>(node: MarkdownNode, handlers: MarkdownHandlers<T>, depth: number): T {\n\tfunction dispatch(current: MarkdownNode, children: readonly T[]): T {\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\t\treturn handlers.document(current, children)\n\t\t\tcase 'heading':\n\t\t\t\treturn handlers.heading(current, children)\n\t\t\tcase 'paragraph':\n\t\t\t\treturn handlers.paragraph(current, children)\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn handlers.thematicBreak(current, children)\n\t\t\tcase 'blockquote':\n\t\t\t\treturn handlers.blockquote(current, children)\n\t\t\tcase 'codeBlock':\n\t\t\t\treturn handlers.codeBlock(current, children)\n\t\t\tcase 'list':\n\t\t\t\treturn handlers.list(current, children)\n\t\t\tcase 'listItem':\n\t\t\t\treturn handlers.listItem(current, children)\n\t\t\tcase 'table':\n\t\t\t\treturn handlers.table(current, children)\n\t\t\tcase 'text':\n\t\t\t\treturn handlers.text(current, children)\n\t\t\tcase 'emphasis':\n\t\t\t\treturn handlers.emphasis(current, children)\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn handlers.codeSpan(current, children)\n\t\t\tcase 'link':\n\t\t\t\treturn handlers.link(current, children)\n\t\t}\n\t}\n\n\tfunction childNodes(current: MarkdownNode): readonly MarkdownNode[] {\n\t\tswitch (current.element) {\n\t\t\tcase 'document':\n\t\t\tcase 'heading':\n\t\t\tcase 'paragraph':\n\t\t\tcase 'blockquote':\n\t\t\tcase 'listItem':\n\t\t\tcase 'emphasis':\n\t\t\tcase 'link':\n\t\t\t\treturn current.children\n\t\t\tcase 'list':\n\t\t\t\treturn current.items\n\t\t\tcase 'table': {\n\t\t\t\tconst header = current.header.flatMap((cell) => cell)\n\t\t\t\tconst rows = current.rows.flatMap((row) => row.flatMap((cell) => cell))\n\t\t\t\treturn [...header, ...rows]\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn []\n\t\t}\n\t}\n\n\tfunction fold(current: MarkdownNode, level: number): T {\n\t\tif (level >= MAX_DEPTH) return dispatch(current, [])\n\t\tconst children = childNodes(current).map((child) => fold(child, level + 1))\n\t\treturn dispatch(current, children)\n\t}\n\n\treturn fold(node, depth)\n}\n\n/**\n * Rewrite a {@link MarkdownDocument} bottom-up (copy-on-write) - each node's children\n * are rewritten first (post-order), then `rewrite` is applied to the node itself; the\n * document ROOT is never passed to `rewrite` (the `element: 'document'` invariant\n * always holds). A table's inline cells and a list's items ARE rewritten.\n *\n * @remarks\n * Never mutates `document` - every level is rebuilt into a fresh object/array, even\n * when `rewrite` returns its input unchanged. When `rewrite` returns a node whose\n * `element` does not fit the slot it was called for (a block slot handed a\n * non-{@link BlockNode}, an inline slot handed a non-{@link InlineNode}, a list-item\n * slot handed a non-`listItem`), the ill-fitting result is discarded and the\n * freshly-rebuilt (unrewritten-at-this-level) node is kept instead - `rewriteDocument`\n * stays total and never produces a structurally invalid document.\n *\n * Descent is capped at {@link MAX_DEPTH}, the same cap {@link walkNodes} and\n * {@link foldNode} observe: at `depth >= MAX_DEPTH` the subtree is passed through\n * UNCHANGED (by reference, not rebuilt, and `rewrite` is not invoked on it) instead of\n * recursing further, so a pathologically deep adopted document cannot exhaust the\n * call stack. {@link MarkdownInterface.map} inherits this cap since it delegates here.\n *\n * @param document - The document AST to rewrite\n * @param rewrite - The bottom-up {@link MarkdownRewriteHandler}\n * @returns A new, rewritten {@link MarkdownDocument}\n *\n * @example\n * ```ts\n * rewriteDocument(document, (node) =>\n * node.element === 'text' ? { element: 'text', value: node.value.toUpperCase() } : node,\n * )\n * ```\n */\nexport function rewriteDocument(\n\tdocument: MarkdownDocument,\n\trewrite: MarkdownRewriteHandler,\n): MarkdownDocument {\n\tfunction rewriteInline(node: InlineNode, depth: number): InlineNode {\n\t\tif (depth >= MAX_DEPTH) return node\n\t\tconst rebuilt = rebuildInline(node, depth)\n\t\tconst result = rewrite(rebuilt)\n\t\treturn isInlineNode(result) ? result : rebuilt\n\t}\n\n\tfunction rewriteBlock(node: BlockNode, depth: number): BlockNode {\n\t\tif (depth >= MAX_DEPTH) return node\n\t\tconst rebuilt = rebuildBlock(node, depth)\n\t\tconst result = rewrite(rebuilt)\n\t\treturn isBlockNode(result) ? result : rebuilt\n\t}\n\n\tfunction rewriteItem(item: ListItemNode, depth: number): ListItemNode {\n\t\tif (depth >= MAX_DEPTH) return item\n\t\tconst rebuilt: ListItemNode = {\n\t\t\telement: 'listItem',\n\t\t\tchildren: item.children.map((child) => rewriteBlock(child, depth + 1)),\n\t\t}\n\t\tconst result = rewrite(rebuilt)\n\t\treturn result.element === 'listItem' ? result : rebuilt\n\t}\n\n\tfunction rebuildInline(node: InlineNode, depth: number): InlineNode {\n\t\tswitch (node.element) {\n\t\t\tcase 'emphasis':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'link':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'text':\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn node\n\t\t}\n\t}\n\n\tfunction rebuildBlock(node: BlockNode, depth: number): BlockNode {\n\t\tswitch (node.element) {\n\t\t\tcase 'heading':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'paragraph':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteInline(child, depth + 1)) }\n\t\t\tcase 'blockquote':\n\t\t\t\treturn { ...node, children: node.children.map((child) => rewriteBlock(child, depth + 1)) }\n\t\t\tcase 'list':\n\t\t\t\treturn { ...node, items: node.items.map((item) => rewriteItem(item, depth + 1)) }\n\t\t\tcase 'table':\n\t\t\t\treturn {\n\t\t\t\t\t...node,\n\t\t\t\t\theader: node.header.map((cell) => cell.map((inline) => rewriteInline(inline, depth + 1))),\n\t\t\t\t\trows: node.rows.map((row) =>\n\t\t\t\t\t\trow.map((cell) => cell.map((inline) => rewriteInline(inline, depth + 1))),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\tcase 'codeBlock':\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn node\n\t\t}\n\t}\n\n\treturn { element: 'document', children: document.children.map((child) => rewriteBlock(child, 0)) }\n}\n\n/**\n * Concatenate the `value` / `code` content of every descendant text / code-span /\n * code-block node under `node`, in walk order - the plain-text projection of an AST\n * (search indexing, word counts, a text-only preview).\n *\n * @remarks\n * Total: never throws. Descent stops at {@link MAX_DEPTH} (contributes `''` past the\n * cap instead of recursing further).\n *\n * @param node - The AST node to flatten (a full document, or any sub-node)\n * @returns The concatenated text content\n *\n * @example\n * ```ts\n * flattenText({ element: 'paragraph', children: [\n * { element: 'text', value: 'a ' },\n * { element: 'codeSpan', value: 'b' },\n * ] })\n * // 'a b'\n * ```\n */\nexport function flattenText(node: MarkdownNode): string {\n\tfunction flatten(current: MarkdownNode, depth: number): string {\n\t\tif (depth >= MAX_DEPTH) return ''\n\t\tswitch (current.element) {\n\t\t\tcase 'text':\n\t\t\t\treturn current.value\n\t\t\tcase 'codeSpan':\n\t\t\t\treturn current.value\n\t\t\tcase 'codeBlock':\n\t\t\t\treturn current.code\n\t\t\tcase 'document':\n\t\t\tcase 'heading':\n\t\t\tcase 'paragraph':\n\t\t\tcase 'blockquote':\n\t\t\tcase 'listItem':\n\t\t\tcase 'emphasis':\n\t\t\tcase 'link':\n\t\t\t\treturn current.children.map((child) => flatten(child, depth + 1)).join('')\n\t\t\tcase 'list':\n\t\t\t\treturn current.items.map((item) => flatten(item, depth + 1)).join('')\n\t\t\tcase 'table': {\n\t\t\t\tconst header = current.header\n\t\t\t\t\t.map((cell) => cell.map((inline) => flatten(inline, depth + 1)).join(''))\n\t\t\t\t\t.join('')\n\t\t\t\tconst rows = current.rows\n\t\t\t\t\t.map((row) =>\n\t\t\t\t\t\trow.map((cell) => cell.map((inline) => flatten(inline, depth + 1)).join('')).join(''),\n\t\t\t\t\t)\n\t\t\t\t\t.join('')\n\t\t\t\treturn header + rows\n\t\t\t}\n\t\t\tcase 'thematicBreak':\n\t\t\t\treturn ''\n\t\t\tdefault:\n\t\t\t\treturn ''\n\t\t}\n\t}\n\treturn flatten(node, 0)\n}\n","import type {\n\tBlockNode,\n\tInlineNode,\n\tListItemNode,\n\tListNode,\n\tMarkdownDocument,\n\tTableAlign,\n\tTableNode,\n} from './types.js'\nimport {\n\tcoalesceText,\n\tleadingIndent,\n\textractFence,\n\textractHeading,\n\textractListItem,\n\tscanInline,\n\tsplitLines,\n\tsplitTableRow,\n\tstartsBlock,\n\tstripQuote,\n\ttableAlignments,\n} from './helpers.js'\nimport { isBlankLine, isFenceClose, isQuote, isTableStart, isThematicBreak } from './validators.js'\nimport { MAX_DEPTH } from './constants.js'\nimport { isNonEmptyArray } from '@orkestrel/contract'\n\n/**\n * Parses a run of markdown lines into a block AST, recursing into nested\n * blockquotes, list items, and depth-capped degrade paragraphs.\n *\n * @param lines - The markdown lines to parse.\n * @param depth - The current recursion depth (blockquotes/lists increment it).\n * @returns The parsed block nodes.\n *\n * @example\n * ```ts\n * parseBlocks(['# Hi'], 0) // [{ element: 'heading', level: 1, children: [...] }]\n * ```\n */\nexport function parseBlocks(lines: readonly string[], depth: number): readonly BlockNode[] {\n\tif (depth >= MAX_DEPTH) {\n\t\treturn lines.length > 0\n\t\t\t? [{ element: 'paragraph', children: [{ element: 'text', value: lines.join('\\n') }] }]\n\t\t\t: []\n\t}\n\tconst blocks: BlockNode[] = []\n\tlet index = 0\n\twhile (index < lines.length) {\n\t\tconst line = lines[index] ?? ''\n\t\tif (isBlankLine(line)) {\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tconst fence = extractFence(line)\n\t\tif (fence) {\n\t\t\tconst body: string[] = []\n\t\t\tindex += 1\n\t\t\twhile (index < lines.length && !isFenceClose(lines[index] ?? '', fence.marker)) {\n\t\t\t\tbody.push(lines[index] ?? '')\n\t\t\t\tindex += 1\n\t\t\t}\n\t\t\tindex += 1 // step past the closing fence (a no-op past EOF)\n\t\t\tblocks.push({\n\t\t\t\telement: 'codeBlock',\n\t\t\t\t...(fence.lang === undefined ? {} : { lang: fence.lang }),\n\t\t\t\tcode: body.join('\\n'),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif (isThematicBreak(line)) {\n\t\t\tblocks.push({ element: 'thematicBreak' })\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tconst heading = extractHeading(line)\n\t\tif (heading) {\n\t\t\tblocks.push({\n\t\t\t\telement: 'heading',\n\t\t\t\tlevel: heading.level,\n\t\t\t\tchildren: parseInline(heading.text),\n\t\t\t})\n\t\t\tindex += 1\n\t\t\tcontinue\n\t\t}\n\t\tif (isQuote(line)) {\n\t\t\tconst quoted: string[] = []\n\t\t\twhile (index < lines.length && isQuote(lines[index] ?? '')) {\n\t\t\t\tquoted.push(stripQuote(lines[index] ?? ''))\n\t\t\t\tindex += 1\n\t\t\t}\n\t\t\tblocks.push({ element: 'blockquote', children: parseBlocks(quoted, depth + 1) })\n\t\t\tcontinue\n\t\t}\n\t\tif (isTableStart(line, lines[index + 1])) {\n\t\t\tconst table = collectTable(lines, index)\n\t\t\tblocks.push(table.node)\n\t\t\tindex = table.next\n\t\t\tcontinue\n\t\t}\n\t\tif (extractListItem(line)) {\n\t\t\tconst list = collectList(lines, index, depth)\n\t\t\tblocks.push(list.node)\n\t\t\tindex = list.next\n\t\t\tcontinue\n\t\t}\n\t\tconst paragraph: string[] = []\n\t\twhile (\n\t\t\tindex < lines.length &&\n\t\t\t!isBlankLine(lines[index] ?? '') &&\n\t\t\t!(isNonEmptyArray(paragraph) && startsBlock(lines, index))\n\t\t) {\n\t\t\tparagraph.push((lines[index] ?? '').trim())\n\t\t\tindex += 1\n\t\t}\n\t\tblocks.push({ element: 'paragraph', children: parseInline(paragraph.join('\\n')) })\n\t}\n\treturn blocks\n}\n\n/**\n * Collects a GFM table starting at a header row, parsing the header, the\n * alignment row, and every contiguous body row that follows.\n *\n * @param lines - The markdown lines to scan.\n * @param start - The index of the header row.\n * @returns The parsed table node and the index of the first line after it.\n *\n * @example\n * ```ts\n * collectTable(['| a |', '| - |'], 0) // { node: { element: 'table', ... }, next: 2 }\n * ```\n */\nexport function collectTable(\n\tlines: readonly string[],\n\tstart: number,\n): { readonly node: TableNode; readonly next: number } {\n\tconst headerCells = splitTableRow(lines[start] ?? '')\n\tconst columns = headerCells.length\n\tconst header = headerCells.map((cell) => parseInline(cell.trim()))\n\tconst align = tableAlignments(lines[start + 1] ?? '')\n\tconst padded: TableAlign[] = []\n\tfor (let column = 0; column < columns; column += 1) padded.push(align[column] ?? 'none')\n\tconst rows: (readonly InlineNode[])[][] = []\n\tlet index = start + 2\n\twhile (\n\t\tindex < lines.length &&\n\t\t!isBlankLine(lines[index] ?? '') &&\n\t\t(lines[index] ?? '').includes('|')\n\t) {\n\t\tconst cells = splitTableRow(lines[index] ?? '')\n\t\tconst row: (readonly InlineNode[])[] = []\n\t\tfor (let column = 0; column < columns; column += 1)\n\t\t\trow.push(parseInline((cells[column] ?? '').trim()))\n\t\trows.push(row)\n\t\tindex += 1\n\t}\n\treturn { node: { element: 'table', header, rows, align: padded }, next: index }\n}\n\n/**\n * Collects a list starting at the first item, gathering sibling items at the\n * same indent/ordering and recursing into each item's own block content.\n *\n * @param lines - The markdown lines to scan.\n * @param start - The index of the first list item.\n * @param depth - The current recursion depth (each item recurses at `depth + 1`).\n * @returns The parsed list node and the index of the first line after it.\n *\n * @example\n * ```ts\n * collectList(['- item'], 0, 0) // { node: { element: 'list', ... }, next: 1 }\n * ```\n */\nexport function collectList(\n\tlines: readonly string[],\n\tstart: number,\n\tdepth: number,\n): { readonly node: ListNode; readonly next: number } {\n\tconst first = extractListItem(lines[start] ?? '')\n\tconst ordered = first?.ordered ?? false\n\tconst startOrdinal = first?.start ?? 1\n\tconst topIndent = first?.indent ?? 0\n\tconst items: ListItemNode[] = []\n\tlet index = start\n\twhile (index < lines.length) {\n\t\tconst parsed = extractListItem(lines[index] ?? '')\n\t\t// A sibling item shares the list's (top) indent + ordering; anything else stops\n\t\t// the top loop (a deeper item is a nested list, gathered as continuation below).\n\t\tif (!parsed || parsed.indent > topIndent || parsed.ordered !== ordered) break\n\t\tconst itemLines: string[] = [parsed.content]\n\t\tconst continuation = parsed.marker\n\t\tindex += 1\n\t\twhile (index < lines.length) {\n\t\t\tconst next = lines[index] ?? ''\n\t\t\tif (isBlankLine(next)) {\n\t\t\t\tconst after = lines[index + 1] ?? ''\n\t\t\t\tif (\n\t\t\t\t\tindex + 1 < lines.length &&\n\t\t\t\t\t!isBlankLine(after) &&\n\t\t\t\t\tleadingIndent(after) >= continuation\n\t\t\t\t) {\n\t\t\t\t\titemLines.push('')\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (leadingIndent(next) >= continuation) {\n\t\t\t\titemLines.push(next.slice(continuation))\n\t\t\t\tindex += 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (extractListItem(next) || startsBlock(lines, index)) break\n\t\t\titemLines.push(next.trim()) // a lazy paragraph-continuation line\n\t\t\tindex += 1\n\t\t}\n\t\titems.push({ element: 'listItem', children: parseBlocks(itemLines, depth + 1) })\n\t}\n\treturn { node: { element: 'list', ordered, start: startOrdinal, items }, next: index }\n}\n\n/**\n * Parses a markdown string into a typed {@link MarkdownDocument} AST via the\n * block phase.\n *\n * @param markdown - The markdown source to parse.\n * @returns The parsed document.\n */\nexport function parseDocument(markdown: string): MarkdownDocument {\n\treturn { element: 'document', children: parseBlocks(splitLines(markdown), 0) }\n}\n\n/**\n * Parses inline markdown text (emphasis, code spans, links) into inline AST\n * nodes, coalescing adjacent text runs.\n *\n * @param text - The inline markdown text to parse.\n * @returns The parsed inline nodes.\n */\nexport function parseInline(text: string): readonly InlineNode[] {\n\treturn coalesceText(scanInline(text, 0, text.length))\n}\n","import {\n\tbooleanShape,\n\tintegerShape,\n\tliteralShape,\n\tobjectShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\n\n// AGENTS section 14 / 4.6.1: shapers are `ContractShape` VALUES, not functions\n// or types - a JSON-Schema blueprint the compilers (factories.ts) turn into a\n// guard / parser / schema / generator in lockstep. Only the NON-recursive\n// parts of the markdown AST (types.ts) can be expressed here: a shape tree has\n// no lazy/self-referential node, so any type whose fields recurse into\n// `BlockNode` / `InlineNode` / `MarkdownNode` (EmphasisNode, LinkNode,\n// HeadingNode, ParagraphNode, ListItemNode, ListNode, TableNode,\n// BlockquoteNode, MarkdownDocument) is skipped here and stays guard-only\n// (validators.ts) via `lazyOf`.\n\n/**\n * The shape of a {@link TextNode} - a plain-text leaf inline run.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { textShape } from '@src/core'\n *\n * const text = createContract(textShape)\n * text.is({ element: 'text', value: 'hi' }) // true\n * ```\n */\nexport const textShape = objectShape({\n\telement: literalShape(['text']),\n\tvalue: stringShape(),\n})\n\n/**\n * The shape of a {@link CodeSpanNode} - an inline code span (`` `code` ``).\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { codeSpanShape } from '@src/core'\n *\n * const codeSpan = createContract(codeSpanShape)\n * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true\n * ```\n */\nexport const codeSpanShape = objectShape({\n\telement: literalShape(['codeSpan']),\n\tvalue: stringShape(),\n})\n\n/**\n * The shape of a {@link CodeBlockNode} - a fenced code block. `lang` is\n * optional (absent when the opening fence carries no info-string).\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { codeBlockShape } from '@src/core'\n *\n * const codeBlock = createContract(codeBlockShape)\n * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true\n * codeBlock.is({ element: 'codeBlock', code: 'x', lang: 'ts' }) // true\n * ```\n */\nexport const codeBlockShape = objectShape({\n\telement: literalShape(['codeBlock']),\n\tlang: optionalShape(stringShape()),\n\tcode: stringShape(),\n})\n\n/**\n * The shape of a {@link ThematicBreakNode} - a horizontal rule. Carries no\n * fields beyond its `element` discriminant.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { thematicBreakShape } from '@src/core'\n *\n * const thematicBreak = createContract(thematicBreakShape)\n * thematicBreak.is({ element: 'thematicBreak' }) // true\n * ```\n */\nexport const thematicBreakShape = objectShape({\n\telement: literalShape(['thematicBreak']),\n})\n\n/**\n * The shape of a {@link TableAlign} - the per-column GFM table alignment\n * literal.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { tableAlignShape } from '@src/core'\n *\n * const tableAlign = createContract(tableAlignShape)\n * tableAlign.is('left') // true\n * tableAlign.is('center') // true\n * tableAlign.is('top') // false\n * ```\n */\nexport const tableAlignShape = literalShape(['none', 'left', 'right', 'center'])\n\n/**\n * The shape of {@link ListItemParts} - the parsed parts of a single list-item\n * line the block phase's list detector returns. Fully non-recursive (no\n * nested node fields), so every field shapes directly.\n *\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { listItemPartsShape } from '@src/core'\n *\n * const listItemParts = createContract(listItemPartsShape)\n * listItemParts.is({ ordered: false, start: 1, content: 'hi', indent: 0, marker: 2 }) // true\n * ```\n */\nexport const listItemPartsShape = objectShape({\n\tordered: booleanShape(),\n\tstart: integerShape(),\n\tcontent: stringShape(),\n\tindent: integerShape(),\n\tmarker: integerShape(),\n})\n","import type {\n\tBlockNode,\n\tMarkdownDocument,\n\tMarkdownHandlers,\n\tMarkdownInterface,\n\tMarkdownNode,\n\tMarkdownRewriteHandler,\n} from './types.js'\nimport { foldNode, rewriteDocument, walkNodes } from './helpers.js'\nimport { parseDocument } from './parsers.js'\n\n/**\n * A stateful, parsed markdown document - wraps a typed {@link MarkdownDocument} AST\n * with the query (`find` / `filter` / `reduce` / iteration), rewrite (`map`), fold, and\n * streaming operations {@link MarkdownInterface} declares.\n *\n * @remarks\n * - **Construction.** Given a `string`, the constructor runs {@link parseDocument} (the\n * block phase then the inline phase) to build the AST. Given a {@link MarkdownDocument},\n * the document is adopted AS-IS and is NOT re-validated - a caller adopting an\n * untrusted value should gate it with `isMarkdownDocument` first.\n * - **Immutable.** {@link map} never mutates the stored AST - it returns a NEW `Markdown`\n * instance; the document root invariant (`element: 'document'`) always holds.\n * - **Traversal order.** {@link walk} and the `find` / `filter` / `reduce` queries built\n * on it walk the AST depth-first, pre-order, root-inclusive (via {@link walkNodes});\n * `stream` is shallow - only the document's direct block children.\n *\n * @example\n * ```ts\n * import { Markdown, isHeadingNode, renderMarkdown } from '@src/core'\n *\n * const markdown = new Markdown('# Title\\n\\nA **bold** [link](https://x.dev).')\n * const heading = markdown.find(isHeadingNode) // the HeadingNode, or undefined\n * const shouted = markdown.map((node) =>\n * node.element === 'text' ? { element: 'text', value: node.value.toUpperCase() } : node,\n * )\n * renderMarkdown(shouted.document) // '# TITLE\\n\\nA **BOLD** [LINK](https://x.dev).'\n * ```\n */\nexport class Markdown implements MarkdownInterface {\n\treadonly #document: MarkdownDocument\n\n\tconstructor(input: string | MarkdownDocument) {\n\t\tthis.#document = typeof input === 'string' ? parseDocument(input) : input\n\t}\n\n\t/** The stored {@link MarkdownDocument} AST root. */\n\tget document(): MarkdownDocument {\n\t\treturn this.#document\n\t}\n\n\t/**\n\t * THE deep traversal - a lazy, depth-first, pre-order, root-inclusive generator\n\t * over every {@link MarkdownNode} in the document. `find` / `filter` / `reduce`\n\t * all iterate this single traversal.\n\t *\n\t * @example\n\t * ```ts\n\t * for (const node of markdown.walk()) {\n\t * // every node, depth-first, pre-order, root-inclusive\n\t * }\n\t *\n\t * // also consumable by for-await - JS accepts a sync iterable in for-await\n\t * for await (const node of markdown.walk()) {\n\t * // same sequence, no separate async iterator needed\n\t * }\n\t * ```\n\t */\n\t*walk(): Generator<MarkdownNode> {\n\t\tyield* walkNodes(this.#document)\n\t}\n\n\t// Finds the first node (depth-first, pre-order) narrowed by a type guard.\n\tfind<T extends MarkdownNode>(guard: (node: MarkdownNode) => node is T): T | undefined\n\t// Finds the first node (depth-first, pre-order) matching a predicate.\n\tfind(predicate: (node: MarkdownNode) => boolean): MarkdownNode | undefined\n\tfind(predicate: (node: MarkdownNode) => boolean): MarkdownNode | undefined {\n\t\tfor (const node of this.walk()) if (predicate(node)) return node\n\t\treturn undefined\n\t}\n\n\t// Collects every node (depth-first, pre-order) narrowed by a type guard.\n\tfilter<T extends MarkdownNode>(guard: (node: MarkdownNode) => node is T): readonly T[]\n\t// Collects every node (depth-first, pre-order) matching a predicate.\n\tfilter(predicate: (node: MarkdownNode) => boolean): readonly MarkdownNode[]\n\tfilter(predicate: (node: MarkdownNode) => boolean): readonly MarkdownNode[] {\n\t\tconst out: MarkdownNode[] = []\n\t\tfor (const node of this.walk()) if (predicate(node)) out.push(node)\n\t\treturn out\n\t}\n\n\t/** Rewrites the AST bottom-up (copy-on-write) and returns a new {@link Markdown}. */\n\tmap(rewrite: MarkdownRewriteHandler): MarkdownInterface {\n\t\treturn new Markdown(rewriteDocument(this.#document, rewrite))\n\t}\n\n\t/** Folds the AST depth-first, pre-order into an accumulator. */\n\treduce<T>(callback: (accumulator: T, node: MarkdownNode) => T, initial: T): T {\n\t\tlet accumulator = initial\n\t\tfor (const node of this.walk()) accumulator = callback(accumulator, node)\n\t\treturn accumulator\n\t}\n\n\t/** Runs a total catamorphism over the document using a {@link MarkdownHandlers} table. */\n\tfold<T>(handlers: MarkdownHandlers<T>): T {\n\t\treturn foldNode(this.#document, handlers, 0)\n\t}\n\n\t/**\n\t * A web-standard {@link ReadableStream} over the document's top-level block nodes\n\t * (shallow, source order) - a fresh, pull-based source per call: one block is\n\t * enqueued per `pull`, so a slow reader's backpressure is respected. Cancellable,\n\t * async-iterable wherever the platform supports it (Node, Deno), and pipeable\n\t * through any {@link TransformStream} / {@link WritableStream}.\n\t *\n\t * @example\n\t * ```ts\n\t * // universal - works in every ReadableStream-supporting environment\n\t * const reader = markdown.stream().getReader()\n\t * for (let result = await reader.read(); !result.done; result = await reader.read()) {\n\t * console.log(result.value) // one BlockNode\n\t * }\n\t *\n\t * // Node / Deno / Firefox support async iteration of ReadableStream natively;\n\t * // other environments should use the reader loop above instead.\n\t * for await (const block of markdown.stream()) {\n\t * console.log(block)\n\t * }\n\t * ```\n\t */\n\tstream(): ReadableStream<BlockNode> {\n\t\tconst blocks = this.#document.children\n\t\tlet index = 0\n\t\treturn new ReadableStream<BlockNode>({\n\t\t\tpull(controller) {\n\t\t\t\tif (index < blocks.length) {\n\t\t\t\t\tcontroller.enqueue(blocks[index])\n\t\t\t\t\tindex += 1\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.close()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tCodeBlockNode,\n\tCodeSpanNode,\n\tMarkdownDocument,\n\tMarkdownInterface,\n\tTextNode,\n\tThematicBreakNode,\n} from './types.js'\nimport { createContract } from '@orkestrel/contract'\nimport { Markdown } from './Markdown.js'\nimport { codeBlockShape, codeSpanShape, textShape, thematicBreakShape } from './shapers.js'\n\n/**\n * Create a stateful markdown handle from a markdown string or an already-parsed\n * {@link MarkdownDocument} - a typed AST plus the query, rewrite, and fold operations\n * {@link MarkdownInterface} exposes.\n *\n * @remarks\n * Given a `string`, runs a block phase (headings / paragraphs / lists / GFM tables /\n * fenced code / blockquotes / thematic breaks) then an inline phase (emphasis /\n * inline code / links) to build a render-agnostic {@link MarkdownDocument}. Given a\n * {@link MarkdownDocument}, adopts it AS-IS without re-validation - gate an untrusted\n * value with `isMarkdownDocument` first. Pure + total parse (malformed markdown\n * degrades to text, never throws) and zero-dependency - a hand-written scanner, no\n * regex-only structural parse, linear-time (no ReDoS).\n *\n * @param input - A markdown string to parse, or an already-parsed {@link MarkdownDocument}\n * @returns A working {@link MarkdownInterface}\n *\n * @example\n * ```ts\n * import { createMarkdown } from '@src/core'\n *\n * const markdown = createMarkdown('# Hi\\n\\nRead the [guide](./guide.md).')\n * markdown.document.children[0] // { element: 'heading', ... }\n * ```\n */\nexport function createMarkdown(input: string | MarkdownDocument): MarkdownInterface {\n\treturn new Markdown(input)\n}\n\n/**\n * Compile the {@link textShape} into a {@link ContractInterface} for\n * {@link TextNode} - a guard, coercing parser, JSON Schema, and seeded\n * generator from one shape declaration (AGENTS §14).\n *\n * @returns A `TextNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createTextContract } from '@src/core'\n *\n * const text = createTextContract()\n * text.is({ element: 'text', value: 'hi' }) // true\n * ```\n */\nexport function createTextContract(): ContractInterface<TextNode> {\n\treturn createContract(textShape)\n}\n\n/**\n * Compile the {@link codeSpanShape} into a {@link ContractInterface} for\n * {@link CodeSpanNode} - a guard, coercing parser, JSON Schema, and seeded\n * generator from one shape declaration (AGENTS §14).\n *\n * @returns A `CodeSpanNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createCodeSpanContract } from '@src/core'\n *\n * const codeSpan = createCodeSpanContract()\n * codeSpan.is({ element: 'codeSpan', value: 'const x = 1' }) // true\n * ```\n */\nexport function createCodeSpanContract(): ContractInterface<CodeSpanNode> {\n\treturn createContract(codeSpanShape)\n}\n\n/**\n * Compile the {@link codeBlockShape} into a {@link ContractInterface} for\n * {@link CodeBlockNode} - a guard, coercing parser, JSON Schema, and seeded\n * generator from one shape declaration (AGENTS §14).\n *\n * @returns A `CodeBlockNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createCodeBlockContract } from '@src/core'\n *\n * const codeBlock = createCodeBlockContract()\n * codeBlock.is({ element: 'codeBlock', code: 'x' }) // true\n * ```\n */\nexport function createCodeBlockContract(): ContractInterface<CodeBlockNode> {\n\treturn createContract(codeBlockShape)\n}\n\n/**\n * Compile the {@link thematicBreakShape} into a {@link ContractInterface} for\n * {@link ThematicBreakNode} - a guard, coercing parser, JSON Schema, and\n * seeded generator from one shape declaration (AGENTS §14).\n *\n * @returns A `ThematicBreakNode` contract bundling `schema` / `is` / `parse` / `generate`\n *\n * @example\n * ```ts\n * import { createThematicBreakContract } from '@src/core'\n *\n * const thematicBreak = createThematicBreakContract()\n * thematicBreak.is({ element: 'thematicBreak' }) // true\n * ```\n */\nexport function createThematicBreakContract(): ContractInterface<ThematicBreakNode> {\n\treturn createContract(thematicBreakShape)\n}\n"],"mappings":";;;;;;;;AAMA,IAAa,mCAAwC,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAU;AAAK,CAAC;;;;;;;;;;AAW/F,IAAa,YAAY;;;;;;;;;;;;;;;;ACiCzB,SAAgB,aAAa,WAA4B;CACxD,OAAO,cAAc,OAAO,cAAc,OAAQ,cAAc;AACjE;;;;;;;;;;;;;;AAeA,SAAgB,YAAY,WAA4B;CACvD,OAAO,0BAA0B,KAAK,SAAS;AAChD;;;;;;;;;;;;;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