/** * The deterministic JSON-object repair tier — decide how JSON-like a malformed text is ({@link scoreJsonObjectText}), fix * the shape slips that need no judgment ({@link repairJsonObjectText}), and prove a repair invented and dropped nothing * ({@link checkJsonRepairFidelity}). Pure: no I/O. Built for model replies that should have been one JSON object. * * ONE LENIENT WALK. A string-aware tokenizer carries a container stack and an EXPECT state, records every fault with * its index, and rebuilds the text as it goes, applying a recovery op wherever one exists. The score, the verdict and * the repair all derive from that one walk. Pass 2 re-walks with the inner-quote heuristic only when pass 1 could not * produce a parseable object. * * WHAT IS NEVER REPAIRED. A text that ends INSIDE a string, or right after a `:`, a `,`, a bare key or an opener, is * `truncated-looking`: that is the signature of cut content, and no tier may invent the end of a value. Python * literals, unquoted keys, comments and single quotes are left to a judgment tier. */ import { type Maybe } from '../value/maybe.type'; /** * The scorer's verdict on one text. * * - `near-miss` — every fault is one the deterministic tier recovers, the rebuilt text parses into an object, and the * repair is faithful. * - `mangled` — object-led, not truncated-looking, but some fault needs judgment (or the rebuilt text failed parse / * fidelity). * - `truncated-looking` — ends inside a string, or right after `:` / `,` / a bare key / an opener. Never repaired. * - `not-json` — no `{`, not object-led, or less than a fifth of the object reads as JSON. */ export type JsonRepairVerdict = 'near-miss' | 'mangled' | 'truncated-looking' | 'not-json'; /** * One kind of structural fault the scorer's walk found. */ export type JsonRepairFaultKind = 'unclosed' | 'trailing-comma' | 'missing-comma' | 'mismatched-closer' | 'stray-closer' | 'control-in-string' | 'inner-quote' | 'trailing-prose' | 'ends-in-string' | 'dangling' | 'unexpected'; /** * One recorded fault — its kind and the index in the ORIGINAL text it was found at. */ export interface JsonRepairFault { /** * The fault's kind. */ readonly kind: JsonRepairFaultKind; /** * The index in the original text the fault was found at. */ readonly at: number; } /** * The scorer's reading of one text. */ export interface JsonRepairShape { /** * The verdict ({@link JsonRepairVerdict}). */ readonly verdict: JsonRepairVerdict; /** * The fraction of the object text (first `{` → trimmed end) that is valid JSON before the FIRST structural fault. * A text whose only fault is stopping with containers open scores 1. */ readonly score: number; /** * Whether the first non-whitespace character (after one optional leading code-fence line) is `{`. */ readonly objectLed: boolean; /** * The index of the object's opening `{`, `-1` when there is none. */ readonly objectStart: number; /** * The index of the first structural fault (excluding the end-of-input faults), when there is one. */ readonly faultAt?: number; /** * The recorded faults, in order (capped at {@link JSON_REPAIR_MAX_RECORDED_FAULTS}). */ readonly faults: ReadonlyArray; /** * The open-container stack where the walk ended, e.g. `'{'` — `''` when balanced. */ readonly unclosed: string; /** * The text length (UTF-16 code units). */ readonly length: number; } /** * One deterministic recovery op. */ export type JsonRepairOpKind = 'close-object' | 'close-array' | 'drop-trailing-comma' | 'insert-missing-comma' | 'insert-missing-closer' | 'drop-stray-closer' | 'escape-control' | 'escape-inner-quote' | 'strip-trailing-prose' | 'strip-code-fence'; /** * The ops a repair applied, counted by kind. */ export type JsonRepairOpCounts = Readonly>>; /** * A deterministic repair's product. */ export interface JsonRepairProduct { /** * The repaired JSON text (the object only — surrounding prose / fences dropped). */ readonly text: string; /** * The parsed repaired object. */ readonly value: Record; /** * The ops applied. */ readonly ops: JsonRepairOpCounts; /** * Which pass produced it — pass 2 is the inner-quote re-walk. */ readonly pass: 1 | 2; } /** * The result of {@link repairJsonObjectText} — the shape, plus the repair iff the verdict is `near-miss`. */ export interface JsonRepairResult { /** * The scorer's shape of the text. */ readonly shape: JsonRepairShape; /** * The repair, present iff the verdict is `near-miss`. */ readonly repaired?: JsonRepairProduct; } /** * The fidelity verdict of one repair. */ export interface JsonRepairFidelity { /** * Nothing invented AND coverage ≥ {@link JSON_REPAIR_MIN_COVERAGE}. */ readonly ok: boolean; /** * The repaired strings / keys / numbers that do not appear in the original (capped at 8). */ readonly invented: ReadonlyArray; /** * The fraction of the original's content literals the repair kept (1 when none were checked). */ readonly coverage: number; /** * How many content literals were checked. */ readonly checked: number; } /** * Optional settings for {@link repairJsonObjectText} and {@link scoreJsonObjectText}. */ export interface RepairJsonObjectTextConfig { /** * Take the fidelity coverage check over the value of the first `"":` in the original: when that value is an object * that closes, the region is its balanced `{…}` slice (an envelope field after it does not count); when it never closes * (cut or mangled) or is not an object, the region runs to the end of the text. Unset (or the key not found) ⇒ the whole * text is checked. */ readonly coverageFromKey?: Maybe; } /** * The input of {@link checkJsonRepairFidelity}. */ export interface CheckJsonRepairFidelityConfig extends RepairJsonObjectTextConfig { /** * The original text. */ readonly original: string; /** * The repaired value. */ readonly repaired: unknown; } /** * The fraction of the original's content literals a repair must keep. */ export declare const JSON_REPAIR_MIN_COVERAGE = 0.9; /** * The shortest string literal the coverage check counts as CONTENT (shorter ones are ids / enum values / keys). */ export declare const JSON_REPAIR_CONTENT_LITERAL_MIN_CHARS = 12; /** * The most faults one shape records (the op counts are never capped). */ export declare const JSON_REPAIR_MAX_RECORDED_FAULTS = 32; /** * Below this score a malformed object-led text reads as `not-json`. */ export declare const JSON_REPAIR_NOT_JSON_MAX_SCORE = 0.2; /** * The faults that sit at EOF and so do not count against the score. */ export declare const JSON_REPAIR_EOF_FAULT_KINDS: ReadonlySet; /** * Scores a text that should have been one JSON object and, when it is a near miss, repairs it. * * The repair fixes only slips that need no judgment: containers left open at EOF, trailing and missing commas, a missing or * stray closer, raw control characters in strings, inner quotes (second pass), and a code fence or prose around the object. * A repair is kept only when {@link checkJsonRepairFidelity} proves it invented and dropped nothing. A text that looks cut * off is never repaired. A rebuilt text that does not parse is reported through the verdict, never thrown. * * @param text - The text that should hold one JSON object. * @param config - Optional settings; `coverageFromKey` limits the fidelity coverage region. * @returns The shape, plus the repair iff the verdict is `near-miss`. * * @dbxUtil * @dbxUtilCategory string * @dbxUtilTags json, repair, lenient, fix, object, llm, reply, parse * @dbxUtilRelated score-json-object-text, check-json-repair-fidelity, repair-json-object-or-undefined * * @example * ```ts * repairJsonObjectText('{"a":1,"b":[1,2,],}').repaired?.value; // { a: 1, b: [1, 2] } * repairJsonObjectText('{"a":"cut').shape.verdict; // 'truncated-looking' * ``` */ export declare function repairJsonObjectText(text: string, config?: Maybe): JsonRepairResult; /** * Scores a text that should have been one JSON object, without keeping the repair. * * @param text - The text that should hold one JSON object. * @param config - Optional settings; `coverageFromKey` limits the fidelity coverage region. * @returns The shape {@link repairJsonObjectText} computes. * * @dbxUtil * @dbxUtilCategory string * @dbxUtilTags json, repair, score, verdict, lenient, object, llm, reply * @dbxUtilRelated repair-json-object-text * * @example * ```ts * scoreJsonObjectText('{"a":1,').verdict; // 'truncated-looking' * scoreJsonObjectText('no json here').verdict; // 'not-json' * ``` */ export declare function scoreJsonObjectText(text: string, config?: Maybe): JsonRepairShape; /** * Parses text into a JSON object, falling back to the deterministic repair when it does not parse. * * Valid object JSON returns its parsed value. Otherwise the repair's value is returned when the text is a faithful near miss, * and `undefined` when it is not. Its `(text) => value` shape lets it stand in wherever a plain JSON decoder is accepted, so * repair stays an explicit opt-in. * * @param text - The text that should hold one JSON object. * @param config - Optional repair settings. * @returns The parsed or repaired object, or `undefined`. * * @dbxUtil * @dbxUtilCategory string * @dbxUtilTags json, repair, parse, lenient, object, decode, llm, reply * @dbxUtilRelated repair-json-object-text, parse-json-object-or-undefined * * @example * ```ts * repairJsonObjectOrUndefined('{"a":1'); // { a: 1 } * repairJsonObjectOrUndefined('{"a":"cut'); // undefined * ``` */ export declare function repairJsonObjectOrUndefined(text: Maybe, config?: Maybe): Maybe>; /** * Proves a repair invented and dropped nothing — the runtime gate on any repair of a JSON object text. * * - Nothing invented: every string leaf, object key and number of the repaired value appears in the original (strings * compared with whitespace, quotes and backslashes removed; numbers as numeric tokens). * - Nothing dropped: at least {@link JSON_REPAIR_MIN_COVERAGE} of the original's content literals (string literals of at * least {@link JSON_REPAIR_CONTENT_LITERAL_MIN_CHARS} characters, taken over the value of `coverageFromKey` when it is set * and found — its balanced object, or the rest of the text when that value is unclosed or not an object) * appear in the repaired value. * * @param config - The original text, the repaired value, and the optional coverage key. * @returns The fidelity verdict. * * @dbxUtil * @dbxUtilCategory string * @dbxUtilTags json, repair, fidelity, verify, coverage, llm, reply * @dbxUtilRelated repair-json-object-text * * @example * ```ts * checkJsonRepairFidelity({ original: '{"a":1', repaired: { a: 1 } }).ok; // true * checkJsonRepairFidelity({ original: '{"a":1', repaired: { a: 2 } }).invented; // ['2'] * ``` */ export declare function checkJsonRepairFidelity(config: CheckJsonRepairFidelityConfig): JsonRepairFidelity;