@nexkit/json-repair 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/README.md +365 -0
- package/dist/cli.js +2744 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +2400 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +343 -0
- package/dist/index.d.ts +343 -0
- package/dist/index.js +2389 -0
- package/dist/index.js.map +1 -0
- package/package.json +97 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/scanner/tokens.ts","../src/scanner/scanner.ts","../src/errors/JsonRepairError.ts","../src/limits.ts","../src/native.ts","../src/types.ts","../src/options.ts","../src/repair/brackets.ts","../src/repair/comments.ts","../src/repair/literals.ts","../src/repair/numbers.ts","../src/parser/probe.ts","../src/repair/quotes.ts","../src/repair/trailing-comma.ts","../src/parser/parser.ts","../src/repair/messages.ts","../src/parser/state.ts","../src/repair/markdown.ts","../src/extract.ts","../src/repair.ts","../src/cli/run.ts","../src/cli/index.ts"],"names":["code","matchesWord","parsed","io","text"],"mappings":";;;;;AAaO,IAAM,aAAA,GAAgB,GAAA;AACtB,IAAM,cAAA,GAAiB,GAAA;AACvB,IAAM,eAAA,GAAkB,EAAA;AACxB,IAAM,gBAAA,GAAmB,EAAA;AACzB,IAAM,QAAA,GAAW,EAAA;AACjB,IAAM,QAAA,GAAW,EAAA;AAIjB,IAAM,eAAA,GAAkB,EAAA;AACxB,IAAM,eAAA,GAAkB,EAAA;AACxB,IAAM,WAAA,GAAc,EAAA;AACpB,IAAM,oBAAA,GAAuB,IAAA;AAC7B,IAAM,qBAAA,GAAwB,IAAA;AAC9B,IAAM,mBAAA,GAAsB,IAAA;AAC5B,IAAM,uBAAA,GAA0B,IAAA;AAChC,IAAM,oBAAA,GAAuB,IAAA;AAC7B,IAAM,qBAAA,GAAwB,IA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AM,IAAI,CAAA;AAAA,EAC3B,CAAA;AAAA,EACA,UAAA,EAAY,CAAC,IAAA,KAAS;AACpB,IAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,EAC3B;AACF,CAAA;AAUA,eAAe,IAAA,GAAsB;AACnC,EAAA,OAAA,CAAQ,QAAA,GAAW,MAAM,GAAA,CAAI,OAAA,CAAQ,KAAK,KAAA,CAAM,CAAC,GAAG,EAAE,CAAA;AACxD;AAEA,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,KAAA,KAAmB;AAC/B,EAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,+BAAA,EAAkC,OAAO;AAAA,CAAI,CAAA;AAClE,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.js","sourcesContent":["/**\n * Character-code constants and predicates shared by the scanner, the parser and\n * the repair rules.\n *\n * Everything here works on UTF-16 code units via `charCodeAt`. The package uses\n * no regular expressions at all — a deliberate choice, since a repair engine\n * fed adversarial input is exactly where catastrophic backtracking bites. Every\n * predicate below is a constant-time comparison, which keeps the whole pipeline\n * linear in the length of the input.\n */\n\n/* ── Structural characters ──────────────────────────────────────────────── */\n\nexport const CH_OPEN_BRACE = 0x7b; /* { */\nexport const CH_CLOSE_BRACE = 0x7d; /* } */\nexport const CH_OPEN_BRACKET = 0x5b; /* [ */\nexport const CH_CLOSE_BRACKET = 0x5d; /* ] */\nexport const CH_COLON = 0x3a; /* : */\nexport const CH_COMMA = 0x2c; /* , */\n\n/* ── Quotes ─────────────────────────────────────────────────────────────── */\n\nexport const CH_DOUBLE_QUOTE = 0x22; /* \" */\nexport const CH_SINGLE_QUOTE = 0x27; /* ' */\nexport const CH_BACKTICK = 0x60; /* ` */\nexport const CH_LEFT_SINGLE_QUOTE = 0x2018; /* ‘ */\nexport const CH_RIGHT_SINGLE_QUOTE = 0x2019; /* ’ */\nexport const CH_SINGLE_LOW_QUOTE = 0x201a; /* ‚ */\nexport const CH_SINGLE_HIGH_REVERSED = 0x201b; /* ‛ */\nexport const CH_LEFT_DOUBLE_QUOTE = 0x201c; /* “ */\nexport const CH_RIGHT_DOUBLE_QUOTE = 0x201d; /* ” */\nexport const CH_DOUBLE_LOW_QUOTE = 0x201e; /* „ */\nexport const CH_DOUBLE_HIGH_REVERSED = 0x201f; /* ‟ */\n\n/* ── Escapes, comments, signs ───────────────────────────────────────────── */\n\nexport const CH_BACKSLASH = 0x5c; /* \\ */\nexport const CH_SLASH = 0x2f; /* / */\nexport const CH_ASTERISK = 0x2a; /* * */\nexport const CH_HASH = 0x23; /* # */\nexport const CH_MINUS = 0x2d; /* - */\nexport const CH_PLUS = 0x2b; /* + */\nexport const CH_DOT = 0x2e; /* . */\nexport const CH_UNDERSCORE = 0x5f; /* _ */\nexport const CH_DOLLAR = 0x24; /* $ */\n\n/* ── Whitespace and line breaks ─────────────────────────────────────────── */\n\nexport const CH_TAB = 0x09;\nexport const CH_LINE_FEED = 0x0a;\nexport const CH_VERTICAL_TAB = 0x0b;\nexport const CH_FORM_FEED = 0x0c;\nexport const CH_CARRIAGE_RETURN = 0x0d;\nexport const CH_SPACE = 0x20;\nexport const CH_NBSP = 0x00a0;\nexport const CH_BOM = 0xfeff;\n\n/* ── Letters used by literal and escape handling ────────────────────────── */\n\nexport const CH_LOWER_A = 0x61;\nexport const CH_LOWER_B = 0x62;\nexport const CH_LOWER_E = 0x65;\nexport const CH_LOWER_F = 0x66;\nexport const CH_LOWER_N = 0x6e;\nexport const CH_LOWER_R = 0x72;\nexport const CH_LOWER_T = 0x74;\nexport const CH_LOWER_U = 0x75;\nexport const CH_LOWER_X = 0x78;\nexport const CH_LOWER_Z = 0x7a;\nexport const CH_UPPER_A = 0x41;\nexport const CH_UPPER_E = 0x45;\nexport const CH_UPPER_F = 0x46;\nexport const CH_UPPER_X = 0x58;\nexport const CH_UPPER_Z = 0x5a;\nexport const CH_ZERO = 0x30;\nexport const CH_NINE = 0x39;\n\n/* ── Surrogates ─────────────────────────────────────────────────────────── */\n\nexport const CH_HIGH_SURROGATE_START = 0xd800;\nexport const CH_HIGH_SURROGATE_END = 0xdbff;\nexport const CH_LOW_SURROGATE_START = 0xdc00;\nexport const CH_LOW_SURROGATE_END = 0xdfff;\n\n/** Sentinel returned by the scanner past the end of its bounded region. */\nexport const CH_EOF = -1;\n\n/* ── Predicates ─────────────────────────────────────────────────────────── */\n\n/**\n * Whitespace recognised *between* tokens.\n *\n * Wider than the four characters JSON allows, because malformed input pasted\n * from a browser, a PDF or a word processor routinely carries non-breaking\n * spaces and Unicode separators. They are treated as trivia and dropped, never\n * as data — inside a string literal these characters remain untouched content.\n */\nexport function isWhitespace(code: number): boolean {\n switch (code) {\n case CH_SPACE:\n case CH_TAB:\n case CH_LINE_FEED:\n case CH_CARRIAGE_RETURN:\n case CH_VERTICAL_TAB:\n case CH_FORM_FEED:\n case CH_NBSP:\n case CH_BOM:\n case 0x1680: /* OGHAM SPACE MARK */\n case 0x2028: /* LINE SEPARATOR */\n case 0x2029: /* PARAGRAPH SEPARATOR */\n case 0x202f: /* NARROW NO-BREAK SPACE */\n case 0x205f: /* MEDIUM MATHEMATICAL SPACE */\n case 0x3000 /* IDEOGRAPHIC SPACE */:\n return true;\n default:\n // U+2000..U+200A: EN QUAD through HAIR SPACE.\n return code >= 0x2000 && code <= 0x200a;\n }\n}\n\n/**\n * The four characters JSON itself allows between tokens.\n *\n * Anything {@link isWhitespace} accepts beyond these is a repair, not trivia, so\n * skipping it has to be recorded in the repair log.\n */\nexport function isJsonWhitespace(code: number): boolean {\n return (\n code === CH_SPACE || code === CH_TAB || code === CH_LINE_FEED || code === CH_CARRIAGE_RETURN\n );\n}\n\n/** Reports whether `code` ends a line for the purpose of line/column reporting. */\nexport function isLineBreak(code: number): boolean {\n return code === CH_LINE_FEED || code === CH_CARRIAGE_RETURN;\n}\n\n/** Reports whether `code` is an ASCII decimal digit. */\nexport function isDigit(code: number): boolean {\n return code >= CH_ZERO && code <= CH_NINE;\n}\n\n/** Reports whether `code` is a hexadecimal digit in either case. */\nexport function isHexDigit(code: number): boolean {\n return (\n (code >= CH_ZERO && code <= CH_NINE) ||\n (code >= CH_UPPER_A && code <= CH_UPPER_F) ||\n (code >= CH_LOWER_A && code <= CH_LOWER_F)\n );\n}\n\n/**\n * Reports whether `code` opens a string literal in some dialect.\n *\n * Covers the JSON `\"`, the JavaScript `'` and `` ` ``, and the typographic\n * quotes U+2018..U+201F that word processors and LLM prose substitute. The\n * table is deliberately closed: guillemets (`«` `»`) and CJK brackets are *not*\n * included, because they appear far more often as ordinary prose punctuation\n * than as string delimiters.\n */\nexport function isQuote(code: number): boolean {\n switch (code) {\n case CH_DOUBLE_QUOTE:\n case CH_SINGLE_QUOTE:\n case CH_BACKTICK:\n case CH_LEFT_SINGLE_QUOTE:\n case CH_RIGHT_SINGLE_QUOTE:\n case CH_SINGLE_LOW_QUOTE:\n case CH_SINGLE_HIGH_REVERSED:\n case CH_LEFT_DOUBLE_QUOTE:\n case CH_RIGHT_DOUBLE_QUOTE:\n case CH_DOUBLE_LOW_QUOTE:\n case CH_DOUBLE_HIGH_REVERSED:\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Returns the set of code units that can close a string opened by `code`.\n *\n * Typographic quotes are paired, so a string opened with `“` closes on `”` —\n * but LLM output mixes them freely, so the opening character is accepted as a\n * closer too. Returns `-1` for the second slot when there is only one closer.\n */\nexport function closersFor(code: number): readonly [number, number] {\n switch (code) {\n case CH_LEFT_DOUBLE_QUOTE:\n case CH_DOUBLE_LOW_QUOTE:\n case CH_DOUBLE_HIGH_REVERSED:\n return [CH_RIGHT_DOUBLE_QUOTE, code];\n case CH_RIGHT_DOUBLE_QUOTE:\n return [CH_RIGHT_DOUBLE_QUOTE, CH_LEFT_DOUBLE_QUOTE];\n case CH_LEFT_SINGLE_QUOTE:\n case CH_SINGLE_LOW_QUOTE:\n case CH_SINGLE_HIGH_REVERSED:\n return [CH_RIGHT_SINGLE_QUOTE, code];\n case CH_RIGHT_SINGLE_QUOTE:\n return [CH_RIGHT_SINGLE_QUOTE, CH_LEFT_SINGLE_QUOTE];\n default:\n return [code, -1];\n }\n}\n\n/**\n * Reports whether a string opened by `code` follows JSON escaping rules.\n *\n * Only `\"` does. Inside `'`, `` ` `` or typographic quotes an apostrophe is far\n * more likely to be prose than a delimiter, which is why the continuation probe\n * treats those delimiters more permissively.\n */\nexport function isStandardQuote(code: number): boolean {\n return code === CH_DOUBLE_QUOTE;\n}\n\n/**\n * Reports whether `code` may start a bare (unquoted) object key or literal.\n *\n * Matches the JavaScript identifier convention restricted to ASCII letters plus\n * `_` and `$`, and additionally admits any code unit at or above U+00C0 so that\n * non-English keys (`{café: 1}`, `{名前: 1}`) are recognised. Digits are handled\n * by {@link isIdentifierPart} only, so `{2fast: 1}` is not mistaken for a key.\n */\nexport function isIdentifierStart(code: number): boolean {\n return (\n (code >= CH_LOWER_A && code <= CH_LOWER_Z) ||\n (code >= CH_UPPER_A && code <= CH_UPPER_Z) ||\n code === CH_UNDERSCORE ||\n code === CH_DOLLAR ||\n code >= 0x00c0\n );\n}\n\n/** Reports whether `code` may continue a bare object key or literal. */\nexport function isIdentifierPart(code: number): boolean {\n return isIdentifierStart(code) || isDigit(code) || code === CH_MINUS || code === CH_DOT;\n}\n\n/**\n * Reports whether `code` terminates an unquoted value in aggressive mode.\n *\n * Bare values run until a structural character, so `{a: hello world}` yields the\n * single value `\"hello world\"` rather than two tokens.\n */\nexport function isStructural(code: number): boolean {\n switch (code) {\n case CH_OPEN_BRACE:\n case CH_CLOSE_BRACE:\n case CH_OPEN_BRACKET:\n case CH_CLOSE_BRACKET:\n case CH_COLON:\n case CH_COMMA:\n case CH_EOF:\n return true;\n default:\n return false;\n }\n}\n\n/** Reports whether `code` is the high half of a surrogate pair. */\nexport function isHighSurrogate(code: number): boolean {\n return code >= CH_HIGH_SURROGATE_START && code <= CH_HIGH_SURROGATE_END;\n}\n\n/** Reports whether `code` is the low half of a surrogate pair. */\nexport function isLowSurrogate(code: number): boolean {\n return code >= CH_LOW_SURROGATE_START && code <= CH_LOW_SURROGATE_END;\n}\n\n/**\n * Lower-cases an ASCII letter code unit; returns other codes unchanged.\n *\n * Used for case-insensitive literal matching (`TRUE`, `Null`) without building\n * substrings or touching locale-sensitive `toLowerCase`, which would break the\n * determinism requirement under a Turkish locale.\n */\nexport function toLowerAscii(code: number): number {\n return code >= CH_UPPER_A && code <= CH_UPPER_Z ? code + 0x20 : code;\n}\n","import { CH_CARRIAGE_RETURN, CH_EOF, CH_LINE_FEED } from './tokens.js';\n\n/** A one-based line/column pair, resolved against the original input. */\nexport interface SourcePosition {\n line: number;\n column: number;\n}\n\n/**\n * A cursor over a bounded region of the original input.\n *\n * Extraction never copies: it narrows {@link Scanner.start} and leaves\n * {@link Scanner.source} pointing at the caller's original string. Every offset\n * the engine reports is therefore already absolute, so repair positions stay\n * meaningful even when the JSON was buried in prose.\n *\n * Line and column numbers are derived from an index of line starts that is\n * built on first use. Malformed input that produces no diagnostics never pays\n * for it.\n */\nexport class Scanner {\n /** The original, uncut input. */\n readonly source: string;\n\n /** First offset of the region being parsed. */\n readonly start: number;\n\n /** Offset one past the last character of the region. */\n readonly end: number;\n\n /** Current offset. Always within `[start, end]`. */\n index: number;\n\n /** Offsets at which each line begins; built lazily by {@link positionAt}. */\n private lineStarts: number[] | undefined;\n\n constructor(source: string, start = 0, end = source.length) {\n this.source = source;\n this.start = start;\n this.end = end;\n this.index = start;\n }\n\n /** Reports whether the cursor has reached the end of the region. */\n eof(): boolean {\n return this.index >= this.end;\n }\n\n /** Returns the code unit at the cursor, or {@link CH_EOF} at the end. */\n peek(): number {\n return this.index < this.end ? this.source.charCodeAt(this.index) : CH_EOF;\n }\n\n /** Returns the text between two absolute offsets. */\n slice(from: number, to: number): string {\n return this.source.slice(from, to);\n }\n\n /**\n * Resolves an absolute offset to a one-based line and column.\n *\n * `\\n`, `\\r\\n` and a lone `\\r` all end a line. U+2028 and U+2029 do not:\n * JSON treats them as ordinary string content, and counting them would make\n * positions disagree with what an editor shows.\n */\n positionAt(offset: number): SourcePosition {\n const starts = this.lineStarts ?? (this.lineStarts = buildLineStarts(this.source));\n\n // Binary search for the last line start at or before `offset`.\n let low = 0;\n let high = starts.length - 1;\n while (low < high) {\n const mid = (low + high + 1) >>> 1;\n if (starts[mid]! <= offset) {\n low = mid;\n } else {\n high = mid - 1;\n }\n }\n\n return { line: low + 1, column: offset - starts[low]! + 1 };\n }\n}\n\n/** Computes the offset at which each line of `source` begins. */\nfunction buildLineStarts(source: string): number[] {\n const starts: number[] = [0];\n const length = source.length;\n\n for (let index = 0; index < length; index += 1) {\n const code = source.charCodeAt(index);\n if (code === CH_CARRIAGE_RETURN) {\n // Treat CRLF as a single break so a column is never counted twice.\n if (index + 1 < length && source.charCodeAt(index + 1) === CH_LINE_FEED) {\n index += 1;\n }\n starts.push(index + 1);\n } else if (code === CH_LINE_FEED) {\n starts.push(index + 1);\n }\n }\n\n return starts;\n}\n","import { Scanner } from '../scanner/scanner.js';\nimport type { JsonRepairErrorCode } from '../types.js';\n\n/**\n * Brand used to identify errors from this package across module realms.\n *\n * A dual ESM/CJS package can be loaded twice in the same process (once through\n * `import`, once through `require`), which gives two distinct class objects and\n * makes `instanceof` unreliable. `Symbol.for` uses the cross-realm global\n * registry, so the brand stays identical for every copy.\n */\nconst ERROR_BRAND: unique symbol = Symbol.for('json-repair.error') as never;\n\n/** Number of characters of context shown on either side of the failure point. */\nconst SNIPPET_RADIUS = 24;\n\n/** Extra fields accepted when constructing a {@link JsonRepairError}. */\nexport interface JsonRepairErrorDetails {\n /** Zero-based offset into the original input, in UTF-16 code units. */\n position?: number;\n /** One-based line number in the original input. */\n line?: number;\n /** One-based column number in the original input. */\n column?: number;\n /** A short excerpt of the input around {@link JsonRepairErrorDetails.position}. */\n snippet?: string;\n}\n\n/**\n * The only error type thrown by this package.\n *\n * Every failure carries a stable {@link JsonRepairError.code} so callers can\n * branch on the reason without matching on message text, which is not part of\n * the public contract and may be reworded in any release.\n *\n * @example\n * ```ts\n * import { repairJson, isJsonRepairError } from '@nexkit/json-repair';\n *\n * try {\n * repairJson(input);\n * } catch (error) {\n * if (isJsonRepairError(error) && error.code === 'AMBIGUOUS_REPAIR') {\n * return repairJson(input, { mode: 'aggressive' });\n * }\n * throw error;\n * }\n * ```\n */\nexport class JsonRepairError extends Error {\n /** Always `'JsonRepairError'`, so the name survives minification. */\n override readonly name = 'JsonRepairError';\n\n /** Stable, machine-readable failure reason. */\n readonly code: JsonRepairErrorCode;\n\n /** Zero-based offset into the original input, in UTF-16 code units. */\n readonly position: number | undefined;\n\n /** One-based line number in the original input. */\n readonly line: number | undefined;\n\n /** One-based column number in the original input. */\n readonly column: number | undefined;\n\n /** A short excerpt of the input around {@link JsonRepairError.position}. */\n readonly snippet: string | undefined;\n\n /** Cross-realm brand; see {@link isJsonRepairError}. */\n readonly [ERROR_BRAND] = true;\n\n constructor(code: JsonRepairErrorCode, message: string, details: JsonRepairErrorDetails = {}) {\n super(message);\n this.code = code;\n this.position = details.position;\n this.line = details.line;\n this.column = details.column;\n this.snippet = details.snippet;\n\n // Restores the prototype chain when the package is consumed as downlevelled\n // ES5, where `super()` would otherwise return a plain Error.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Reports whether a value is a {@link JsonRepairError}, including instances\n * created by a different copy of this package.\n *\n * Prefer this over `instanceof` — see {@link ERROR_BRAND}.\n */\n static isJsonRepairError(value: unknown): value is JsonRepairError {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[ERROR_BRAND] === true\n );\n }\n}\n\n/**\n * Reports whether a value is a {@link JsonRepairError}, including instances\n * created by a different copy of this package (dual ESM/CJS loading).\n */\nexport function isJsonRepairError(value: unknown): value is JsonRepairError {\n return JsonRepairError.isJsonRepairError(value);\n}\n\n/**\n * Builds a fully located error from a raw source string.\n *\n * Callers that hold a {@link Scanner} already have a line index and should use\n * it. This helper exists for the stages that run outside the parser — limit\n * checks and the orchestration layer — so that every error the package throws\n * carries the same position, line, column and snippet fields.\n */\nexport function createError(\n code: JsonRepairErrorCode,\n message: string,\n source: string,\n position: number,\n): JsonRepairError {\n const clamped = position < 0 ? 0 : position > source.length ? source.length : position;\n const { line, column } = new Scanner(source).positionAt(clamped);\n\n return new JsonRepairError(code, message, {\n position: clamped,\n line,\n column,\n snippet: buildSnippet(source, clamped),\n });\n}\n\n/**\n * Builds a single-line excerpt of `source` around `position`, with control\n * characters escaped and ellipses marking truncation.\n */\nexport function buildSnippet(source: string, position: number): string {\n const clamped = position < 0 ? 0 : position > source.length ? source.length : position;\n const start = clamped - SNIPPET_RADIUS < 0 ? 0 : clamped - SNIPPET_RADIUS;\n const end = clamped + SNIPPET_RADIUS > source.length ? source.length : clamped + SNIPPET_RADIUS;\n\n let excerpt = '';\n for (let index = start; index < end; index += 1) {\n excerpt += escapeForDisplay(source.charCodeAt(index));\n }\n\n return `${start > 0 ? '…' : ''}${excerpt}${end < source.length ? '…' : ''}`;\n}\n\n/** Renders one code unit safely for a single-line diagnostic message. */\nfunction escapeForDisplay(code: number): string {\n switch (code) {\n case 0x08:\n return '\\\\b';\n case 0x09:\n return '\\\\t';\n case 0x0a:\n return '\\\\n';\n case 0x0c:\n return '\\\\f';\n case 0x0d:\n return '\\\\r';\n default:\n break;\n }\n if (code < 0x20 || code === 0x7f) {\n return `\\\\u${code.toString(16).padStart(4, '0')}`;\n }\n return String.fromCharCode(code);\n}\n","import { createError, JsonRepairError } from './errors/JsonRepairError.js';\nimport {\n CH_BACKSLASH,\n CH_CLOSE_BRACE,\n CH_CLOSE_BRACKET,\n CH_DOUBLE_QUOTE,\n CH_OPEN_BRACE,\n CH_OPEN_BRACKET,\n} from './scanner/tokens.js';\n\n/**\n * Rejects an input that is not a string.\n *\n * This runs before anything touches the value, so a caller who accidentally\n * passes an already-parsed object or a `Buffer` gets a named error rather than\n * a confusing failure deep inside the scanner.\n *\n * @throws {JsonRepairError} `INVALID_INPUT`\n */\nexport function assertString(input: unknown, parameter: string): asserts input is string {\n if (typeof input !== 'string') {\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Parameter \"${parameter}\" must be a string, received ${input === null ? 'null' : typeof input}.`,\n );\n }\n}\n\n/**\n * Rejects an input longer than the configured budget.\n *\n * The check happens before any scanning, so an oversized payload costs one\n * property read rather than a full pass.\n *\n * @throws {JsonRepairError} `MAX_LENGTH_EXCEEDED`\n */\nexport function assertInputLength(input: string, maxLength: number): void {\n if (input.length > maxLength) {\n throw new JsonRepairError(\n 'MAX_LENGTH_EXCEEDED',\n `Input is ${input.length} characters, which exceeds the maximum of ${maxLength}.`,\n { position: maxLength },\n );\n }\n}\n\n/**\n * Enforces `maxDepth` on text that `JSON.parse` has already accepted.\n *\n * The repairing parser tracks depth as it descends, but the fast path never\n * enters the parser, so valid input needs its own check or `maxDepth` would be\n * silently unenforced for exactly the documents most likely to be deep.\n *\n * Because the text is known-valid JSON, string boundaries are unambiguous: a\n * quote is either the delimiter or escaped, with no repair cases to consider.\n * That makes a single linear pass exact.\n *\n * @throws {JsonRepairError} `MAX_DEPTH_EXCEEDED`\n */\nexport function assertStructuralDepth(\n source: string,\n start: number,\n end: number,\n maxDepth: number,\n): void {\n let depth = 0;\n let index = start;\n\n while (index < end) {\n const code = source.charCodeAt(index);\n\n if (code === CH_DOUBLE_QUOTE) {\n index = skipValidString(source, index + 1, end);\n continue;\n }\n\n if (code === CH_OPEN_BRACE || code === CH_OPEN_BRACKET) {\n depth += 1;\n if (depth > maxDepth) {\n throw createError(\n 'MAX_DEPTH_EXCEEDED',\n `Nesting depth exceeds the maximum of ${maxDepth}.`,\n source,\n index,\n );\n }\n } else if (code === CH_CLOSE_BRACE || code === CH_CLOSE_BRACKET) {\n depth -= 1;\n }\n\n index += 1;\n }\n}\n\n/**\n * Returns the offset one past the closing quote of a string whose opening quote\n * has already been consumed. Only valid on text `JSON.parse` has accepted.\n */\nfunction skipValidString(source: string, from: number, end: number): number {\n let index = from;\n\n while (index < end) {\n const code = source.charCodeAt(index);\n if (code === CH_BACKSLASH) {\n index += 2;\n continue;\n }\n if (code === CH_DOUBLE_QUOTE) {\n return index + 1;\n }\n index += 1;\n }\n\n return end;\n}\n","/**\n * References to the built-ins the engine depends on, captured when the module\n * is first evaluated.\n *\n * A repair library is often loaded into pages that also load third-party code,\n * and `JSON.parse` is a popular monkey-patching target. Holding the original\n * function means a later reassignment cannot change how this package validates\n * its own output, which is what the determinism guarantee rests on.\n */\nexport const parseJsonStrict: (text: string) => unknown = JSON.parse;\n","/**\n * Public type contracts for `@nexkit/json-repair`.\n *\n * These shapes are frozen for the 1.x line: fields may be added, never removed\n * or narrowed. New {@link RepairType} members may appear in minor releases, so\n * consumers should not write exhaustive `switch` statements over them.\n */\n\n/**\n * How much interpretation the repair engine is allowed to apply.\n *\n * - `safe` (default) applies only repairs with a single plausible reading and\n * never invents data. Anything ambiguous fails with `AMBIGUOUS_REPAIR`.\n * - `aggressive` additionally applies heuristics that guess intent, such as\n * quoting bare values or dropping trailing garbage. Aggressive mode always\n * tries `safe` first, so whenever `safe` succeeds both modes agree byte for\n * byte.\n */\nexport type RepairMode = 'safe' | 'aggressive';\n\n/**\n * The kind of change the repair engine made. Every operation reported in\n * {@link RepairResult.repairs} carries one of these.\n *\n * Repairs that discard input have deliberately distinct types\n * (`removed-*`, `terminated-string-at-newline`) so that callers can audit\n * whether any content was lost.\n */\nexport type RepairType =\n /** A leading U+FEFF byte order mark was removed. */\n | 'removed-byte-order-mark'\n /** JSON was isolated from Markdown fences or surrounding prose. */\n | 'extracted-json'\n /** A `//`, block or `#` comment was removed. */\n | 'removed-comment'\n /** Whitespace JSON does not allow between tokens, such as a non-breaking space, was dropped. */\n | 'normalized-whitespace'\n /** A comma directly before `}` or `]` was removed. */\n | 'removed-trailing-comma'\n /** A repeated or leading comma inside an object was removed. */\n | 'removed-extra-comma'\n /** A closing bracket that matched no open container was discarded. */\n | 'removed-stray-token'\n /** Content after the top-level value was discarded. */\n | 'removed-trailing-content'\n /** A truncated final key or member was discarded (streamed output). */\n | 'removed-incomplete-member'\n /** A missing separator between members or elements was inserted. */\n | 'added-missing-comma'\n /** A missing `:` between a key and its value was inserted. */\n | 'added-missing-colon'\n /** An absent or elided value was replaced by `null`. */\n | 'added-missing-value'\n /** An unclosed object was closed. */\n | 'added-closing-brace'\n /** An unclosed array was closed. */\n | 'added-closing-bracket'\n /** Single, backtick or typographic quotes were converted to `\"`. */\n | 'normalized-quotes'\n /** A non-JSON literal was mapped to JSON (`True`, `None`, `NaN`). */\n | 'normalized-literal'\n /** A number literal was rewritten to valid JSON grammar (`+1`, `.5`, `0x1F`). */\n | 'normalized-number'\n /** A bare object key was quoted. */\n | 'quoted-key'\n /** A bare value was quoted as a string. */\n | 'quoted-value'\n /** A raw control character, inner quote or lone surrogate was escaped. */\n | 'escaped-character'\n /** An invalid escape sequence was corrected. */\n | 'fixed-escape'\n /** A string left open at end of input was closed. Lossless. */\n | 'terminated-string-at-eof'\n /** A string left open was closed at a line break. **Discards** the text after that line break. */\n | 'terminated-string-at-newline';\n\n/** Every {@link RepairType}, in a stable order. Useful for exhaustive UIs and tests. */\nexport const REPAIR_TYPES = [\n 'removed-byte-order-mark',\n 'extracted-json',\n 'removed-comment',\n 'normalized-whitespace',\n 'removed-trailing-comma',\n 'removed-extra-comma',\n 'removed-stray-token',\n 'removed-trailing-content',\n 'removed-incomplete-member',\n 'added-missing-comma',\n 'added-missing-colon',\n 'added-missing-value',\n 'added-closing-brace',\n 'added-closing-bracket',\n 'normalized-quotes',\n 'normalized-literal',\n 'normalized-number',\n 'quoted-key',\n 'quoted-value',\n 'escaped-character',\n 'fixed-escape',\n 'terminated-string-at-eof',\n 'terminated-string-at-newline',\n] as const satisfies readonly RepairType[];\n\n/**\n * A single change applied to the input.\n *\n * Positions locate the change in the **original** input string — they stay\n * absolute even when the JSON was extracted from a larger document, and they\n * include a leading byte order mark if one was present.\n */\nexport interface RepairOperation {\n /** What kind of change was made. */\n type: RepairType;\n /** Zero-based offset into the original input, in UTF-16 code units. */\n position?: number;\n /** One-based line number in the original input. */\n line?: number;\n /** One-based column number in the original input, in UTF-16 code units. */\n column?: number;\n /** Human-readable description, used by the CLI's `--explain` output. */\n message?: string;\n}\n\n/** Result of {@link repairJson} when `returnMetadata: true` is set. */\nexport interface RepairResult {\n /** Repaired JSON text. Guaranteed to be accepted by `JSON.parse`. */\n json: string;\n /** `true` when {@link RepairResult.json} differs from the input. */\n changed: boolean;\n /** Ordered list of the changes that were applied, ascending by position. */\n repairs: RepairOperation[];\n}\n\n/**\n * Options accepted by {@link repairJson} and {@link parseJson}.\n *\n * The boolean flags are tri-state: leaving one `undefined` uses the default for\n * the selected {@link RepairMode}, while an explicit `true` or `false` always\n * wins. Passing `false` therefore *disables* a repair — it does not mean\n * \"use the default\".\n */\nexport interface RepairOptions {\n /**\n * Repair strategy. Defaults to `'safe'`.\n * @see RepairMode\n */\n mode?: RepairMode;\n /**\n * Isolate JSON from Markdown code fences and surrounding prose before\n * repairing. Defaults to `true`.\n */\n extract?: boolean;\n /**\n * Accept and strip line comments, block comments and `#` comments.\n * Defaults to `true`.\n * When `false`, a comment is a syntax error rather than trivia.\n */\n allowComments?: boolean;\n /** Accept single-quoted strings. Defaults to `true`. */\n allowSingleQuotes?: boolean;\n /** Accept and quote bare object keys. Defaults to `true`. */\n allowUnquotedKeys?: boolean;\n /** Remove commas that directly precede `}` or `]`. Defaults to `true`. */\n fixTrailingCommas?: boolean;\n /** Close containers that were never closed. Defaults to `true`. */\n fixMissingBrackets?: boolean;\n /**\n * Maximum accepted input length, in UTF-16 code units (not bytes).\n * Defaults to `10_000_000`. Exceeding it throws `MAX_LENGTH_EXCEEDED`.\n */\n maxLength?: number;\n /**\n * Maximum accepted nesting depth. Defaults to `512`, and may not exceed\n * {@link MAX_SUPPORTED_DEPTH}. Exceeding it throws `MAX_DEPTH_EXCEEDED`,\n * which also keeps the parser clear of host stack limits.\n */\n maxDepth?: number;\n /**\n * Maximum number of repair operations per attempt. Defaults to `Infinity`;\n * the engine is single pass, so it terminates regardless of this value.\n */\n maxRepairs?: number;\n /** Return a {@link RepairResult} instead of a plain string. Defaults to `false`. */\n returnMetadata?: boolean;\n}\n\n/** Options accepted by {@link extractJson} and {@link extractAllJson}. */\nexport interface ExtractOptions extends Pick<\n RepairOptions,\n | 'mode'\n | 'allowComments'\n | 'allowSingleQuotes'\n | 'allowUnquotedKeys'\n | 'fixTrailingCommas'\n | 'fixMissingBrackets'\n | 'maxLength'\n | 'maxDepth'\n | 'maxRepairs'\n> {\n /**\n * Which candidate {@link extractJson} returns when the document contains\n * several JSON blocks. Defaults to `'best'`, matching what\n * {@link repairJson} picks.\n *\n * - `best` — fewest repairs, then longest, then earliest. Prose decoys such\n * as the `[1]` in \"see [1] for details\" lose to a real payload beside them.\n * - `first` — the earliest repairable candidate, in document order.\n * - `last` — the last repairable candidate, in document order.\n * - `largest` — the longest repairable candidate; ties resolve to the earliest.\n */\n select?: 'best' | 'first' | 'last' | 'largest';\n}\n\n/** Machine-readable reason a repair failed. */\nexport type JsonRepairErrorCode =\n /** Input was not a string, was empty/whitespace-only, or an option was invalid. */\n | 'INVALID_INPUT'\n /** No repairable JSON value could be located in the input. */\n | 'NO_JSON_FOUND'\n /** No safe repair sequence exists for this input. */\n | 'UNREPAIRABLE_JSON'\n /** Input exceeded `maxLength`. */\n | 'MAX_LENGTH_EXCEEDED'\n /** Nesting exceeded `maxDepth`. */\n | 'MAX_DEPTH_EXCEEDED'\n /** More repairs were required than `maxRepairs` allows. */\n | 'MAX_REPAIRS_EXCEEDED'\n /** Several readings are possible and `safe` mode refuses to choose. */\n | 'AMBIGUOUS_REPAIR';\n\n/**\n * Hard ceiling for {@link RepairOptions.maxDepth}. Requesting more throws\n * `INVALID_INPUT`. The cap keeps the recursive parser well clear of host stack\n * limits on every supported runtime, so deep input always produces a\n * `MAX_DEPTH_EXCEEDED` error rather than a stack overflow.\n */\nexport const MAX_SUPPORTED_DEPTH = 1024;\n","import { JsonRepairError } from './errors/JsonRepairError.js';\nimport {\n MAX_SUPPORTED_DEPTH,\n type ExtractOptions,\n type RepairMode,\n type RepairOptions,\n} from './types.js';\n\n/** Default maximum input length, in UTF-16 code units. */\nexport const DEFAULT_MAX_LENGTH = 10_000_000;\n\n/** Default maximum nesting depth. */\nexport const DEFAULT_MAX_DEPTH = 512;\n\n/**\n * Fully resolved options. Every field is concrete, so the engine never has to\n * re-derive a default or consult the mode for a flag.\n */\nexport interface ResolvedOptions {\n mode: RepairMode;\n /** Convenience mirror of `mode === 'aggressive'`, read on hot paths. */\n aggressive: boolean;\n extract: boolean;\n allowComments: boolean;\n allowSingleQuotes: boolean;\n allowUnquotedKeys: boolean;\n fixTrailingCommas: boolean;\n fixMissingBrackets: boolean;\n maxLength: number;\n maxDepth: number;\n maxRepairs: number;\n returnMetadata: boolean;\n}\n\n/** Which candidate {@link extractJson} returns from a multi-block document. */\nexport type SelectStrategy = NonNullable<ExtractOptions['select']>;\n\n/**\n * Validates and resolves user options.\n *\n * The boolean flags are tri-state on purpose. `undefined` means \"use the\n * default for this mode\"; an explicit `true` or `false` always wins, so\n * `{ mode: 'aggressive', allowComments: false }` really does reject comments.\n * All six flags currently default to `true` in both modes — the difference\n * between modes lies in the repairs that have no flag of their own.\n *\n * @throws {JsonRepairError} `INVALID_INPUT` when any option is out of range.\n */\nexport function resolveOptions(options: RepairOptions | undefined): ResolvedOptions {\n const source = asOptionBag(options);\n const mode = resolveMode(source.mode);\n\n return {\n mode,\n aggressive: mode === 'aggressive',\n extract: resolveFlag(source.extract, 'extract', true),\n allowComments: resolveFlag(source.allowComments, 'allowComments', true),\n allowSingleQuotes: resolveFlag(source.allowSingleQuotes, 'allowSingleQuotes', true),\n allowUnquotedKeys: resolveFlag(source.allowUnquotedKeys, 'allowUnquotedKeys', true),\n fixTrailingCommas: resolveFlag(source.fixTrailingCommas, 'fixTrailingCommas', true),\n fixMissingBrackets: resolveFlag(source.fixMissingBrackets, 'fixMissingBrackets', true),\n maxLength: resolveLimit(source.maxLength, 'maxLength', DEFAULT_MAX_LENGTH, 1, Infinity),\n maxDepth: resolveLimit(source.maxDepth, 'maxDepth', DEFAULT_MAX_DEPTH, 1, MAX_SUPPORTED_DEPTH),\n maxRepairs: resolveLimit(source.maxRepairs, 'maxRepairs', Infinity, 0, Infinity),\n returnMetadata: resolveFlag(source.returnMetadata, 'returnMetadata', false),\n };\n}\n\n/**\n * Views the caller's options as a bag of unknown values.\n *\n * Every field is then validated as `unknown` rather than as its declared type,\n * because the declared type is only a promise: JavaScript callers, and\n * TypeScript callers who have cast, can pass anything at all. Validating what\n * actually arrived is what turns a mistake into a named `INVALID_INPUT` error\n * instead of undefined behaviour deep in the parser.\n *\n * @throws {JsonRepairError} `INVALID_INPUT`\n */\nfunction asOptionBag(options: unknown): Record<string, unknown> {\n if (options === undefined) {\n return {};\n }\n if (typeof options !== 'object' || options === null) {\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Options must be an object, received ${describe(options)}.`,\n );\n }\n return options as Record<string, unknown>;\n}\n\n/**\n * Resolves options for {@link extractJson} and {@link extractAllJson}.\n *\n * Extraction is the whole point of these entry points, so `extract` is forced\n * on and is not exposed as an option.\n */\nexport function resolveExtractOptions(\n options: ExtractOptions | undefined,\n): ResolvedOptions & { select: SelectStrategy } {\n const source = asOptionBag(options);\n const select = resolveSelect(source.select);\n\n return { ...resolveOptions({ ...source, extract: true }), select };\n}\n\nfunction resolveSelect(select: unknown): SelectStrategy {\n if (select === undefined) {\n return 'best';\n }\n if (select !== 'best' && select !== 'first' && select !== 'last' && select !== 'largest') {\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Option \"select\" must be \"best\", \"first\", \"last\" or \"largest\", received ${describe(select)}.`,\n );\n }\n return select;\n}\n\n/** Returns a copy of `options` running in `mode`. */\nexport function withMode(options: ResolvedOptions, mode: RepairMode): ResolvedOptions {\n return { ...options, mode, aggressive: mode === 'aggressive' };\n}\n\nfunction resolveMode(mode: unknown): RepairMode {\n if (mode === undefined) {\n return 'safe';\n }\n if (mode !== 'safe' && mode !== 'aggressive') {\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Option \"mode\" must be \"safe\" or \"aggressive\", received ${describe(mode)}.`,\n );\n }\n return mode;\n}\n\nfunction resolveFlag(value: unknown, name: string, fallback: boolean): boolean {\n if (value === undefined) {\n return fallback;\n }\n if (typeof value !== 'boolean') {\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Option \"${name}\" must be a boolean, received ${describe(value)}.`,\n );\n }\n return value;\n}\n\nfunction resolveLimit(\n value: unknown,\n name: string,\n fallback: number,\n min: number,\n max: number,\n): number {\n if (value === undefined) {\n return fallback;\n }\n if (typeof value !== 'number' || Number.isNaN(value)) {\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Option \"${name}\" must be a number, received ${describe(value)}.`,\n );\n }\n if (value !== Infinity && !Number.isInteger(value)) {\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Option \"${name}\" must be an integer or Infinity, received ${value}.`,\n );\n }\n if (value < min || value > max) {\n const ceiling = max === Infinity ? 'Infinity' : String(max);\n throw new JsonRepairError(\n 'INVALID_INPUT',\n `Option \"${name}\" must be between ${min} and ${ceiling}, received ${value}.`,\n );\n }\n return value;\n}\n\n/** Renders an untrusted value for an error message without ever calling into it. */\nfunction describe(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n switch (typeof value) {\n case 'string':\n return JSON.stringify(value);\n case 'number':\n case 'boolean':\n case 'undefined':\n return String(value);\n case 'bigint':\n return `${String(value)}n`;\n default:\n return typeof value;\n }\n}\n","import type { RepairContext } from '../parser/state.js';\nimport { CH_CLOSE_BRACE } from '../scanner/tokens.js';\n\n/** Which container the parser is inside. */\nexport type ContainerKind = 'object' | 'array';\n\n/**\n * Records the implicit closing of a container that the input never closed.\n *\n * Truncated output — a cut-off stream, a response that hit a token limit — is\n * the usual cause, and there is only one way to close the containers that are\n * still open, so this is a safe repair. Callers that set\n * `fixMissingBrackets: false` get a hard failure instead.\n */\nexport function closeUnterminated(ctx: RepairContext, kind: ContainerKind, position: number): void {\n if (!ctx.options.fixMissingBrackets) {\n ctx.fail(kind === 'object' ? 'Object is never closed' : 'Array is never closed', position);\n }\n ctx.record(kind === 'object' ? 'added-closing-brace' : 'added-closing-bracket', position);\n}\n\n/**\n * Consumes a closing bracket that matches no open container.\n *\n * At the very end of the input a stray closer is almost always a typo for the\n * right one — `{\"a\":1]` can only have meant `{\"a\":1}` — so it is dropped\n * safely and the correct closer is added by {@link closeUnterminated}.\n * Anywhere else the bracket may be marking a real structural boundary, so only\n * aggressive mode discards it.\n */\nexport function dropStrayCloser(ctx: RepairContext): void {\n const position = ctx.scanner.index;\n const atEnd = position === ctx.lastContentIndex;\n\n if (!atEnd && !ctx.options.aggressive) {\n const character = ctx.scanner.peek() === CH_CLOSE_BRACE ? '}' : ']';\n ctx.refuse(`Unexpected \"${character}\" with no matching opening bracket`, position);\n }\n\n ctx.record('removed-stray-token', position);\n ctx.scanner.index = position + 1;\n}\n","import type { RepairContext } from '../parser/state.js';\nimport {\n CH_ASTERISK,\n CH_HASH,\n CH_SLASH,\n isJsonWhitespace,\n isLineBreak,\n isWhitespace,\n} from '../scanner/tokens.js';\n\n/**\n * Advances past whitespace and comments, recording each comment removed.\n *\n * Three comment syntaxes are accepted, all controlled by\n * `RepairOptions.allowComments`: `//` and `#` run to the end of the line, while\n * a C-style block comment runs to its terminator or, if it was never closed, to\n * the end of the input. Comments are trivia, so removing one never merges the tokens\n * around it — the parser reads the tokens separately and inserts any separator\n * that turns out to be missing.\n */\nexport function skipTrivia(ctx: RepairContext): void {\n const { scanner } = ctx;\n const { source, end } = scanner;\n const allowComments = ctx.options.allowComments;\n\n let index = scanner.index;\n\n for (;;) {\n // One record per run of whitespace, not per character, so a paste full of\n // non-breaking spaces cannot inflate the repair log out of proportion.\n let exotic = -1;\n while (index < end) {\n const code = source.charCodeAt(index);\n if (!isWhitespace(code)) {\n break;\n }\n if (exotic < 0 && !isJsonWhitespace(code)) {\n exotic = index;\n }\n index += 1;\n }\n\n if (exotic >= 0) {\n scanner.index = index;\n ctx.record('normalized-whitespace', exotic);\n }\n\n if (index >= end || !allowComments) {\n break;\n }\n\n const commentStart = index;\n const code = source.charCodeAt(index);\n\n if (code === CH_HASH) {\n index = skipToLineEnd(source, index + 1, end);\n } else if (code === CH_SLASH && index + 1 < end) {\n const nextCode = source.charCodeAt(index + 1);\n if (nextCode === CH_SLASH) {\n index = skipToLineEnd(source, index + 2, end);\n } else if (nextCode === CH_ASTERISK) {\n index = skipBlockComment(source, index + 2, end);\n } else {\n break;\n }\n } else {\n break;\n }\n\n scanner.index = index;\n ctx.record('removed-comment', commentStart);\n }\n\n scanner.index = index;\n}\n\n/**\n * Returns the offset after the whitespace and comments starting at `from`,\n * without recording anything.\n *\n * Used by the string-continuation probe, which must look past trivia while\n * remaining free of side effects — it may decide the lookahead was wrong.\n */\nexport function scanTrivia(\n source: string,\n from: number,\n end: number,\n allowComments: boolean,\n): number {\n let index = from;\n\n for (;;) {\n while (index < end && isWhitespace(source.charCodeAt(index))) {\n index += 1;\n }\n\n if (index >= end || !allowComments) {\n return index;\n }\n\n const code = source.charCodeAt(index);\n\n if (code === CH_HASH) {\n index = skipToLineEnd(source, index + 1, end);\n } else if (code === CH_SLASH && index + 1 < end) {\n const nextCode = source.charCodeAt(index + 1);\n if (nextCode === CH_SLASH) {\n index = skipToLineEnd(source, index + 2, end);\n } else if (nextCode === CH_ASTERISK) {\n index = skipBlockComment(source, index + 2, end);\n } else {\n return index;\n }\n } else {\n return index;\n }\n }\n}\n\nfunction skipToLineEnd(source: string, from: number, end: number): number {\n let index = from;\n while (index < end && !isLineBreak(source.charCodeAt(index))) {\n index += 1;\n }\n return index;\n}\n\nfunction skipBlockComment(source: string, from: number, end: number): number {\n let index = from;\n while (index < end) {\n if (\n source.charCodeAt(index) === CH_ASTERISK &&\n index + 1 < end &&\n source.charCodeAt(index + 1) === CH_SLASH\n ) {\n return index + 2;\n }\n index += 1;\n }\n // Unterminated block comment: everything to the end of the input is comment.\n return end;\n}\n","import type { RepairContext } from '../parser/state.js';\nimport { toLowerAscii } from '../scanner/tokens.js';\n\n/** What {@link readLiteral} was able to do with a bare token. */\nexport type LiteralOutcome =\n /** The token was written to the output as a JSON literal. */\n | 'emitted'\n /** A reading exists, but only `mode: 'aggressive'` is willing to commit to it. */\n | 'needs-aggressive'\n /** The token is not a literal in any mode. */\n | 'not-a-literal';\n\n/** How faithfully a non-JSON spelling of \"no value\" becomes `null`. */\ntype NullishKind =\n /** `None` — the same value under another language's spelling. */\n | 'equivalent'\n /** `NaN`, `Infinity`, `undefined` — `null` is the nearest JSON has, not the same value. */\n | 'lossy';\n\n/**\n * Tries to emit the bare token spanning `[start, end)` as `true`, `false` or\n * `null`.\n *\n * Case variants of the three JSON literals are safe: `True` and `NULL` have no\n * second reading in a value position. `None` is safe for the same reason. It is\n * Python's spelling of `null` and nothing is lost in rewriting it, and the only\n * competing reading — the string `\"None\"` — requires unquoted string values,\n * which safe mode does not perform in the first place. Refusing `None` while\n * accepting `True` would also split the one Python dict repr that LLM output\n * produces constantly down the middle.\n *\n * `NaN`, `Infinity` and `undefined` stay aggressive-only, because for them\n * `null` is a lossy answer rather than a translation: the first two discard a\n * number the author did write, and `JSON.stringify` drops an `undefined` object\n * member entirely instead of nulling it, so two defensible readings exist.\n */\nexport function readLiteral(ctx: RepairContext, start: number, end: number): LiteralOutcome {\n const { source } = ctx.scanner;\n const length = end - start;\n\n if (length < 3 || length > 9) {\n return 'not-a-literal';\n }\n\n const canonical = matchJsonLiteral(source, start, end, length);\n if (canonical !== undefined) {\n if (matchesExactly(source, start, canonical)) {\n ctx.writeSpan(start, end);\n } else {\n ctx.write(canonical);\n ctx.record('normalized-literal', start, `Rewrote a literal as ${canonical}`);\n }\n return 'emitted';\n }\n\n const nullish = matchNullish(source, start, end, length);\n if (nullish === undefined) {\n return 'not-a-literal';\n }\n if (nullish === 'lossy' && !ctx.options.aggressive) {\n return 'needs-aggressive';\n }\n\n ctx.write('null');\n ctx.record('normalized-literal', start, 'Rewrote a non-JSON literal as null');\n return 'emitted';\n}\n\n/** Returns the canonical JSON literal a token spells in any case, if any. */\nfunction matchJsonLiteral(\n source: string,\n start: number,\n end: number,\n length: number,\n): string | undefined {\n if (length === 4) {\n if (matchesWord(source, start, end, 'true')) {\n return 'true';\n }\n if (matchesWord(source, start, end, 'null')) {\n return 'null';\n }\n return undefined;\n }\n if (length === 5 && matchesWord(source, start, end, 'false')) {\n return 'false';\n }\n return undefined;\n}\n\n/**\n * Classifies a token as one of the non-JSON spellings of \"no value\".\n *\n * @returns how faithfully the token maps to `null`, or `undefined` when it is\n * not one of these spellings at all.\n */\nfunction matchNullish(\n source: string,\n start: number,\n end: number,\n length: number,\n): NullishKind | undefined {\n switch (length) {\n case 3:\n return matchesWord(source, start, end, 'nan') ? 'lossy' : undefined;\n case 4:\n return matchesWord(source, start, end, 'none') ? 'equivalent' : undefined;\n case 8:\n return matchesWord(source, start, end, 'infinity') ? 'lossy' : undefined;\n case 9:\n return matchesWord(source, start, end, 'undefined') ||\n matchesWord(source, start, end, '-infinity')\n ? 'lossy'\n : undefined;\n default:\n return undefined;\n }\n}\n\n/**\n * Compares a span against a lower-case ASCII word, ignoring case.\n *\n * Uses code-unit arithmetic rather than `toLowerCase`, whose result depends on\n * the host locale — under a Turkish locale `\"NULL\".toLowerCase()` yields `null`\n * but `\"I\".toLowerCase()` yields `ı`, and the package guarantees identical\n * output on every machine.\n */\nfunction matchesWord(source: string, start: number, end: number, word: string): boolean {\n if (end - start !== word.length) {\n return false;\n }\n for (let offset = 0; offset < word.length; offset += 1) {\n if (toLowerAscii(source.charCodeAt(start + offset)) !== word.charCodeAt(offset)) {\n return false;\n }\n }\n return true;\n}\n\n/** Reports whether a span is already exactly `word`. */\nfunction matchesExactly(source: string, start: number, word: string): boolean {\n for (let offset = 0; offset < word.length; offset += 1) {\n if (source.charCodeAt(start + offset) !== word.charCodeAt(offset)) {\n return false;\n }\n }\n return true;\n}\n","import type { RepairContext } from '../parser/state.js';\nimport {\n CH_DOT,\n CH_LOWER_E,\n CH_LOWER_X,\n CH_MINUS,\n CH_PLUS,\n CH_UNDERSCORE,\n CH_UPPER_E,\n CH_UPPER_X,\n CH_ZERO,\n isDigit,\n isHexDigit,\n} from '../scanner/tokens.js';\n\n/**\n * Tries to emit the token spanning `[start, end)` as a JSON number.\n *\n * Returns `false` when the token is not a number under the active mode, leaving\n * the output untouched so the caller can fall back to quoting it or refusing.\n *\n * Numbers are never round-tripped through `Number`: doing so would rewrite\n * `1.0` as `1`, turn `1e999` into `Infinity` and quietly lose precision beyond\n * 2^53. The token's own digits are reused verbatim, and repairs are limited to\n * the smallest edit that makes the JSON grammar accept them.\n */\nexport function readNumber(ctx: RepairContext, start: number, end: number): boolean {\n const { source } = ctx.scanner;\n\n if (isValidJsonNumber(source, start, end)) {\n ctx.writeSpan(start, end);\n return true;\n }\n\n const aggressive = ctx.options.aggressive;\n let index = start;\n let sign = '';\n let normalized = false;\n\n const first = source.charCodeAt(index);\n if (first === CH_PLUS) {\n // JSON has no unary plus, but `+1` has exactly one reading.\n index += 1;\n normalized = true;\n } else if (first === CH_MINUS) {\n sign = '-';\n index += 1;\n }\n\n if (aggressive && isHexPrefix(source, index, end)) {\n return readHex(ctx, start, index, end, sign);\n }\n\n let usedUnderscore = false;\n let integerDigits = '';\n while (index < end) {\n const code = source.charCodeAt(index);\n if (isDigit(code)) {\n integerDigits += source.charAt(index);\n } else if (code === CH_UNDERSCORE) {\n usedUnderscore = true;\n } else {\n break;\n }\n index += 1;\n }\n\n let fractionDigits = '';\n let sawDot = false;\n if (index < end && source.charCodeAt(index) === CH_DOT) {\n sawDot = true;\n index += 1;\n while (index < end) {\n const code = source.charCodeAt(index);\n if (isDigit(code)) {\n fractionDigits += source.charAt(index);\n } else if (code === CH_UNDERSCORE) {\n usedUnderscore = true;\n } else {\n break;\n }\n index += 1;\n }\n }\n\n let exponent = '';\n if (index < end) {\n const code = source.charCodeAt(index);\n if (code === CH_LOWER_E || code === CH_UPPER_E) {\n let cursor = index + 1;\n let exponentSign = '';\n if (cursor < end) {\n const signCode = source.charCodeAt(cursor);\n if (signCode === CH_PLUS || signCode === CH_MINUS) {\n exponentSign = signCode === CH_MINUS ? '-' : '';\n cursor += 1;\n }\n }\n const digitsStart = cursor;\n while (cursor < end && isDigit(source.charCodeAt(cursor))) {\n cursor += 1;\n }\n if (cursor > digitsStart) {\n exponent = `e${exponentSign}${source.slice(digitsStart, cursor)}`;\n } else {\n // `1e` and `1e+` carry no exponent; dropping it is the only reading.\n normalized = true;\n }\n index = cursor;\n }\n }\n\n // Anything left over means this was never a number: `1.2.3`, `12abc`, `--1`.\n if (index !== end || (integerDigits.length === 0 && fractionDigits.length === 0)) {\n return false;\n }\n\n if (usedUnderscore) {\n if (!aggressive) {\n return false;\n }\n normalized = true;\n }\n\n let integerPart = integerDigits;\n if (integerPart.length === 0) {\n // `.5` is unambiguous once the missing zero is supplied.\n integerPart = '0';\n normalized = true;\n } else if (integerPart.length > 1 && integerPart.charCodeAt(0) === CH_ZERO) {\n // `007` could be a padded identifier, so only aggressive mode picks a reading.\n if (!aggressive) {\n return false;\n }\n let cut = 0;\n while (cut < integerPart.length - 1 && integerPart.charCodeAt(cut) === CH_ZERO) {\n cut += 1;\n }\n integerPart = integerPart.slice(cut);\n normalized = true;\n }\n\n if (sawDot && fractionDigits.length === 0) {\n // `5.` means `5`; JSON requires a digit after the point.\n normalized = true;\n }\n\n if (!normalized) {\n return false;\n }\n\n ctx.write(sign);\n ctx.write(integerPart);\n if (fractionDigits.length > 0) {\n ctx.write('.');\n ctx.write(fractionDigits);\n }\n ctx.write(exponent);\n ctx.record('normalized-number', start);\n return true;\n}\n\n/** Reports whether `[start, end)` already matches the JSON number grammar. */\nexport function isValidJsonNumber(source: string, start: number, end: number): boolean {\n let index = start;\n if (index < end && source.charCodeAt(index) === CH_MINUS) {\n index += 1;\n }\n\n if (index >= end) {\n return false;\n }\n\n if (source.charCodeAt(index) === CH_ZERO) {\n index += 1;\n } else {\n if (!isDigit(source.charCodeAt(index))) {\n return false;\n }\n while (index < end && isDigit(source.charCodeAt(index))) {\n index += 1;\n }\n }\n\n if (index < end && source.charCodeAt(index) === CH_DOT) {\n index += 1;\n const digitsStart = index;\n while (index < end && isDigit(source.charCodeAt(index))) {\n index += 1;\n }\n if (index === digitsStart) {\n return false;\n }\n }\n\n if (index < end) {\n const code = source.charCodeAt(index);\n if (code !== CH_LOWER_E && code !== CH_UPPER_E) {\n return false;\n }\n index += 1;\n if (index < end) {\n const signCode = source.charCodeAt(index);\n if (signCode === CH_PLUS || signCode === CH_MINUS) {\n index += 1;\n }\n }\n const digitsStart = index;\n while (index < end && isDigit(source.charCodeAt(index))) {\n index += 1;\n }\n if (index === digitsStart) {\n return false;\n }\n }\n\n return index === end;\n}\n\nfunction isHexPrefix(source: string, index: number, end: number): boolean {\n if (index + 2 >= end || source.charCodeAt(index) !== CH_ZERO) {\n return false;\n }\n const marker = source.charCodeAt(index + 1);\n return marker === CH_LOWER_X || marker === CH_UPPER_X;\n}\n\n/**\n * Converts `0x…` to decimal.\n *\n * `BigInt` keeps values above 2^53 exact, which `parseInt` would not — a hex\n * hash rewritten as a lossy float would be a silent data corruption.\n */\nfunction readHex(\n ctx: RepairContext,\n start: number,\n prefixStart: number,\n end: number,\n sign: string,\n): boolean {\n const { source } = ctx.scanner;\n const digitsStart = prefixStart + 2;\n\n let index = digitsStart;\n while (index < end && isHexDigit(source.charCodeAt(index))) {\n index += 1;\n }\n if (index !== end || index === digitsStart) {\n return false;\n }\n\n const value = BigInt(source.slice(prefixStart, end));\n ctx.write(sign);\n ctx.write(value.toString());\n ctx.record('normalized-number', start);\n return true;\n}\n","import { scanTrivia } from '../repair/comments.js';\nimport {\n CH_BACKSLASH,\n CH_CLOSE_BRACE,\n CH_CLOSE_BRACKET,\n CH_COLON,\n CH_COMMA,\n CH_MINUS,\n CH_OPEN_BRACE,\n CH_OPEN_BRACKET,\n CH_PLUS,\n CH_DOT,\n closersFor,\n isDigit,\n isIdentifierPart,\n isIdentifierStart,\n isQuote,\n} from '../scanner/tokens.js';\nimport type { RepairContext } from './state.js';\n\n/**\n * Where in the grammar a string that just closed was sitting.\n *\n * `document` is the top-level value; it is probed like an array element, which\n * makes a bare word after the quote (`\"he said \"hi\" today\"`) reject the close\n * while a closing punctuation mark or end of input accepts it.\n */\nexport type Slot = 'object-key' | 'object-value' | 'array-element' | 'document';\n\n/**\n * Characters of lookahead a single probe may consume.\n *\n * Wide enough for a comma, a long key and a colon; narrow enough that a string\n * containing many quote characters cannot turn the parse quadratic. The global\n * `RepairContext.probeBudget` bounds the total across all probes as well.\n */\nconst PROBE_WINDOW = 256;\n\n/** {@link scanString}/{@link scanValueToken} hit the end of input with no terminator. */\nconst SCAN_UNTERMINATED = -1;\n\n/** {@link scanString}/{@link scanValueToken} ran past the lookahead window. */\nconst SCAN_BUDGET = -2;\n\n/**\n * Decides whether a quote character really closes the string, by checking that\n * what follows could continue the enclosing container.\n *\n * This is the heart of the inner-quote heuristic. Given `{\"a\": \"he said \"hi\",\n * ok\"}` a naive parser closes the value at `\"he said \"` and then chokes; a\n * parser that accepts any quote followed by a comma closes it at `\"hi\"` and\n * silently drops `ok`. Both are wrong. Probing asks the only question that\n * distinguishes them — *does a well-formed continuation start here?* — and the\n * answer is no in both cases, because ` ok\"` is not a key followed by a colon.\n * The string therefore runs to the final quote, and the inner ones become\n * escaped content.\n *\n * The probe is read-only and bounded: on running out of budget it accepts the\n * close, which is what a plain JSON parser would have done anyway.\n *\n * @param from Absolute offset immediately after the candidate closing quote.\n */\nexport function probeContinuation(ctx: RepairContext, from: number, slot: Slot): boolean {\n if (ctx.probeBudget <= 0) {\n return true;\n }\n\n const { source, end } = ctx.scanner;\n const window = end < from + PROBE_WINDOW ? end : from + PROBE_WINDOW;\n const allowComments = ctx.options.allowComments;\n const aggressive = ctx.options.aggressive;\n\n const index = scanTrivia(source, from, window, allowComments);\n ctx.probeBudget -= index - from + 1;\n\n // Reaching the true end of the region means the string ended the document.\n if (index >= end) {\n return true;\n }\n if (index >= window) {\n return true;\n }\n\n const code = source.charCodeAt(index);\n\n switch (slot) {\n case 'object-key':\n if (code === CH_COLON) {\n return true;\n }\n // `{\"a\", \"b\": 1}` only has a reading once missing colons may be invented.\n return aggressive && (code === CH_COMMA || code === CH_CLOSE_BRACE);\n\n case 'object-value':\n if (code === CH_CLOSE_BRACE || code === CH_CLOSE_BRACKET) {\n return true;\n }\n if (code === CH_COMMA) {\n return looksLikeMember(ctx, index + 1, window, allowComments);\n }\n // A key starting straight after the value means a comma went missing.\n if (isQuote(code) || isIdentifierStart(code)) {\n return looksLikeMember(ctx, index, window, allowComments);\n }\n return false;\n\n case 'array-element':\n case 'document':\n if (code === CH_CLOSE_BRACKET || code === CH_CLOSE_BRACE) {\n return true;\n }\n if (code === CH_COMMA) {\n return looksLikeElement(ctx, index + 1, window, allowComments);\n }\n if (isQuote(code)) {\n return looksLikeElement(ctx, index, window, allowComments);\n }\n return false;\n\n default:\n return true;\n }\n}\n\n/** Reports whether `from` plausibly starts `key :` inside an object. */\nfunction looksLikeMember(\n ctx: RepairContext,\n from: number,\n window: number,\n allowComments: boolean,\n): boolean {\n const { source, end } = ctx.scanner;\n\n const keyStart = scanTrivia(source, from, window, allowComments);\n ctx.probeBudget -= keyStart - from + 1;\n\n if (keyStart >= end || keyStart >= window) {\n return true;\n }\n\n const code = source.charCodeAt(keyStart);\n // A closing brace or another comma still leaves a well-formed member list.\n if (code === CH_CLOSE_BRACE || code === CH_COMMA) {\n return true;\n }\n\n const keyEnd = scanKey(source, keyStart, window, end);\n ctx.probeBudget -= (keyEnd < 0 ? window - keyStart : keyEnd - keyStart) + 1;\n\n if (keyEnd === SCAN_BUDGET) {\n return true;\n }\n if (keyEnd < 0) {\n return false;\n }\n\n const afterKey = scanTrivia(source, keyEnd, window, allowComments);\n if (afterKey >= end || afterKey >= window) {\n return true;\n }\n return source.charCodeAt(afterKey) === CH_COLON;\n}\n\n/** Reports whether `from` plausibly starts an array element followed by `,` or `]`. */\nfunction looksLikeElement(\n ctx: RepairContext,\n from: number,\n window: number,\n allowComments: boolean,\n): boolean {\n const { source, end } = ctx.scanner;\n\n const valueStart = scanTrivia(source, from, window, allowComments);\n ctx.probeBudget -= valueStart - from + 1;\n\n if (valueStart >= end || valueStart >= window) {\n return true;\n }\n\n const code = source.charCodeAt(valueStart);\n // A closing bracket or another comma still leaves a well-formed element list.\n if (code === CH_CLOSE_BRACKET || code === CH_COMMA) {\n return true;\n }\n\n const valueEnd = scanValueToken(source, valueStart, window, end);\n ctx.probeBudget -= (valueEnd < 0 ? window - valueStart : valueEnd - valueStart) + 1;\n\n if (valueEnd === SCAN_BUDGET) {\n return true;\n }\n if (valueEnd < 0) {\n return false;\n }\n\n const afterValue = scanTrivia(source, valueEnd, window, allowComments);\n if (afterValue >= end || afterValue >= window) {\n return true;\n }\n const next = source.charCodeAt(afterValue);\n return next === CH_COMMA || next === CH_CLOSE_BRACKET;\n}\n\n/** Returns the offset after a quoted or bare key, or a negative scan code. */\nfunction scanKey(source: string, from: number, window: number, end: number): number {\n const code = source.charCodeAt(from);\n if (isQuote(code)) {\n return scanString(source, from, window, end);\n }\n if (!isIdentifierStart(code)) {\n return SCAN_UNTERMINATED;\n }\n\n let index = from + 1;\n while (index < window && isIdentifierPart(source.charCodeAt(index))) {\n index += 1;\n }\n return index >= window && index < end ? SCAN_BUDGET : index;\n}\n\n/** Returns the offset after one value token, or a negative scan code. */\nfunction scanValueToken(source: string, from: number, window: number, end: number): number {\n const code = source.charCodeAt(from);\n\n if (isQuote(code)) {\n return scanString(source, from, window, end);\n }\n // A nested container is a value; its own contents are not this probe's problem.\n if (code === CH_OPEN_BRACE || code === CH_OPEN_BRACKET) {\n return SCAN_BUDGET;\n }\n if (!isDigit(code) && !isIdentifierStart(code) && code !== CH_MINUS && code !== CH_PLUS) {\n return SCAN_UNTERMINATED;\n }\n\n let index = from + 1;\n while (index < window) {\n const next = source.charCodeAt(index);\n if (!isIdentifierPart(next) && !isDigit(next) && next !== CH_PLUS && next !== CH_DOT) {\n break;\n }\n index += 1;\n }\n return index >= window && index < end ? SCAN_BUDGET : index;\n}\n\n/** Returns the offset after a string literal, or a negative scan code. */\nfunction scanString(source: string, from: number, window: number, end: number): number {\n const opener = source.charCodeAt(from);\n const closers = closersFor(opener);\n\n let index = from + 1;\n while (index < window) {\n const code = source.charCodeAt(index);\n if (code === CH_BACKSLASH) {\n index += 2;\n continue;\n }\n if (code === closers[0] || code === closers[1]) {\n return index + 1;\n }\n index += 1;\n }\n return index >= end ? SCAN_UNTERMINATED : SCAN_BUDGET;\n}\n","import { probeContinuation, type Slot } from '../parser/probe.js';\nimport type { Checkpoint, RepairContext } from '../parser/state.js';\nimport {\n CH_BACKSLASH,\n CH_CARRIAGE_RETURN,\n CH_CLOSE_BRACE,\n CH_CLOSE_BRACKET,\n CH_COMMA,\n CH_DOUBLE_QUOTE,\n CH_LINE_FEED,\n CH_LOWER_B,\n CH_LOWER_F,\n CH_LOWER_N,\n CH_LOWER_R,\n CH_LOWER_T,\n CH_LOWER_U,\n CH_SLASH,\n closersFor,\n isHexDigit,\n isHighSurrogate,\n isLowSurrogate,\n isQuote,\n isStandardQuote,\n isWhitespace,\n} from '../scanner/tokens.js';\n\n/* Classification of the escape sequence at a backslash. Non-negative values are\n * the length of a sequence JSON already accepts verbatim. */\nconst ESC_SHORT = 2;\nconst ESC_UNICODE = 6;\nconst ESC_DANGLING = -1; /* backslash is the last character of the input */\nconst ESC_TRUNCATED_UNICODE = -2; /* `\\u` with too few hex digits before the end */\nconst ESC_BAD_UNICODE = -3; /* `\\u` not followed by four hex digits */\nconst ESC_QUOTE = -4; /* backslash before a quote character */\nconst ESC_CONTROL = -5; /* backslash before a raw control character */\nconst ESC_UNKNOWN = -6; /* backslash before anything else */\n\n/**\n * Reads a quoted string and writes it back as a canonical JSON string.\n *\n * Handles every string-level repair in one pass:\n *\n * - non-standard delimiters (`'`, `` ` ``, `“ ”`) become `\"`,\n * - raw control characters and unpaired surrogates are escaped,\n * - invalid escape sequences are corrected without losing characters,\n * - a quote that does not actually end the string becomes escaped content,\n * - a string left open is closed, at a line break or at end of input.\n *\n * The cursor must sit on the opening quote, and is left just past the point the\n * string was found to end.\n */\nexport function readString(ctx: RepairContext, slot: Slot): void {\n const { scanner } = ctx;\n const { source, end } = scanner;\n\n const start = scanner.index;\n const opener = source.charCodeAt(start);\n const standard = isStandardQuote(opener);\n const closers = closersFor(opener);\n const closerA = closers[0];\n const closerB = closers[1];\n\n if (!standard) {\n ctx.record('normalized-quotes', start);\n }\n\n ctx.write('\"');\n\n let index = start + 1;\n let spanStart = index;\n let checkpoint: Checkpoint | undefined;\n /** End of the last reported run of control characters, so a multi-line string logs one repair per line, not per character. */\n let reportedControlEnd = -1;\n\n while (index < end) {\n const code = source.charCodeAt(index);\n\n if (code === CH_BACKSLASH) {\n const kind = classifyEscape(source, index, end);\n if (kind >= 0) {\n index += kind;\n continue;\n }\n\n ctx.writeSpan(spanStart, index);\n\n switch (kind) {\n case ESC_DANGLING:\n ctx.record('fixed-escape', index, 'Removed a trailing backslash with nothing to escape');\n index = end;\n break;\n case ESC_TRUNCATED_UNICODE:\n ctx.record('fixed-escape', index, 'Removed a truncated \\\\u escape at end of input');\n index = end;\n break;\n case ESC_BAD_UNICODE:\n ctx.write('\\\\\\\\u');\n ctx.record('fixed-escape', index, 'Escaped an incomplete \\\\u sequence');\n index += 2;\n break;\n case ESC_QUOTE: {\n // `'it\\'s'` and friends: the backslash belonged to the source dialect.\n const quoted = source.charCodeAt(index + 1);\n ctx.write(quoted === CH_DOUBLE_QUOTE ? '\\\\\"' : source[index + 1]!);\n ctx.record('fixed-escape', index, 'Unescaped a quote that JSON does not escape');\n index += 2;\n break;\n }\n case ESC_CONTROL:\n ctx.write(escapeControl(source.charCodeAt(index + 1)));\n ctx.record('fixed-escape', index, 'Replaced a backslash before a control character');\n index += 2;\n break;\n default:\n // Keep both characters: `\\x41` stays `\\x41` rather than becoming `x41`.\n ctx.write('\\\\\\\\');\n ctx.write(source[index + 1]!);\n ctx.record('fixed-escape', index, 'Escaped a backslash that began an unknown sequence');\n index += 2;\n break;\n }\n\n spanStart = index;\n continue;\n }\n\n if (code === closerA || code === closerB) {\n if (probeContinuation(ctx, index + 1, slot)) {\n ctx.writeSpan(spanStart, index);\n ctx.write('\"');\n scanner.index = index + 1;\n return;\n }\n\n // Nothing that could continue the container follows this quote. Either the\n // quote is content, or — in safe mode with a standard delimiter — the real\n // closing quote was dropped and the string ended at the previous newline.\n if (standard && !ctx.options.aggressive) {\n if (checkpoint !== undefined && ctx.canRewindTo(checkpoint)) {\n closeAtCheckpoint(ctx, checkpoint);\n return;\n }\n ctx.writeSpan(spanStart, index);\n ctx.write('\"');\n scanner.index = index + 1;\n return;\n }\n\n ctx.writeSpan(spanStart, index);\n if (standard) {\n ctx.write('\\\\\"');\n ctx.record('escaped-character', index, 'Escaped a quote inside a string');\n } else {\n ctx.write(source[index]!);\n }\n index += 1;\n spanStart = index;\n continue;\n }\n\n if (code < 0x20) {\n ctx.writeSpan(spanStart, index);\n if (code === CH_LINE_FEED || code === CH_CARRIAGE_RETURN) {\n // Remember where the line ended: if the closing quote turns out to be\n // missing, this is the most likely place for the string to have stopped.\n checkpoint = ctx.checkpoint(index);\n }\n if (index !== reportedControlEnd) {\n ctx.record('escaped-character', index, 'Escaped a raw control character in a string');\n }\n reportedControlEnd = index + 1;\n ctx.write(escapeControl(code));\n index += 1;\n spanStart = index;\n continue;\n }\n\n if (code === CH_DOUBLE_QUOTE) {\n // Reached only inside a non-standard delimiter, where `\"` is plain content.\n ctx.writeSpan(spanStart, index);\n ctx.write('\\\\\"');\n index += 1;\n spanStart = index;\n continue;\n }\n\n if (isHighSurrogate(code)) {\n if (index + 1 < end && isLowSurrogate(source.charCodeAt(index + 1))) {\n index += 2;\n continue;\n }\n index = escapeStrayUnit(ctx, spanStart, index, code);\n spanStart = index;\n continue;\n }\n\n if (isLowSurrogate(code)) {\n index = escapeStrayUnit(ctx, spanStart, index, code);\n spanStart = index;\n continue;\n }\n\n index += 1;\n }\n\n // End of input reached with the string still open.\n ctx.writeSpan(spanStart, index);\n\n if (\n checkpoint !== undefined &&\n ctx.canRewindTo(checkpoint) &&\n tailIsStructural(source, checkpoint.index, end)\n ) {\n closeAtCheckpoint(ctx, checkpoint);\n return;\n }\n\n ctx.write('\"');\n ctx.record('terminated-string-at-eof', end);\n scanner.index = end;\n}\n\n/**\n * Writes `[from, to)` of the input as a JSON string literal.\n *\n * Used for text that was never quoted in the source — a bare key or, in\n * aggressive mode, a bare value. Unescaped runs are copied as spans, so the\n * cost is proportional to the number of characters that actually need escaping.\n */\nexport function writeQuotedSpan(ctx: RepairContext, from: number, to: number): void {\n const { source } = ctx.scanner;\n\n ctx.write('\"');\n\n let spanStart = from;\n for (let index = from; index < to; index += 1) {\n const code = source.charCodeAt(index);\n\n let replacement: string | undefined;\n if (code === CH_DOUBLE_QUOTE) {\n replacement = '\\\\\"';\n } else if (code === CH_BACKSLASH) {\n replacement = '\\\\\\\\';\n } else if (code < 0x20) {\n replacement = escapeControl(code);\n } else if (isHighSurrogate(code)) {\n if (index + 1 < to && isLowSurrogate(source.charCodeAt(index + 1))) {\n index += 1;\n continue;\n }\n replacement = escapeUnit(code);\n } else if (isLowSurrogate(code)) {\n replacement = escapeUnit(code);\n }\n\n if (replacement !== undefined) {\n ctx.writeSpan(spanStart, index);\n ctx.write(replacement);\n spanStart = index + 1;\n }\n }\n\n ctx.writeSpan(spanStart, to);\n ctx.write('\"');\n}\n\n/**\n * Escapes an unpaired surrogate so the output survives UTF-8 encoding.\n *\n * `JSON.parse` accepts a lone surrogate, but writing one to a file or a socket\n * produces a replacement character, so the repaired text would no longer round\n * trip. Escaping keeps the exact code unit. Input that needs no repair skips\n * this path entirely and is returned byte-identical.\n */\nfunction escapeStrayUnit(\n ctx: RepairContext,\n spanStart: number,\n index: number,\n code: number,\n): number {\n ctx.writeSpan(spanStart, index);\n ctx.write(escapeUnit(code));\n ctx.record('escaped-character', index, 'Escaped an unpaired surrogate');\n return index + 1;\n}\n\n/** Closes the string at a remembered line break and resumes parsing there. */\nfunction closeAtCheckpoint(ctx: RepairContext, checkpoint: Checkpoint): void {\n ctx.rewindTo(checkpoint);\n ctx.write('\"');\n ctx.record('terminated-string-at-newline', checkpoint.index);\n}\n\n/**\n * Classifies the escape sequence at `index`.\n *\n * Returns the length of the sequence when JSON already accepts it verbatim, so\n * the caller can keep extending its current span, or one of the `ESC_*` codes\n * when the sequence has to be rewritten.\n */\nfunction classifyEscape(source: string, index: number, end: number): number {\n if (index + 1 >= end) {\n return ESC_DANGLING;\n }\n\n const escaped = source.charCodeAt(index + 1);\n\n switch (escaped) {\n case CH_DOUBLE_QUOTE:\n case CH_BACKSLASH:\n case CH_SLASH:\n case CH_LOWER_B:\n case CH_LOWER_F:\n case CH_LOWER_N:\n case CH_LOWER_R:\n case CH_LOWER_T:\n return ESC_SHORT;\n case CH_LOWER_U:\n if (\n index + 5 < end &&\n isHexDigit(source.charCodeAt(index + 2)) &&\n isHexDigit(source.charCodeAt(index + 3)) &&\n isHexDigit(source.charCodeAt(index + 4)) &&\n isHexDigit(source.charCodeAt(index + 5))\n ) {\n return ESC_UNICODE;\n }\n return index + 6 > end ? ESC_TRUNCATED_UNICODE : ESC_BAD_UNICODE;\n default:\n break;\n }\n\n if (isQuote(escaped)) {\n return ESC_QUOTE;\n }\n return escaped < 0x20 ? ESC_CONTROL : ESC_UNKNOWN;\n}\n\n/**\n * Reports whether everything between `from` and `end` is structural.\n *\n * Decides what an unterminated string at end of input swallowed. If the rest is\n * only whitespace and closing punctuation it was the document's structure —\n * `{\"a\": \"oops⏎}` means `{\"a\":\"oops\"}`, not a value containing a brace. If it\n * holds anything else it is real content, and closing at end of input keeps it.\n */\nfunction tailIsStructural(source: string, from: number, end: number): boolean {\n for (let index = from; index < end; index += 1) {\n const code = source.charCodeAt(index);\n if (\n code === CH_CLOSE_BRACE ||\n code === CH_CLOSE_BRACKET ||\n code === CH_COMMA ||\n isWhitespace(code)\n ) {\n continue;\n }\n return false;\n }\n return true;\n}\n\n/** Returns the JSON escape for a control character. */\nfunction escapeControl(code: number): string {\n switch (code) {\n case 0x08:\n return '\\\\b';\n case 0x09:\n return '\\\\t';\n case 0x0a:\n return '\\\\n';\n case 0x0c:\n return '\\\\f';\n case 0x0d:\n return '\\\\r';\n default:\n return escapeUnit(code);\n }\n}\n\n/** Returns the `\\uXXXX` escape for a code unit. */\nfunction escapeUnit(code: number): string {\n return `\\\\u${code.toString(16).padStart(4, '0')}`;\n}\n","import type { RepairContext } from '../parser/state.js';\nimport { CH_CLOSE_BRACE, CH_CLOSE_BRACKET, CH_COMMA, CH_EOF } from '../scanner/tokens.js';\nimport { skipTrivia } from './comments.js';\n\n/** What the parser found where a member or element separator was expected. */\nexport type Separator =\n /** A comma with more content after it. */\n | 'comma'\n /** A comma directly before the container's closer; it has been removed. */\n | 'trailing-comma'\n /** The container ends here — a closing bracket or end of input. */\n | 'end'\n /** Content continues but the comma is missing; one has been inserted. */\n | 'missing';\n\n/**\n * Reads the separator after a member or element, recording whatever repair the\n * input needed.\n *\n * Trailing commas are the single most common JSON defect, and unlike most\n * repairs they are unambiguous in both directions: `[1,2,3,]` can only ever have\n * meant `[1,2,3]`. A missing comma is equally unambiguous once the parser has\n * confirmed that another member starts, which is why both are safe repairs.\n *\n * The cursor is left on the next meaningful character; the closer, if any, is\n * not consumed.\n */\nexport function readSeparator(ctx: RepairContext): Separator {\n skipTrivia(ctx);\n\n const code = ctx.scanner.peek();\n\n if (code === CH_COMMA) {\n const commaPosition = ctx.scanner.index;\n ctx.scanner.index += 1;\n skipTrivia(ctx);\n\n const next = ctx.scanner.peek();\n if (next === CH_CLOSE_BRACE || next === CH_CLOSE_BRACKET || next === CH_EOF) {\n if (!ctx.options.fixTrailingCommas) {\n ctx.fail('Trailing comma before the end of the container', commaPosition);\n }\n ctx.record('removed-trailing-comma', commaPosition);\n return 'trailing-comma';\n }\n return 'comma';\n }\n\n if (code === CH_CLOSE_BRACE || code === CH_CLOSE_BRACKET || code === CH_EOF) {\n return 'end';\n }\n\n ctx.record('added-missing-comma', ctx.scanner.index);\n return 'missing';\n}\n","import { closeUnterminated, dropStrayCloser } from '../repair/brackets.js';\nimport { skipTrivia } from '../repair/comments.js';\nimport { readLiteral } from '../repair/literals.js';\nimport { readNumber } from '../repair/numbers.js';\nimport { readString, writeQuotedSpan } from '../repair/quotes.js';\nimport { readSeparator } from '../repair/trailing-comma.js';\nimport {\n CH_ASTERISK,\n CH_CLOSE_BRACE,\n CH_CLOSE_BRACKET,\n CH_COLON,\n CH_COMMA,\n CH_DOUBLE_QUOTE,\n CH_EOF,\n CH_HASH,\n CH_OPEN_BRACE,\n CH_OPEN_BRACKET,\n CH_SLASH,\n isIdentifierPart,\n isIdentifierStart,\n isQuote,\n isStructural,\n isWhitespace,\n} from '../scanner/tokens.js';\nimport type { Slot } from './probe.js';\nimport type { RepairContext } from './state.js';\n\n/**\n * Outcome of parsing one value.\n *\n * `dropped` means the construct was cut off by the end of the input, nothing\n * was written, and the cursor now sits at the end of the region. Streamed\n * output that stops mid-token is the reason this exists: emitting a husk such\n * as `{\"name\"` is impossible, and failing outright would throw away everything\n * that did arrive, so the truncated tail is discarded and reported.\n */\nexport type ParseStatus = 'ok' | 'dropped';\n\n/**\n * Parses one complete JSON value starting at the cursor, writing the repaired\n * text into the context.\n *\n * The cursor is left immediately after the value; anything beyond it is the\n * caller's concern.\n *\n * @throws {JsonRepairError} when the input cannot be read as JSON in the active mode.\n */\nexport function parseDocument(ctx: RepairContext): void {\n skipTrivia(ctx);\n\n if (ctx.scanner.eof()) {\n throw ctx.error('NO_JSON_FOUND', 'No JSON value found', ctx.scanner.index);\n }\n\n if (parseValue(ctx, 'document', false) === 'dropped') {\n throw ctx.error('NO_JSON_FOUND', 'No JSON value found', ctx.scanner.index);\n }\n}\n\n/**\n * Parses a single value.\n *\n * @param mayDrop Whether an entirely truncated container may be discarded. The\n * top-level value never can: `[{` still has to produce `[]` rather than\n * nothing at all.\n */\nexport function parseValue(ctx: RepairContext, slot: Slot, mayDrop: boolean): ParseStatus {\n const { scanner } = ctx;\n\n for (;;) {\n skipTrivia(ctx);\n\n const start = scanner.index;\n const code = scanner.peek();\n\n if (code === CH_EOF) {\n return 'dropped';\n }\n if (code === CH_OPEN_BRACE) {\n return parseObject(ctx, mayDrop);\n }\n if (code === CH_OPEN_BRACKET) {\n return parseArray(ctx, mayDrop);\n }\n if (isQuote(code)) {\n if (code !== CH_DOUBLE_QUOTE && !ctx.options.allowSingleQuotes) {\n ctx.fail('Non-standard string delimiter, and allowSingleQuotes is disabled', start);\n }\n readString(ctx, slot);\n return 'ok';\n }\n if (\n code === CH_CLOSE_BRACE ||\n code === CH_CLOSE_BRACKET ||\n code === CH_COMMA ||\n code === CH_COLON\n ) {\n // The value is simply absent: `{\"a\":}` or `[1,,2]`.\n if (!ctx.options.aggressive) {\n ctx.refuse('Expected a value', start);\n }\n ctx.write('null');\n ctx.record('added-missing-value', start);\n return 'ok';\n }\n\n const coreEnd = scanCoreToken(ctx, start);\n if (coreEnd > start) {\n return parseBareValue(ctx, start, coreEnd);\n }\n\n // A character that cannot begin anything. Dropping it is the only way to\n // make progress, and only aggressive mode is willing to.\n if (!ctx.options.aggressive) {\n ctx.fail(`Unexpected character ${describeChar(scanner.source, start)}`, start);\n }\n ctx.record('removed-stray-token', start);\n scanner.index = start + 1;\n }\n}\n\n/* ── Objects ────────────────────────────────────────────────────────────── */\n\nfunction parseObject(ctx: RepairContext, mayDrop: boolean): ParseStatus {\n const { scanner } = ctx;\n const openPosition = scanner.index;\n const entry = ctx.checkpoint(openPosition);\n\n scanner.index += 1;\n ctx.enter(openPosition);\n ctx.openBraces += 1;\n ctx.write('{');\n\n let members = 0;\n let closed = false;\n let truncated = false;\n let previousIndex = -1;\n\n for (;;) {\n skipTrivia(ctx);\n\n if (scanner.index === previousIndex) {\n ctx.fail('Parser made no progress', scanner.index);\n }\n previousIndex = scanner.index;\n\n const code = scanner.peek();\n\n if (code === CH_EOF) {\n closeUnterminated(ctx, 'object', scanner.index);\n truncated = true;\n break;\n }\n if (code === CH_CLOSE_BRACE) {\n scanner.index += 1;\n closed = true;\n break;\n }\n if (code === CH_CLOSE_BRACKET) {\n if (ctx.openBrackets > 0) {\n // An enclosing array is waiting for this bracket; close the object here\n // and leave the bracket for its owner.\n closeUnterminated(ctx, 'object', scanner.index);\n break;\n }\n dropStrayCloser(ctx);\n continue;\n }\n if (code === CH_COMMA) {\n // Leading or repeated commas carry no meaning between named members.\n ctx.record('removed-extra-comma', scanner.index);\n scanner.index += 1;\n continue;\n }\n\n if (!canStartKey(ctx, code)) {\n if (!ctx.options.aggressive) {\n ctx.fail(\n `Expected an object key, found ${describeChar(scanner.source, scanner.index)}`,\n scanner.index,\n );\n }\n ctx.record('removed-stray-token', scanner.index);\n scanner.index += 1;\n continue;\n }\n\n const slot = ctx.checkpoint(scanner.index);\n if (members > 0) {\n ctx.write(',');\n }\n\n if (parseMember(ctx) === 'dropped') {\n ctx.restore(slot);\n scanner.index = scanner.end;\n ctx.record('removed-incomplete-member', slot.index);\n closeUnterminated(ctx, 'object', slot.index);\n truncated = true;\n break;\n }\n\n members += 1;\n readSeparator(ctx);\n }\n\n ctx.write('}');\n ctx.openBraces -= 1;\n ctx.leave();\n\n if (mayDrop && truncated && !closed && members === 0) {\n // An opening brace and nothing else: the stream was cut before any content.\n ctx.restore(entry);\n scanner.index = scanner.end;\n return 'dropped';\n }\n return 'ok';\n}\n\n/** Parses `key : value`, writing both. */\nfunction parseMember(ctx: RepairContext): ParseStatus {\n const { scanner } = ctx;\n\n parseKey(ctx);\n skipTrivia(ctx);\n\n const afterKey = scanner.index;\n const next = scanner.peek();\n\n if (next === CH_EOF) {\n return 'dropped';\n }\n\n if (next === CH_COLON) {\n scanner.index += 1;\n } else if (next === CH_CLOSE_BRACE || next === CH_COMMA) {\n // A key with nothing after it: `{\"a\", \"b\": 1}`.\n if (!ctx.options.aggressive) {\n ctx.refuse('Object key has no value', afterKey);\n }\n ctx.record('added-missing-colon', afterKey);\n ctx.write(':null');\n ctx.record('added-missing-value', afterKey);\n return 'ok';\n } else if (isQuote(next)) {\n // `{\"a\" \"b\"}` could be a missing colon or a missing comma between two keys.\n if (!ctx.options.aggressive) {\n ctx.refuse('Expected \":\" between key and value', afterKey);\n }\n ctx.record('added-missing-colon', afterKey);\n } else {\n // `{\"a\" 1}` has only one reading: the colon was dropped.\n ctx.record('added-missing-colon', afterKey);\n }\n\n ctx.write(':');\n return parseValue(ctx, 'object-value', true);\n}\n\n/** Writes the object key at the cursor, quoting it if the input did not. */\nfunction parseKey(ctx: RepairContext): void {\n const { scanner } = ctx;\n const { source, end } = scanner;\n const start = scanner.index;\n const code = scanner.peek();\n\n if (isQuote(code)) {\n readString(ctx, 'object-key');\n return;\n }\n\n let index = start;\n if (isIdentifierStart(code)) {\n index += 1;\n while (index < end && isIdentifierPart(source.charCodeAt(index))) {\n index += 1;\n }\n } else {\n // Aggressive mode only: take everything up to the colon and trim it.\n index = scanBareKey(ctx, start);\n }\n\n writeQuotedSpan(ctx, start, index);\n ctx.record('quoted-key', start);\n scanner.index = index;\n}\n\n/** Reports whether `code` can begin an object key under the active options. */\nfunction canStartKey(ctx: RepairContext, code: number): boolean {\n if (isQuote(code)) {\n return code === CH_DOUBLE_QUOTE || ctx.options.allowSingleQuotes;\n }\n if (!ctx.options.allowUnquotedKeys) {\n return false;\n }\n if (isIdentifierStart(code)) {\n return true;\n }\n return ctx.options.aggressive && !isStructural(code);\n}\n\n/* ── Arrays ─────────────────────────────────────────────────────────────── */\n\nfunction parseArray(ctx: RepairContext, mayDrop: boolean): ParseStatus {\n const { scanner } = ctx;\n const openPosition = scanner.index;\n const entry = ctx.checkpoint(openPosition);\n\n scanner.index += 1;\n ctx.enter(openPosition);\n ctx.openBrackets += 1;\n ctx.write('[');\n\n let elements = 0;\n let closed = false;\n let truncated = false;\n let previousIndex = -1;\n\n for (;;) {\n skipTrivia(ctx);\n\n if (scanner.index === previousIndex) {\n ctx.fail('Parser made no progress', scanner.index);\n }\n previousIndex = scanner.index;\n\n const code = scanner.peek();\n\n if (code === CH_EOF) {\n closeUnterminated(ctx, 'array', scanner.index);\n truncated = true;\n break;\n }\n if (code === CH_CLOSE_BRACKET) {\n scanner.index += 1;\n closed = true;\n break;\n }\n if (code === CH_CLOSE_BRACE) {\n if (ctx.openBraces > 0) {\n closeUnterminated(ctx, 'array', scanner.index);\n break;\n }\n dropStrayCloser(ctx);\n continue;\n }\n if (code === CH_COMMA) {\n // An elided element. Unlike an extra comma between object members this\n // changes the array's length, so safe mode declines to guess.\n if (!ctx.options.aggressive) {\n ctx.refuse('Array element is missing', scanner.index);\n }\n if (elements > 0) {\n ctx.write(',');\n }\n ctx.write('null');\n ctx.record('added-missing-value', scanner.index);\n elements += 1;\n scanner.index += 1;\n continue;\n }\n\n const slot = ctx.checkpoint(scanner.index);\n if (elements > 0) {\n ctx.write(',');\n }\n\n if (parseValue(ctx, 'array-element', true) === 'dropped') {\n ctx.restore(slot);\n scanner.index = scanner.end;\n ctx.record('removed-incomplete-member', slot.index);\n closeUnterminated(ctx, 'array', slot.index);\n truncated = true;\n break;\n }\n\n elements += 1;\n readSeparator(ctx);\n }\n\n ctx.write(']');\n ctx.openBrackets -= 1;\n ctx.leave();\n\n if (mayDrop && truncated && !closed && elements === 0) {\n ctx.restore(entry);\n scanner.index = scanner.end;\n return 'dropped';\n }\n return 'ok';\n}\n\n/* ── Bare tokens ────────────────────────────────────────────────────────── */\n\n/** Emits an unquoted token as a literal, a number, or — aggressively — a string. */\nfunction parseBareValue(ctx: RepairContext, start: number, coreEnd: number): ParseStatus {\n const { scanner } = ctx;\n\n const literal = readLiteral(ctx, start, coreEnd);\n if (literal === 'emitted') {\n scanner.index = coreEnd;\n return 'ok';\n }\n if (literal === 'needs-aggressive') {\n ctx.refuse(`\"${scanner.slice(start, coreEnd)}\" is not a JSON literal`, start);\n }\n\n if (readNumber(ctx, start, coreEnd)) {\n scanner.index = coreEnd;\n return 'ok';\n }\n\n if (!ctx.options.aggressive) {\n ctx.refuse(`Unquoted value \"${scanner.slice(start, coreEnd)}\"`, start);\n }\n\n const valueEnd = extendBareValue(ctx, coreEnd);\n writeQuotedSpan(ctx, start, valueEnd);\n ctx.record('quoted-value', start);\n scanner.index = valueEnd;\n return 'ok';\n}\n\n/**\n * Scans an unquoted token: everything up to whitespace, a structural character,\n * a quote or the start of a comment.\n */\nfunction scanCoreToken(ctx: RepairContext, from: number): number {\n const { source, end } = ctx.scanner;\n const allowComments = ctx.options.allowComments;\n\n let index = from;\n while (index < end) {\n const code = source.charCodeAt(index);\n if (\n isWhitespace(code) ||\n isStructural(code) ||\n isQuote(code) ||\n startsComment(source, index, end, allowComments)\n ) {\n break;\n }\n index += 1;\n }\n return index;\n}\n\n/**\n * Extends an unquoted value across interior whitespace, so `{a: hello world}`\n * yields one value rather than two.\n *\n * Trailing whitespace is excluded, and the scan still stops at any structural\n * character, which keeps `[1 2]` two elements with a missing comma between them.\n */\nfunction extendBareValue(ctx: RepairContext, from: number): number {\n const { source, end } = ctx.scanner;\n const allowComments = ctx.options.allowComments;\n\n let index = from;\n let lastContent = from;\n while (index < end) {\n const code = source.charCodeAt(index);\n if (isStructural(code) || startsComment(source, index, end, allowComments)) {\n break;\n }\n if (!isWhitespace(code)) {\n lastContent = index + 1;\n }\n index += 1;\n }\n return lastContent;\n}\n\n/** Scans an unquoted key: everything up to the colon, trimmed. */\nfunction scanBareKey(ctx: RepairContext, from: number): number {\n const { source, end } = ctx.scanner;\n const allowComments = ctx.options.allowComments;\n\n let index = from;\n let lastContent = from + 1;\n while (index < end) {\n const code = source.charCodeAt(index);\n if (\n code === CH_COLON ||\n isStructural(code) ||\n startsComment(source, index, end, allowComments)\n ) {\n break;\n }\n if (!isWhitespace(code)) {\n lastContent = index + 1;\n }\n index += 1;\n }\n return lastContent;\n}\n\nfunction startsComment(\n source: string,\n index: number,\n end: number,\n allowComments: boolean,\n): boolean {\n if (!allowComments) {\n return false;\n }\n const code = source.charCodeAt(index);\n if (code === CH_HASH) {\n return true;\n }\n if (code !== CH_SLASH || index + 1 >= end) {\n return false;\n }\n const next = source.charCodeAt(index + 1);\n return next === CH_SLASH || next === CH_ASTERISK;\n}\n\n/** Renders one character for an error message. */\nfunction describeChar(source: string, index: number): string {\n const code = source.charCodeAt(index);\n if (Number.isNaN(code)) {\n return 'end of input';\n }\n if (code < 0x20 || code === 0x7f) {\n return `\"\\\\u${code.toString(16).padStart(4, '0')}\"`;\n }\n return `\"${source.charAt(index)}\"`;\n}\n","import type { RepairType } from '../types.js';\n\n/**\n * Human-readable description for each {@link RepairType}.\n *\n * Used as the default {@link RepairOperation.message} and rendered by the CLI's\n * `--explain` output. These strings are documentation, not contract: match on\n * {@link RepairType} instead.\n */\nconst MESSAGES: Record<RepairType, string> = {\n 'removed-byte-order-mark': 'Removed a leading byte order mark',\n 'extracted-json': 'Extracted JSON from surrounding text',\n 'removed-comment': 'Removed a comment',\n 'normalized-whitespace': 'Replaced whitespace that JSON does not allow between tokens',\n 'removed-trailing-comma': 'Removed a trailing comma',\n 'removed-extra-comma': 'Removed a redundant comma',\n 'removed-stray-token': 'Removed a closing bracket that matched nothing',\n 'removed-trailing-content': 'Removed content after the end of the JSON value',\n 'removed-incomplete-member': 'Removed a truncated final member',\n 'added-missing-comma': 'Inserted a missing comma',\n 'added-missing-colon': 'Inserted a missing colon',\n 'added-missing-value': 'Inserted null for a missing value',\n 'added-closing-brace': 'Closed an unterminated object',\n 'added-closing-bracket': 'Closed an unterminated array',\n 'normalized-quotes': 'Converted non-standard quotes to double quotes',\n 'normalized-literal': 'Rewrote a non-JSON literal',\n 'normalized-number': 'Rewrote a non-JSON number',\n 'quoted-key': 'Quoted an unquoted key',\n 'quoted-value': 'Quoted an unquoted value',\n 'escaped-character': 'Escaped a character that JSON forbids raw',\n 'fixed-escape': 'Corrected an invalid escape sequence',\n 'terminated-string-at-eof': 'Closed a string left open at end of input',\n 'terminated-string-at-newline':\n 'Closed a string at a line break, discarding the rest of the line',\n};\n\n/** Returns the default explanation for a repair type. */\nexport function describeRepair(type: RepairType): string {\n return MESSAGES[type];\n}\n","import { buildSnippet, JsonRepairError } from '../errors/JsonRepairError.js';\nimport type { ResolvedOptions } from '../options.js';\nimport { describeRepair } from '../repair/messages.js';\nimport type { Scanner } from '../scanner/scanner.js';\nimport { isWhitespace } from '../scanner/tokens.js';\nimport type { JsonRepairErrorCode, RepairOperation, RepairType } from '../types.js';\n\n/**\n * Multiplier bounding the total work spent on string-continuation lookahead.\n *\n * Each candidate closing quote may trigger a bounded probe. Without a global\n * cap, input engineered to contain hundreds of thousands of quote characters\n * would turn a linear parse into a quadratic one. The budget scales with the\n * input, so the parse stays O(n) by construction; once it is exhausted probes\n * degrade to plain JSON behaviour (accept the closing quote), which is\n * deterministic and never produces invalid output.\n */\nconst PROBE_BUDGET_FACTOR = 4;\n\n/** A point the parser can return to when a string turns out to be unterminated. */\nexport interface Checkpoint {\n /** Absolute offset to resume scanning from. */\n readonly index: number;\n /** Number of output chunks written at the time of the checkpoint. */\n readonly chunkCount: number;\n /** Number of repairs recorded at the time of the checkpoint. */\n readonly repairCount: number;\n}\n\n/**\n * Mutable state shared by the parser and every repair rule: the output being\n * built, the repair log, the depth counters and the resource budgets.\n *\n * One context serves exactly one parse attempt. The candidate loop in\n * `repair.ts` builds a fresh context per attempt, so a failed attempt can never\n * leak repairs or partial output into the next one.\n */\nexport class RepairContext {\n readonly scanner: Scanner;\n readonly options: ResolvedOptions;\n\n /** Repairs applied so far, in the order they were discovered. */\n readonly repairs: RepairOperation[] = [];\n\n /** Pieces of the output, joined once at the end. */\n private readonly chunks: string[] = [];\n\n /** Current nesting depth. */\n private depth = 0;\n\n /** Open `{` containers, used for O(1) stray-closer classification. */\n openBraces = 0;\n\n /** Open `[` containers, used for O(1) stray-closer classification. */\n openBrackets = 0;\n\n /** Remaining lookahead budget; see {@link PROBE_BUDGET_FACTOR}. */\n probeBudget: number;\n\n /**\n * Highest offset the parser has already rewound to.\n *\n * Rewinding is only ever allowed to move forward, which guarantees the parse\n * cannot loop between two readings of the same unterminated string.\n */\n lastRewind = -1;\n\n constructor(scanner: Scanner, options: ResolvedOptions) {\n this.scanner = scanner;\n this.options = options;\n this.probeBudget = (scanner.end - scanner.start) * PROBE_BUDGET_FACTOR;\n }\n\n /* ── Output ───────────────────────────────────────────────────────────── */\n\n /** Appends literal text to the output. */\n write(text: string): void {\n this.chunks.push(text);\n }\n\n /**\n * Appends a span of the original input verbatim.\n *\n * Copying spans rather than characters keeps the number of output chunks\n * proportional to the number of tokens, not to the length of the input.\n */\n writeSpan(from: number, to: number): void {\n if (to > from) {\n this.chunks.push(this.scanner.slice(from, to));\n }\n }\n\n /** Concatenates everything written so far. */\n output(): string {\n return this.chunks.join('');\n }\n\n /* ── Checkpoints ──────────────────────────────────────────────────────── */\n\n /** Captures the current output, repair log and cursor for a later rewind. */\n checkpoint(index: number): Checkpoint {\n return { index, chunkCount: this.chunks.length, repairCount: this.repairs.length };\n }\n\n /**\n * Reports whether the parser may rewind to `checkpoint`.\n *\n * Refusing a backwards rewind is what makes the unterminated-string heuristic\n * terminating: every rewind strictly advances the furthest point already\n * reconsidered.\n */\n canRewindTo(checkpoint: Checkpoint): boolean {\n return checkpoint.index > this.lastRewind;\n }\n\n /**\n * Returns the parser to `checkpoint`, discarding the output written and the\n * repairs recorded since it was taken, and marks the point as reconsidered.\n *\n * Truncating the repair log matters: without it, a rewound attempt would\n * report repairs that are not present in the text it finally emits.\n */\n rewindTo(checkpoint: Checkpoint): void {\n this.restore(checkpoint);\n this.lastRewind = checkpoint.index;\n }\n\n /**\n * Returns the parser to `checkpoint` without marking it as reconsidered.\n *\n * Used to un-write a construct the parser decided to drop rather than re-read\n * — a member truncated by a cut-off stream, for instance. Unlike\n * {@link rewindTo} these restores never re-scan the same text, so they cannot\n * loop and must not consume the rewind budget.\n */\n restore(checkpoint: Checkpoint): void {\n this.chunks.length = checkpoint.chunkCount;\n this.repairs.length = checkpoint.repairCount;\n this.scanner.index = checkpoint.index;\n }\n\n /**\n * Absolute offset of the last non-whitespace character in the region, or\n * `-1` if there is none.\n *\n * Computed once per parse. Recomputing it per token would make input such as\n * half a megabyte of `}` quadratic, which is precisely the shape an attacker\n * would send.\n */\n get lastContentIndex(): number {\n if (this.lastContentCache === -2) {\n this.lastContentCache = findLastContent(\n this.scanner.source,\n this.scanner.start,\n this.scanner.end,\n );\n }\n return this.lastContentCache;\n }\n\n private lastContentCache = -2;\n\n /* ── Repair log ───────────────────────────────────────────────────────── */\n\n /**\n * Records a repair at an absolute offset in the original input.\n *\n * @throws {JsonRepairError} `MAX_REPAIRS_EXCEEDED` once the budget is spent.\n */\n record(type: RepairType, position: number, message?: string): void {\n if (this.repairs.length >= this.options.maxRepairs) {\n throw this.error(\n 'MAX_REPAIRS_EXCEEDED',\n `Input needs more than ${this.options.maxRepairs} repairs.`,\n position,\n );\n }\n\n const { line, column } = this.scanner.positionAt(position);\n this.repairs.push({\n type,\n position,\n line,\n column,\n message: message ?? describeRepair(type),\n });\n }\n\n /* ── Depth ────────────────────────────────────────────────────────────── */\n\n /**\n * Enters a nested container.\n *\n * @throws {JsonRepairError} `MAX_DEPTH_EXCEEDED` beyond the configured depth.\n */\n enter(position: number): void {\n this.depth += 1;\n if (this.depth > this.options.maxDepth) {\n throw this.error(\n 'MAX_DEPTH_EXCEEDED',\n `Input nests deeper than the configured maximum of ${this.options.maxDepth}.`,\n position,\n );\n }\n }\n\n /** Leaves a nested container. */\n leave(): void {\n this.depth -= 1;\n }\n\n /* ── Failure ──────────────────────────────────────────────────────────── */\n\n /** Builds a positioned error without throwing it. */\n error(code: JsonRepairErrorCode, message: string, position: number): JsonRepairError {\n const { line, column } = this.scanner.positionAt(position);\n return new JsonRepairError(code, `${message} (line ${line}, column ${column})`, {\n position,\n line,\n column,\n snippet: buildSnippet(this.scanner.source, position),\n });\n }\n\n /**\n * Aborts the attempt because the input cannot be read as JSON at all.\n *\n * @throws {JsonRepairError} `UNREPAIRABLE_JSON`.\n */\n fail(message: string, position: number): never {\n throw this.error('UNREPAIRABLE_JSON', message, position);\n }\n\n /**\n * Aborts the attempt because safe mode declines to choose between readings.\n *\n * Callers reach this only when `mode: 'aggressive'` has a defined answer, so\n * the message always points at the escape hatch.\n *\n * @throws {JsonRepairError} `AMBIGUOUS_REPAIR`.\n */\n refuse(message: string, position: number): never {\n throw this.error(\n 'AMBIGUOUS_REPAIR',\n `${message}; retry with mode: \"aggressive\" to apply a best-effort repair.`,\n position,\n );\n }\n}\n\n/** Returns the offset of the last non-whitespace character in a region, or `-1`. */\nfunction findLastContent(source: string, start: number, end: number): number {\n for (let index = end - 1; index >= start; index -= 1) {\n if (!isWhitespace(source.charCodeAt(index))) {\n return index;\n }\n }\n return -1;\n}\n","import {\n CH_BACKTICK,\n CH_LINE_FEED,\n CH_OPEN_BRACE,\n CH_OPEN_BRACKET,\n CH_SPACE,\n CH_TAB,\n isLineBreak,\n isWhitespace,\n toLowerAscii,\n} from '../scanner/tokens.js';\n\n/** Tilde, the alternative Markdown fence character. */\nconst CH_TILDE = 0x7e;\n\n/** Shortest run of `` ` `` or `~` that opens a fenced block. */\nconst MIN_FENCE_LENGTH = 3;\n\n/** Deepest indentation a fence may carry and still open a block. */\nconst MAX_FENCE_INDENT = 3;\n\n/** A fenced code block found in the input. */\nexport interface Fence {\n /** First offset of the block's content. */\n bodyStart: number;\n /** Offset one past the block's content. */\n bodyEnd: number;\n /** Whether the info string names a JSON dialect. */\n jsonTagged: boolean;\n}\n\n/**\n * Finds Markdown fenced code blocks, in document order.\n *\n * Written as a linear character scan rather than a pattern match. A regular\n * expression over untrusted, unbounded text is exactly the shape that\n * backtracks catastrophically, and the whole package is built to stay linear on\n * hostile input.\n *\n * A block that is never closed — the usual result of a response hitting its\n * token limit — runs to the end of the input, which is what makes truncated\n * fenced output recoverable.\n */\nexport function scanFences(source: string, start: number, end: number): Fence[] {\n const fences: Fence[] = [];\n\n let lineStart = start;\n while (lineStart < end) {\n const lineEnd = findLineEnd(source, lineStart, end);\n const marker = readFenceMarker(source, lineStart, lineEnd);\n\n if (marker === undefined) {\n lineStart = nextLineStart(source, lineEnd, end);\n continue;\n }\n\n const bodyStart = nextLineStart(source, lineEnd, end);\n const closing = findClosingFence(source, bodyStart, end, marker.char, marker.length);\n\n fences.push({\n bodyStart,\n bodyEnd: closing.bodyEnd,\n jsonTagged: isJsonInfoString(source, marker.infoStart, lineEnd),\n });\n\n lineStart = closing.next;\n }\n\n return fences;\n}\n\n/**\n * Collects the offsets of every `{` and `[` in a region, in document order.\n *\n * These are only *candidate* starts. Nothing here tries to decide where a value\n * ends or whether a brace sits inside a string — that is the parser's job, and\n * duplicating it with a second, weaker notion of \"string\" is how extraction\n * silently truncates values such as `{'note': 'use } to close', 'n': 2}`.\n */\nexport function findValueStarts(\n source: string,\n start: number,\n end: number,\n limit: number,\n): number[] {\n const starts: number[] = [];\n\n for (let index = start; index < end && starts.length < limit; index += 1) {\n const code = source.charCodeAt(index);\n if (code === CH_OPEN_BRACE || code === CH_OPEN_BRACKET) {\n starts.push(index);\n }\n }\n\n return starts;\n}\n\n/** Returns the first non-whitespace offset at or after `start`, or `end`. */\nexport function skipLeadingWhitespace(source: string, start: number, end: number): number {\n let index = start;\n while (index < end && isWhitespace(source.charCodeAt(index))) {\n index += 1;\n }\n return index;\n}\n\n/** Returns the offset one past the last non-whitespace character before `end`. */\nexport function trimTrailingWhitespace(source: string, start: number, end: number): number {\n let index = end;\n while (index > start && isWhitespace(source.charCodeAt(index - 1))) {\n index -= 1;\n }\n return index;\n}\n\ninterface FenceMarker {\n char: number;\n length: number;\n infoStart: number;\n}\n\n/** Reads an opening fence marker from a line, if the line is one. */\nfunction readFenceMarker(\n source: string,\n lineStart: number,\n lineEnd: number,\n): FenceMarker | undefined {\n let index = lineStart;\n let indent = 0;\n while (index < lineEnd && indent <= MAX_FENCE_INDENT) {\n const code = source.charCodeAt(index);\n if (code !== CH_SPACE && code !== CH_TAB) {\n break;\n }\n indent += 1;\n index += 1;\n }\n\n if (index >= lineEnd || indent > MAX_FENCE_INDENT) {\n return undefined;\n }\n\n const char = source.charCodeAt(index);\n if (char !== CH_BACKTICK && char !== CH_TILDE) {\n return undefined;\n }\n\n const runStart = index;\n while (index < lineEnd && source.charCodeAt(index) === char) {\n index += 1;\n }\n\n const length = index - runStart;\n return length >= MIN_FENCE_LENGTH ? { char, length, infoStart: index } : undefined;\n}\n\n/** Locates the fence that closes a block, or the end of the input. */\nfunction findClosingFence(\n source: string,\n bodyStart: number,\n end: number,\n char: number,\n length: number,\n): { bodyEnd: number; next: number } {\n let lineStart = bodyStart;\n\n while (lineStart < end) {\n const lineEnd = findLineEnd(source, lineStart, end);\n const marker = readFenceMarker(source, lineStart, lineEnd);\n\n if (marker?.char === char && marker.length >= length) {\n return { bodyEnd: lineStart, next: nextLineStart(source, lineEnd, end) };\n }\n\n lineStart = nextLineStart(source, lineEnd, end);\n }\n\n return { bodyEnd: end, next: end };\n}\n\n/** Reports whether a fence's info string names a JSON dialect. */\nfunction isJsonInfoString(source: string, from: number, lineEnd: number): boolean {\n let index = from;\n while (index < lineEnd && isWhitespace(source.charCodeAt(index))) {\n index += 1;\n }\n\n const wordStart = index;\n while (index < lineEnd) {\n const code = toLowerAscii(source.charCodeAt(index));\n if (code < 0x30 || (code > 0x39 && code < 0x61) || code > 0x7a) {\n break;\n }\n index += 1;\n }\n\n const length = index - wordStart;\n if (length < 4 || length > 5) {\n return false;\n }\n if (\n toLowerAscii(source.charCodeAt(wordStart)) !== 0x6a /* j */ ||\n toLowerAscii(source.charCodeAt(wordStart + 1)) !== 0x73 /* s */ ||\n toLowerAscii(source.charCodeAt(wordStart + 2)) !== 0x6f /* o */ ||\n toLowerAscii(source.charCodeAt(wordStart + 3)) !== 0x6e /* n */\n ) {\n return false;\n }\n if (length === 4) {\n return true;\n }\n const suffix = toLowerAscii(source.charCodeAt(wordStart + 4));\n return suffix === 0x63 /* jsonc */ || suffix === 0x35; /* json5 */\n}\n\n/** Returns the offset of the line break that ends the line starting at `from`. */\nfunction findLineEnd(source: string, from: number, end: number): number {\n let index = from;\n while (index < end && !isLineBreak(source.charCodeAt(index))) {\n index += 1;\n }\n return index;\n}\n\n/** Returns the offset at which the line after `lineEnd` begins. */\nfunction nextLineStart(source: string, lineEnd: number, end: number): number {\n if (lineEnd >= end) {\n return end;\n }\n let index = lineEnd + 1;\n if (\n source.charCodeAt(lineEnd) !== CH_LINE_FEED &&\n index < end &&\n source.charCodeAt(index) === CH_LINE_FEED\n ) {\n index += 1;\n }\n return index;\n}\n","import { createError, isJsonRepairError, type JsonRepairError } from './errors/JsonRepairError.js';\nimport { assertInputLength, assertString } from './limits.js';\nimport { parseJsonStrict } from './native.js';\nimport {\n resolveExtractOptions,\n withMode,\n type ResolvedOptions,\n type SelectStrategy,\n} from './options.js';\nimport { parseDocument } from './parser/parser.js';\nimport { RepairContext } from './parser/state.js';\nimport {\n findValueStarts,\n scanFences,\n skipLeadingWhitespace,\n trimTrailingWhitespace,\n} from './repair/markdown.js';\nimport { Scanner } from './scanner/scanner.js';\nimport {\n CH_BACKSLASH,\n CH_BOM,\n CH_CLOSE_BRACE,\n CH_CLOSE_BRACKET,\n CH_DOT,\n CH_MINUS,\n CH_OPEN_BRACE,\n CH_OPEN_BRACKET,\n CH_PLUS,\n isDigit,\n isQuote,\n toLowerAscii,\n} from './scanner/tokens.js';\nimport type { ExtractOptions, RepairOperation } from './types.js';\n\n/**\n * Largest number of candidate starts collected from a single region.\n *\n * Prose that happens to contain hundreds of braces is far more likely to be a\n * code sample than a hundred JSON payloads, and every extra candidate is a\n * potential extra parse. The cap keeps a pathological document from turning\n * extraction into a quadratic scan.\n */\nconst MAX_CANDIDATES = 256;\n\n/**\n * Largest number of candidates that may fail before extraction gives up.\n *\n * Successful candidates are disjoint — each one advances a barrier past its own\n * end — so successes cost O(n) in total no matter how many there are. Only\n * failures can re-scan the same text, so only failures need a budget.\n */\nconst MAX_FAILED_ATTEMPTS = 32;\n\n/** A region of the input that might hold a JSON value. */\nexport interface Candidate {\n /** Offset of the first character to parse. */\n start: number;\n /** Offset the parser may not read past. */\n limit: number;\n}\n\n/** A candidate that parsed and validated successfully. */\nexport interface Attempt {\n /** Offset of the candidate's first character in the original input. */\n start: number;\n /** Offset one past the last character the parser consumed. */\n end: number;\n /** Valid JSON text for this candidate. */\n json: string;\n /** The value {@link Attempt.json} parses to, reused by `parseJson`. */\n value: unknown;\n /** Changes applied while parsing this candidate. */\n repairs: RepairOperation[];\n}\n\n/**\n * Extracts the first — by default the best — JSON value embedded in a larger\n * document, and returns it **exactly as it appears in the input**.\n *\n * The text is returned verbatim rather than repaired, which keeps extraction\n * lossless: whitespace, key order and number formatting all survive. A\n * candidate still has to be repairable to be selected, and the default `best`\n * strategy prefers the longest one, so a decoy such as the `[1]` in \"see [1]\n * for details\" loses to a real payload beside it even though the decoy is\n * already valid and the payload needs work. The returned string may itself need\n * repairing before `JSON.parse` will take it.\n *\n * @throws {JsonRepairError} `INVALID_INPUT`, `MAX_LENGTH_EXCEEDED` or\n * `NO_JSON_FOUND` when no candidate could be repaired.\n */\nexport function extractJson(input: string, options?: ExtractOptions): string {\n const resolved = resolveExtractOptions(options);\n const region = prepare(input, resolved);\n const attempts = solve(input, region.start, region.end, resolved);\n const chosen = rankAttempts(attempts, resolved.select);\n\n return input.slice(chosen.start, chosen.end);\n}\n\n/**\n * Extracts every JSON value embedded in a document, in document order, each\n * returned verbatim as it appears in the input.\n *\n * Values nested inside an already-extracted value are not reported separately,\n * so a document containing `[{\"a\":1}]` yields the array, not the array and then\n * its element.\n *\n * Returns an empty array when the document holds no repairable JSON. Unlike\n * {@link extractJson} this never throws `NO_JSON_FOUND`, because \"nothing here\"\n * is an ordinary answer when the caller asked for everything.\n *\n * @throws {JsonRepairError} `INVALID_INPUT` or `MAX_LENGTH_EXCEEDED`.\n */\nexport function extractAllJson(input: string, options?: ExtractOptions): string[] {\n const resolved = resolveExtractOptions(options);\n const region = prepare(input, resolved);\n\n let attempts: Attempt[];\n try {\n attempts = solve(input, region.start, region.end, resolved);\n } catch (error) {\n if (isJsonRepairError(error) && error.code === 'NO_JSON_FOUND') {\n return [];\n }\n throw error;\n }\n\n return attempts.map((attempt) => input.slice(attempt.start, attempt.end));\n}\n\n/**\n * Validates the input and locates the region to scan.\n *\n * A leading byte order mark is excluded from the region rather than stripped, so\n * that every offset the engine reports still refers to the caller's own string.\n */\nexport function prepare(input: string, options: ResolvedOptions): { start: number; end: number } {\n assertString(input, 'input');\n assertInputLength(input, options.maxLength);\n\n return {\n start: input.length > 0 && input.charCodeAt(0) === CH_BOM ? 1 : 0,\n end: input.length,\n };\n}\n\n/**\n * Finds every JSON value in a region, trying safe repairs before aggressive\n * ones.\n *\n * The two-phase order matters for documents that mix prose and JSON. Given\n * `[2024-01-01 12:00:00] {\"level\":\"info\"}`, an aggressive-only pass would happily\n * quote the bare timestamp and return the leading bracket group. Running safe\n * mode across every candidate first means the real object wins, and the\n * aggressive pass only runs when nothing at all parsed cleanly.\n *\n * @returns Successful attempts in document order; never empty.\n * @throws {JsonRepairError} The most relevant failure, or `NO_JSON_FOUND`.\n */\nexport function solve(\n source: string,\n start: number,\n end: number,\n options: ResolvedOptions,\n): Attempt[] {\n const tiers = buildCandidateTiers(source, start, end, options);\n\n const safe = collectAttempts(source, tiers, withMode(options, 'safe'));\n if (safe.attempts.length > 0) {\n return safe.attempts;\n }\n\n if (!options.aggressive) {\n throw safe.error ?? noJsonFound(source, start);\n }\n\n const loose = collectAttempts(source, tiers, options);\n if (loose.attempts.length > 0) {\n return loose.attempts;\n }\n\n throw loose.error ?? safe.error ?? noJsonFound(source, start);\n}\n\n/**\n * Groups candidate starts into tiers, most trustworthy first.\n *\n * Tiers are tried in order and the first one that yields any result wins, which\n * encodes an ordering of evidence: text a model deliberately tagged as JSON\n * beats text merely fenced as code, which beats a brace found loose in prose.\n * Without the tiering, a `{` inside an English sentence would compete on equal\n * terms with the payload the caller actually wants.\n *\n * Fence candidates are bounded by the fence body, so an unterminated string\n * inside a fenced block stops at the closing fence instead of swallowing the\n * rest of the document.\n */\nexport function buildCandidateTiers(\n source: string,\n start: number,\n end: number,\n options: ResolvedOptions,\n): Candidate[][] {\n const whole = wholeRegionCandidate(source, start, end);\n\n if (!options.extract) {\n return whole === undefined ? [] : [[whole]];\n }\n\n const tagged: Candidate[] = [];\n const fenced: Candidate[] = [];\n\n for (const fence of scanFences(source, start, end)) {\n const target = fence.jsonTagged ? tagged : fenced;\n const starts = findValueStarts(source, fence.bodyStart, fence.bodyEnd, MAX_CANDIDATES);\n\n for (const offset of starts) {\n target.push({ start: offset, limit: fence.bodyEnd });\n }\n\n if (starts.length === 0) {\n // A fence may hold a top-level scalar, such as a bare quoted string.\n const body = wholeRegionCandidate(source, fence.bodyStart, fence.bodyEnd);\n if (body !== undefined) {\n target.push(body);\n }\n }\n }\n\n const bare: Candidate[] = findValueStarts(source, start, end, MAX_CANDIDATES).map((offset) => ({\n start: offset,\n limit: end,\n }));\n\n const tiers: Candidate[][] = [];\n for (const tier of [tagged, fenced, bare]) {\n if (tier.length > 0) {\n tiers.push(tier);\n }\n }\n // The whole region is the last resort, for a document that is nothing but a\n // top-level scalar. It is gated on the region actually looking like a value:\n // without the gate, ordinary prose reaches the parser and fails with a\n // syntax-level complaint about its first word, when the honest answer to\n // \"find me the JSON in this text\" is that there is none.\n if (whole !== undefined && startsJsonValue(source, whole.start, end)) {\n tiers.push([whole]);\n }\n\n return tiers;\n}\n\n/** Literal words a JSON-ish document may open with, lower case. */\nconst VALUE_WORDS = ['true', 'false', 'null', 'nan', 'none', 'infinity', 'undefined'];\n\n/** Reports whether a region plausibly begins a JSON value. */\nfunction startsJsonValue(source: string, from: number, end: number): boolean {\n const code = source.charCodeAt(from);\n\n if (\n code === CH_OPEN_BRACE ||\n code === CH_OPEN_BRACKET ||\n code === CH_MINUS ||\n code === CH_PLUS ||\n code === CH_DOT ||\n isDigit(code) ||\n isQuote(code)\n ) {\n return true;\n }\n\n return VALUE_WORDS.some((word) => matchesWord(source, from, end, word));\n}\n\n/** Reports whether `word` appears at `from`, compared without case or locale. */\nfunction matchesWord(source: string, from: number, end: number, word: string): boolean {\n if (from + word.length > end) {\n return false;\n }\n for (let index = 0; index < word.length; index += 1) {\n if (toLowerAscii(source.charCodeAt(from + index)) !== word.charCodeAt(index)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Runs a tier at a time until one produces results.\n *\n * Within a tier, candidates are tried in document order and a success advances a\n * barrier past its own end, so nested values are skipped rather than reported\n * twice. The failure budget is shared across tiers because it exists to bound\n * total work, not work per tier.\n */\nfunction collectAttempts(\n source: string,\n tiers: readonly Candidate[][],\n options: ResolvedOptions,\n): { attempts: Attempt[]; error: JsonRepairError | undefined } {\n let firstError: JsonRepairError | undefined;\n let failures = 0;\n\n for (const tier of tiers) {\n const attempts: Attempt[] = [];\n let barrier = -1;\n\n for (const candidate of tier) {\n if (candidate.start < barrier) {\n continue;\n }\n if (failures >= MAX_FAILED_ATTEMPTS) {\n break;\n }\n\n let attempt: Attempt;\n try {\n attempt = tryCandidate(source, candidate, options);\n } catch (error) {\n if (!isJsonRepairError(error)) {\n // Anything other than a JsonRepairError is a defect in this package,\n // not a property of the input. Surfacing it beats hiding it behind a\n // generic \"no JSON found\".\n throw error;\n }\n failures += 1;\n firstError ??= error;\n // Everything inside the container this candidate opened is a fragment\n // of it, not a document in its own right. Without this the array in\n // `{\"a\": None, \"b\": [1, 2]}` would be accepted the moment the object\n // around it failed, quietly returning a piece of the input as if it\n // were the whole answer.\n barrier = Math.max(barrier, findStructuralEnd(source, candidate.start, candidate.limit));\n continue;\n }\n\n attempts.push(attempt);\n barrier = Math.max(barrier, attempt.end);\n }\n\n if (attempts.length > 0) {\n return { attempts, error: undefined };\n }\n }\n\n return { attempts: [], error: firstError };\n}\n\n/**\n * Finds where the container opened at `start` ends, by matching brackets.\n *\n * This is a balance scan, not a parse: it only has to answer \"which later\n * candidate starts are inside this one\", and it has to answer it for input the\n * parser has already rejected. Quoted text is skipped so a brace inside a\n * string cannot move the answer, and all three quote characters the repairer\n * accepts count as quotes here for the same reason.\n *\n * Closers are matched against the open containers rather than merely counted,\n * mirroring what the parser itself does with a mismatched closer: one that\n * matches an outer frame closes the frames between, and one that matches\n * nothing on the stack is stray and ignored. Plain counting would let the `]`\n * in `{] \"b\": [1,2]}` cancel the opening brace, put the barrier two characters\n * in, and hand the caller the inner `[1,2]` as if it were the document.\n *\n * @returns the offset one past the matching closer, or `end` when the container\n * is never closed — in which case everything that follows really is inside it.\n */\nfunction findStructuralEnd(source: string, start: number, end: number): number {\n // Bounded by the structural-depth precheck, which runs over the whole input\n // before any candidate is tried, so this cannot grow with the input length.\n const open: number[] = [];\n\n for (let index = start; index < end; index += 1) {\n const code = source.charCodeAt(index);\n\n if (isQuote(code)) {\n index += 1;\n while (index < end) {\n const inner = source.charCodeAt(index);\n if (inner === CH_BACKSLASH) {\n index += 1;\n } else if (inner === code) {\n break;\n }\n index += 1;\n }\n continue;\n }\n\n if (code === CH_OPEN_BRACE || code === CH_OPEN_BRACKET) {\n open.push(code);\n continue;\n }\n\n if (code !== CH_CLOSE_BRACE && code !== CH_CLOSE_BRACKET) {\n continue;\n }\n\n const opener = code === CH_CLOSE_BRACE ? CH_OPEN_BRACE : CH_OPEN_BRACKET;\n const frame = open.lastIndexOf(opener);\n if (frame < 0) {\n // Stray closer: nothing it could be closing is open.\n continue;\n }\n\n open.length = frame;\n if (open.length === 0) {\n return index + 1;\n }\n }\n\n return end;\n}\n\n/** Parses one candidate and validates the result. */\nfunction tryCandidate(source: string, candidate: Candidate, options: ResolvedOptions): Attempt {\n const scanner = new Scanner(source, candidate.start, candidate.limit);\n const context = new RepairContext(scanner, options);\n\n parseDocument(context);\n\n const end = scanner.index;\n const { repairs } = context;\n\n if (repairs.length === 0) {\n // Nothing was repaired, so the source text is already valid JSON. Returning\n // it untouched preserves the author's formatting instead of silently\n // reflowing a pretty-printed payload into a single line.\n const slice = source.slice(candidate.start, end);\n const parsed = tryParse(slice);\n if (parsed !== undefined) {\n return { start: candidate.start, end, json: slice, value: parsed.value, repairs };\n }\n }\n\n const json = context.output();\n const parsed = tryParse(json);\n if (parsed === undefined) {\n throw createError(\n 'UNREPAIRABLE_JSON',\n 'The repaired output is not valid JSON. This is a defect in @nexkit/json-repair; ' +\n 'please report it along with the input that triggered it.',\n source,\n candidate.start,\n );\n }\n\n return { start: candidate.start, end, json, value: parsed.value, repairs };\n}\n\n/**\n * Chooses one attempt from a set of successful ones.\n *\n * Attempts arrive in document order, and every comparison below is strict, so\n * ties always resolve to the earliest candidate. That is what makes the choice\n * deterministic rather than dependent on iteration order.\n */\nexport function rankAttempts(attempts: readonly Attempt[], select: SelectStrategy): Attempt {\n const first = attempts[0];\n if (first === undefined) {\n throw new Error('rankAttempts requires at least one attempt');\n }\n\n if (select === 'first') {\n return first;\n }\n if (select === 'last') {\n return attempts[attempts.length - 1]!;\n }\n\n let best = first;\n for (let index = 1; index < attempts.length; index += 1) {\n const attempt = attempts[index]!;\n if (select === 'largest' ? isLarger(attempt, best) : isBetter(attempt, best)) {\n best = attempt;\n }\n }\n\n return best;\n}\n\n/**\n * Longest span wins; among equal spans, fewest repairs wins.\n *\n * Span has to dominate. A document's real payload is the big thing in it, while\n * a decoy — the `[1]` of \"see [1] for details\", or an array nested inside an\n * object that needed one fix — is small and frequently already valid on its\n * own. Ranking by repair count first would hand the caller the decoy and\n * silently drop the payload, which is the one failure mode worse than throwing.\n */\nfunction isBetter(attempt: Attempt, best: Attempt): boolean {\n const span = attempt.end - attempt.start;\n const bestSpan = best.end - best.start;\n if (span !== bestSpan) {\n return span > bestSpan;\n }\n return attempt.repairs.length < best.repairs.length;\n}\n\n/** Longest span wins. */\nfunction isLarger(attempt: Attempt, best: Attempt): boolean {\n return attempt.end - attempt.start > best.end - best.start;\n}\n\n/** Wraps a whole region as a single candidate, or `undefined` if it is blank. */\nfunction wholeRegionCandidate(source: string, start: number, end: number): Candidate | undefined {\n const from = skipLeadingWhitespace(source, start, end);\n const to = trimTrailingWhitespace(source, from, end);\n\n return from < to ? { start: from, limit: end } : undefined;\n}\n\n/** Parses text without letting a `SyntaxError` escape. */\nfunction tryParse(text: string): { value: unknown } | undefined {\n try {\n return { value: parseJsonStrict(text) };\n } catch {\n return undefined;\n }\n}\n\n/** Builds the error used when a document holds nothing repairable. */\nfunction noJsonFound(source: string, position: number): JsonRepairError {\n return createError('NO_JSON_FOUND', 'No JSON value was found in the input.', source, position);\n}\n","import { createError } from './errors/JsonRepairError.js';\nimport { prepare, rankAttempts, solve, type Attempt } from './extract.js';\nimport { assertStructuralDepth } from './limits.js';\nimport { parseJsonStrict } from './native.js';\nimport { resolveOptions, type ResolvedOptions } from './options.js';\nimport { describeRepair } from './repair/messages.js';\nimport { Scanner } from './scanner/scanner.js';\nimport { isJsonWhitespace, isWhitespace } from './scanner/tokens.js';\nimport type { RepairOperation, RepairOptions, RepairResult, RepairType } from './types.js';\n\n/**\n * A {@link RepairResult} plus the parsed value, which the validation stage has\n * already produced. Keeping it lets `parseJson` avoid a second full parse.\n */\nexport interface RepairOutcome extends RepairResult {\n value: unknown;\n}\n\n/**\n * Repairs malformed JSON and returns valid JSON text.\n *\n * Input that is already valid JSON is returned byte for byte, so this is safe to\n * call unconditionally on data that is usually fine.\n *\n * @throws {JsonRepairError} `INVALID_INPUT`, `NO_JSON_FOUND`, `UNREPAIRABLE_JSON`,\n * `AMBIGUOUS_REPAIR`, `MAX_LENGTH_EXCEEDED`, `MAX_DEPTH_EXCEEDED` or\n * `MAX_REPAIRS_EXCEEDED`.\n */\nexport function repairJson(\n input: string,\n options?: RepairOptions & { returnMetadata?: false },\n): string;\n/**\n * Repairs malformed JSON and reports what was changed.\n *\n * @throws {JsonRepairError} See the string-returning overload.\n */\nexport function repairJson(\n input: string,\n options: RepairOptions & { returnMetadata: true },\n): RepairResult;\nexport function repairJson(input: string, options?: RepairOptions): string | RepairResult;\nexport function repairJson(input: string, options?: RepairOptions): string | RepairResult {\n const resolved = resolveOptions(options);\n const outcome = repairInternal(input, resolved);\n\n if (!resolved.returnMetadata) {\n return outcome.json;\n }\n\n return { json: outcome.json, changed: outcome.changed, repairs: outcome.repairs };\n}\n\n/**\n * The full repair pipeline, shared by every public entry point.\n *\n * The stages are ordered so that the cheapest one that can settle the question\n * runs first: reject bad input, try `JSON.parse` unchanged, and only then start\n * scanning.\n */\nexport function repairInternal(input: string, options: ResolvedOptions): RepairOutcome {\n const region = prepare(input, options);\n const fast = tryFastPath(input, region.start, options);\n if (fast !== undefined) {\n return fast;\n }\n\n const attempts = solve(input, region.start, region.end, options);\n const chosen = rankAttempts(attempts, 'best');\n\n const repairs = buildRepairLog(input, region, chosen);\n if (repairs.length > options.maxRepairs) {\n throw createError(\n 'MAX_REPAIRS_EXCEEDED',\n `Repairing this input required ${repairs.length} changes, which exceeds the maximum of ${options.maxRepairs}.`,\n input,\n chosen.start,\n );\n }\n\n return {\n json: chosen.json,\n changed: chosen.json !== input,\n repairs,\n value: chosen.value,\n };\n}\n\n/**\n * Returns the input unchanged when it is already valid JSON.\n *\n * This is what keeps the package cheap to adopt: a caller can pipe every payload\n * through `repairJson` and pay one `JSON.parse` for the ones that were fine all\n * along, with a guarantee that valid input is never reformatted.\n *\n * A byte order mark is the one thing removed here. It is invisible, it makes\n * `JSON.parse` throw, and no caller has ever meant to keep it.\n *\n * @returns `undefined` when the input is not valid JSON, so the caller can fall\n * through to the repairing parser.\n */\nfunction tryFastPath(\n input: string,\n regionStart: number,\n options: ResolvedOptions,\n): RepairOutcome | undefined {\n const text = regionStart > 0 ? input.slice(regionStart) : input;\n\n let value: unknown;\n try {\n value = parseJsonStrict(text);\n } catch {\n // Not valid JSON, or valid but nested past what the host parser tolerates.\n // Either way the repairing parser is the right next step, and it enforces\n // `maxDepth` itself.\n return undefined;\n }\n\n // Deliberately outside the `try`, so a depth rejection propagates to the\n // caller instead of being mistaken for a parse failure.\n assertStructuralDepth(input, regionStart, input.length, options.maxDepth);\n\n const repairs: RepairOperation[] =\n regionStart > 0 ? [operation(new Scanner(input), 'removed-byte-order-mark', 0)] : [];\n\n if (repairs.length > options.maxRepairs) {\n throw createError(\n 'MAX_REPAIRS_EXCEEDED',\n `Removing the byte order mark exceeds the maximum of ${options.maxRepairs} repairs.`,\n input,\n 0,\n );\n }\n\n return { json: text, changed: regionStart > 0, repairs, value };\n}\n\n/**\n * Assembles the final repair log in ascending position order.\n *\n * The parser only knows about the value it was pointed at, so the three changes\n * that happen around it — the byte order mark, the prose before, the prose\n * after — are recorded here, where the surrounding document is still in view.\n */\nfunction buildRepairLog(\n input: string,\n region: { start: number; end: number },\n chosen: Attempt,\n): RepairOperation[] {\n const scanner = new Scanner(input);\n const repairs: RepairOperation[] = [];\n\n if (region.start > 0) {\n repairs.push(operation(scanner, 'removed-byte-order-mark', 0));\n }\n\n const before = classifyGap(input, region.start, chosen.start);\n if (before === 'content') {\n repairs.push(operation(scanner, 'extracted-json', chosen.start));\n } else if (before === 'exotic') {\n repairs.push(operation(scanner, 'normalized-whitespace', region.start));\n }\n\n for (const repair of chosen.repairs) {\n repairs.push(repair);\n }\n\n const after = classifyGap(input, chosen.end, region.end);\n if (after === 'content') {\n repairs.push(operation(scanner, 'removed-trailing-content', chosen.end));\n } else if (after === 'exotic') {\n repairs.push(operation(scanner, 'normalized-whitespace', chosen.end));\n }\n\n return repairs;\n}\n\n/**\n * Describes what sits in the input between the region and the chosen value.\n *\n * The distinction matters because dropping prose and dropping a stray\n * non-breaking space are different events for an auditor, and because either one\n * changes the output — leaving both unrecorded would let `changed` be `true`\n * with an empty repair log.\n */\nfunction classifyGap(\n source: string,\n from: number,\n to: number,\n): 'empty' | 'whitespace' | 'exotic' | 'content' {\n if (from >= to) {\n return 'empty';\n }\n\n let exotic = false;\n for (let index = from; index < to; index += 1) {\n const code = source.charCodeAt(index);\n if (!isWhitespace(code)) {\n return 'content';\n }\n if (!isJsonWhitespace(code)) {\n exotic = true;\n }\n }\n\n return exotic ? 'exotic' : 'whitespace';\n}\n\n/** Builds one fully located repair record. */\nfunction operation(scanner: Scanner, type: RepairType, position: number): RepairOperation {\n const { line, column } = scanner.positionAt(position);\n return { type, position, line, column, message: describeRepair(type) };\n}\n","/**\n * The `json-repair` command-line interface.\n *\n * This module never touches `process`, `fs` or any other host global — every\n * effect it has on the outside world goes through the {@link CliIo} it is\n * given. That is what makes {@link run} directly unit-testable: a test can\n * hand it in-memory stdin text and capture what it would have written,\n * without spawning a subprocess. `src/cli/index.ts` is the only place that\n * wires this module to the real process.\n */\n\nimport {\n isJsonRepairError,\n repairJson,\n type RepairMode,\n type RepairOperation,\n type RepairOptions,\n type RepairResult,\n} from '../index.js';\n\n/**\n * The host operations the CLI needs, injected so {@link run} stays free of\n * direct `process` access.\n */\nexport interface CliIo {\n /** Reads the whole of standard input. Resolves to `undefined` when stdin is a TTY / not piped. */\n readStdin: () => Promise<string | undefined>;\n /** Reads a UTF-8 file. Rejects when the file does not exist. */\n readFile: (path: string) => Promise<string>;\n /** Writes text to standard output. */\n write: (text: string) => void;\n /** Writes text to standard error. */\n writeError: (text: string) => void;\n}\n\n/** Process exit code for a successful run. */\nconst EXIT_SUCCESS = 0;\n/** Process exit code for input that could not be repaired. */\nconst EXIT_FAILURE = 1;\n/** Process exit code for a command line the CLI could not make sense of. */\nconst EXIT_USAGE = 2;\n\n/**\n * The CLI's reported version.\n *\n * This is a literal rather than an import of `package.json`, because pulling\n * JSON into the bundled CLI output would defeat the point of bundling it as a\n * single portable script. It is kept in step with the `version` field in\n * `package.json` by hand, and must be updated alongside it on every release.\n */\nconst VERSION = '1.0.0';\n\n/** Default `--indent` width in spaces, matching common pretty-printer defaults. */\nconst DEFAULT_INDENT = 2;\n\n/** Largest `--indent` width the CLI accepts. */\nconst MAX_INDENT = 10;\n\n/**\n * Usage text shown for `-h`/`--help`. Every line is kept under 80 columns so\n * it reads cleanly in a standard terminal.\n */\nconst USAGE_TEXT = `Usage: json-repair [options] [file]\n\nRepair malformed JSON from LLM output, logs, or hand-edited config, and\nprint valid JSON to standard output.\n\nReads from FILE when one is given, otherwise from standard input.\n\nOptions:\n -p, --pretty Pretty-print the output with indentation\n --indent <n> Spaces per indent level, used with --pretty\n (0-10, default: 2)\n -e, --explain Print a summary of applied repairs to stderr\n -m, --mode <mode> Repair strategy: \"safe\" or \"aggressive\"\n (default: \"safe\")\n --no-extract Do not isolate JSON from surrounding text\n --no-comments Reject //, /* */ and # comments\n --no-single-quotes Reject single-quoted strings\n --no-unquoted-keys Reject unquoted object keys\n --no-trailing-commas Reject a comma right before } or ]\n --no-missing-brackets Do not close an unterminated object or array\n --max-length <n> Maximum accepted input length, in characters\n --max-depth <n> Maximum accepted nesting depth\n --max-repairs <n> Maximum number of repairs to apply\n -h, --help Show this help message and exit\n -v, --version Print the version number and exit\n\nExamples:\n json-repair data.json\n json-repair --pretty --explain broken.json > fixed.json\n cat broken.json | json-repair --mode aggressive\n`;\n\n/**\n * Runs the CLI end to end: parses `argv`, resolves the input, repairs it and\n * writes the result through `io`.\n *\n * This never throws for a user-facing failure — every error path is turned\n * into a message on `io.writeError` and a numeric exit code, matching the\n * convention that only a genuine defect in this package should surface as an\n * uncaught rejection.\n */\nexport async function run(argv: readonly string[], io: CliIo): Promise<number> {\n const parsed = parseArgs(argv);\n if (!parsed.ok) {\n return reportUsageError(io, parsed.message);\n }\n const { args } = parsed;\n\n if (args.help) {\n io.write(USAGE_TEXT);\n return EXIT_SUCCESS;\n }\n if (args.version) {\n io.write(`${VERSION}\\n`);\n return EXIT_SUCCESS;\n }\n\n const input = await readInput(args.file, io);\n if (!input.ok) {\n return reportUsageError(io, input.message);\n }\n\n try {\n return repairAndReport(input.text, args, io);\n } catch (error) {\n return reportFailure(io, error);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Repairing and reporting\n// ---------------------------------------------------------------------------\n\n/**\n * Runs the repair, writes the JSON to stdout and, when requested, the\n * explanation to stderr.\n *\n * A `JsonRepairError` thrown by {@link repairJson} is deliberately left to\n * propagate: the caller in {@link run} is the single place that turns it into\n * an exit code, so the failure path is not duplicated here.\n */\nfunction repairAndReport(input: string, args: CliArgs, io: CliIo): number {\n const result = repairJson(input, buildRepairOptions(args));\n\n const output = args.pretty ? prettyPrint(result.json, args.indent) : result.json;\n io.write(`${output}\\n`);\n\n if (args.explain) {\n io.writeError(formatExplanation(result));\n }\n\n return EXIT_SUCCESS;\n}\n\n/** Builds the options object passed to {@link repairJson}. */\nfunction buildRepairOptions(args: CliArgs): RepairOptions & { returnMetadata: true } {\n return {\n mode: args.mode,\n extract: args.extract,\n allowComments: args.allowComments,\n allowSingleQuotes: args.allowSingleQuotes,\n allowUnquotedKeys: args.allowUnquotedKeys,\n fixTrailingCommas: args.fixTrailingCommas,\n fixMissingBrackets: args.fixMissingBrackets,\n maxLength: args.maxLength,\n maxDepth: args.maxDepth,\n maxRepairs: args.maxRepairs,\n returnMetadata: true,\n };\n}\n\n/**\n * Re-renders already-valid JSON text with indentation.\n *\n * `result.json` is guaranteed by {@link repairJson} to be accepted by\n * `JSON.parse`, so the parse here cannot fail on repaired output; it can only\n * fail if the package itself produced invalid JSON, which would be a defect\n * worth surfacing rather than swallowing.\n */\nfunction prettyPrint(json: string, indent: number): string {\n const value: unknown = JSON.parse(json);\n return JSON.stringify(value, null, indent);\n}\n\n/**\n * Renders the `--explain` report: a summary line followed by one line per\n * applied repair, or a single \"nothing to do\" line when the input was\n * already valid JSON.\n */\nfunction formatExplanation(result: RepairResult): string {\n if (!result.changed || result.repairs.length === 0) {\n return 'No repairs were needed.\\n';\n }\n\n const count = result.repairs.length;\n const heading = count === 1 ? 'Applied 1 repair:' : `Applied ${count} repairs:`;\n\n let text = `${heading}\\n`;\n for (const repair of result.repairs) {\n text += `${formatRepairLine(repair)}\\n`;\n }\n return text;\n}\n\n/**\n * Formats a single repair as ` line:column type message`, dropping any\n * segment whose data is unavailable rather than printing a literal\n * \"undefined\".\n */\nfunction formatRepairLine(repair: RepairOperation): string {\n const segments: string[] = [];\n\n const location = formatLocation(repair.line, repair.column);\n if (location !== undefined) {\n segments.push(location);\n }\n segments.push(repair.type);\n if (repair.message !== undefined) {\n segments.push(repair.message);\n }\n\n return ` ${segments.join(' ')}`;\n}\n\n/** Renders a line/column pair, tolerating either half being unavailable. */\nfunction formatLocation(line: number | undefined, column: number | undefined): string | undefined {\n if (line !== undefined && column !== undefined) {\n return `${line}:${column}`;\n }\n if (line !== undefined) {\n return `${line}`;\n }\n if (column !== undefined) {\n return `:${column}`;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Input resolution\n// ---------------------------------------------------------------------------\n\n/** Outcome of resolving the CLI's input text, from a file or from stdin. */\ntype InputResult =\n { readonly ok: true; readonly text: string } | { readonly ok: false; readonly message: string };\n\n/**\n * Reads the text to repair: from the given file when one was named on the\n * command line, otherwise from stdin.\n *\n * A missing file and an unpiped, non-TTY-free stdin are both reported as\n * usage errors rather than exceptions, since both mean the caller did not\n * give the program anything to work with.\n */\nasync function readInput(file: string | undefined, io: CliIo): Promise<InputResult> {\n if (file !== undefined) {\n try {\n const text = await io.readFile(file);\n return { ok: true, text };\n } catch (error) {\n return { ok: false, message: `cannot read file '${file}': ${errorMessage(error)}` };\n }\n }\n\n const text = await io.readStdin();\n if (text === undefined) {\n return { ok: false, message: 'no input file given and no input piped on stdin' };\n }\n return { ok: true, text };\n}\n\n// ---------------------------------------------------------------------------\n// Error and usage reporting\n// ---------------------------------------------------------------------------\n\n/**\n * Reports a `JsonRepairError` from the repair engine, or any other\n * unexpected failure, and returns the exit code that corresponds to it.\n */\nfunction reportFailure(io: CliIo, error: unknown): number {\n if (isJsonRepairError(error)) {\n io.writeError(`json-repair: ${error.code}: ${error.message}\\n`);\n if (error.line !== undefined && error.column !== undefined && error.snippet !== undefined) {\n io.writeError(` at line ${error.line}, column ${error.column}: ${error.snippet}\\n`);\n }\n return EXIT_FAILURE;\n }\n\n io.writeError(`json-repair: unexpected error: ${errorMessage(error)}\\n`);\n return EXIT_FAILURE;\n}\n\n/** Reports a problem with the command line itself: a bad flag, value or missing input. */\nfunction reportUsageError(io: CliIo, message: string): number {\n io.writeError(`json-repair: ${message}\\n`);\n io.writeError(`Try 'json-repair --help' for more information.\\n`);\n return EXIT_USAGE;\n}\n\n/** Extracts a human-readable message from an unknown thrown value. */\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// ---------------------------------------------------------------------------\n// Argument parsing\n// ---------------------------------------------------------------------------\n\n/**\n * The command line, fully parsed and validated.\n *\n * Every `RepairOptions` field is left `undefined` when the user did not pass\n * the corresponding flag, so {@link buildRepairOptions} can hand the object\n * straight to {@link repairJson} and let the library apply its own defaults\n * for the selected mode.\n */\ninterface CliArgs {\n help: boolean;\n version: boolean;\n pretty: boolean;\n indent: number;\n explain: boolean;\n mode: RepairMode | undefined;\n extract: boolean | undefined;\n allowComments: boolean | undefined;\n allowSingleQuotes: boolean | undefined;\n allowUnquotedKeys: boolean | undefined;\n fixTrailingCommas: boolean | undefined;\n fixMissingBrackets: boolean | undefined;\n maxLength: number | undefined;\n maxDepth: number | undefined;\n maxRepairs: number | undefined;\n file: string | undefined;\n}\n\n/** {@link CliArgs} minus the resolved positional, built up while scanning `argv`. */\ntype MutableArgs = Omit<CliArgs, 'file'>;\n\ntype ParseArgsResult =\n { readonly ok: true; readonly args: CliArgs } | { readonly ok: false; readonly message: string };\n\n/**\n * Signals that the command line could not be parsed.\n *\n * This is thrown only inside {@link parseArgs} and its helpers and is always\n * caught there — it exists purely to unwind out of deeply nested flag\n * handling without threading a result type through every helper function.\n */\nclass UsageError extends Error {}\n\nfunction createDefaultArgs(): MutableArgs {\n return {\n help: false,\n version: false,\n pretty: false,\n indent: DEFAULT_INDENT,\n explain: false,\n mode: undefined,\n extract: undefined,\n allowComments: undefined,\n allowSingleQuotes: undefined,\n allowUnquotedKeys: undefined,\n fixTrailingCommas: undefined,\n fixMissingBrackets: undefined,\n maxLength: undefined,\n maxDepth: undefined,\n maxRepairs: undefined,\n };\n}\n\n/**\n * Parses `argv` into {@link CliArgs}.\n *\n * A single left-to-right scan handles long flags (`--flag`, `--flag value`,\n * `--flag=value`), clustered short flags (`-pe`) and the `--` terminator,\n * accumulating at most one positional argument — a second one is reported as\n * a usage error rather than silently discarded, since it almost always means\n * the caller mistyped a flag.\n */\nfunction parseArgs(argv: readonly string[]): ParseArgsResult {\n const args = createDefaultArgs();\n const positionals: string[] = [];\n let flagsEnded = false;\n let index = 0;\n\n try {\n while (index < argv.length) {\n const token = argv[index];\n if (token === undefined) {\n break;\n }\n\n if (flagsEnded) {\n positionals.push(token);\n index += 1;\n continue;\n }\n\n if (token === '--') {\n flagsEnded = true;\n index += 1;\n continue;\n }\n\n if (token.startsWith('--')) {\n index = applyLongFlag(token, argv, index + 1, args);\n continue;\n }\n\n if (token.startsWith('-') && token.length > 1) {\n index = applyShortFlags(token, argv, index + 1, args);\n continue;\n }\n\n positionals.push(token);\n index += 1;\n }\n } catch (error) {\n if (error instanceof UsageError) {\n return { ok: false, message: error.message };\n }\n throw error;\n }\n\n const [file, extra] = positionals;\n if (extra !== undefined) {\n return { ok: false, message: `unexpected argument '${extra}'` };\n }\n\n return { ok: true, args: { ...args, file } };\n}\n\n/**\n * Applies one long flag, given the index in `argv` immediately after the\n * flag token, and returns the index to resume parsing from.\n *\n * A `--flag=value` token is split on its first `=`, so a value that itself\n * contains `=` still round-trips correctly.\n */\nfunction applyLongFlag(\n token: string,\n argv: readonly string[],\n index: number,\n args: MutableArgs,\n): number {\n const separator = token.indexOf('=');\n const name = separator === -1 ? token : token.slice(0, separator);\n const inline = separator === -1 ? undefined : token.slice(separator + 1);\n\n switch (name) {\n case '--help':\n requireNoInlineValue(name, inline);\n args.help = true;\n return index;\n case '--version':\n requireNoInlineValue(name, inline);\n args.version = true;\n return index;\n case '--pretty':\n requireNoInlineValue(name, inline);\n args.pretty = true;\n return index;\n case '--explain':\n requireNoInlineValue(name, inline);\n args.explain = true;\n return index;\n case '--no-extract':\n requireNoInlineValue(name, inline);\n args.extract = false;\n return index;\n case '--no-comments':\n requireNoInlineValue(name, inline);\n args.allowComments = false;\n return index;\n case '--no-single-quotes':\n requireNoInlineValue(name, inline);\n args.allowSingleQuotes = false;\n return index;\n case '--no-unquoted-keys':\n requireNoInlineValue(name, inline);\n args.allowUnquotedKeys = false;\n return index;\n case '--no-trailing-commas':\n requireNoInlineValue(name, inline);\n args.fixTrailingCommas = false;\n return index;\n case '--no-missing-brackets':\n requireNoInlineValue(name, inline);\n args.fixMissingBrackets = false;\n return index;\n case '--indent': {\n const read = readFlagValue(name, inline, argv, index);\n args.indent = parseIndentValue(name, read.value);\n return read.nextIndex;\n }\n case '--mode': {\n const read = readFlagValue(name, inline, argv, index);\n args.mode = parseModeValue(name, read.value);\n return read.nextIndex;\n }\n case '--max-length': {\n const read = readFlagValue(name, inline, argv, index);\n args.maxLength = parseCountValue(name, read.value);\n return read.nextIndex;\n }\n case '--max-depth': {\n const read = readFlagValue(name, inline, argv, index);\n args.maxDepth = parseCountValue(name, read.value);\n return read.nextIndex;\n }\n case '--max-repairs': {\n const read = readFlagValue(name, inline, argv, index);\n args.maxRepairs = parseCountValue(name, read.value);\n return read.nextIndex;\n }\n default:\n throw new UsageError(`unknown option '${name}'`);\n }\n}\n\n/**\n * Applies a run of clustered short flags such as `-pe`, and returns the\n * index to resume parsing from.\n *\n * Only `-m` takes a value; per the CLI's contract it must be the last letter\n * in the cluster, since anything after it would otherwise be ambiguous\n * between \"more flags\" and \"the mode value\".\n */\nfunction applyShortFlags(\n token: string,\n argv: readonly string[],\n index: number,\n args: MutableArgs,\n): number {\n const body = token.slice(1);\n const separator = body.indexOf('=');\n const cluster = separator === -1 ? body : body.slice(0, separator);\n const inline = separator === -1 ? undefined : body.slice(separator + 1);\n\n if (inline !== undefined && !cluster.endsWith('m')) {\n throw new UsageError(`option '-${cluster}' does not accept a value`);\n }\n\n let nextIndex = index;\n\n for (let position = 0; position < cluster.length; position += 1) {\n const flag = cluster.charAt(position);\n const isLast = position === cluster.length - 1;\n\n switch (flag) {\n case 'h':\n args.help = true;\n break;\n case 'v':\n args.version = true;\n break;\n case 'p':\n args.pretty = true;\n break;\n case 'e':\n args.explain = true;\n break;\n case 'm': {\n if (!isLast) {\n throw new UsageError(`option '-m' must be the last flag in '-${cluster}'`);\n }\n const read = readFlagValue('-m', inline, argv, nextIndex);\n args.mode = parseModeValue('-m', read.value);\n nextIndex = read.nextIndex;\n break;\n }\n default:\n throw new UsageError(`unknown option '-${flag}'`);\n }\n }\n\n return nextIndex;\n}\n\n/** Rejects a `--flag=value` form for a flag that takes no value. */\nfunction requireNoInlineValue(label: string, inline: string | undefined): void {\n if (inline !== undefined) {\n throw new UsageError(`option '${label}' does not accept a value`);\n }\n}\n\n/** The value read for a flag, and the `argv` index parsing should resume from. */\ninterface FlagValue {\n readonly value: string;\n readonly nextIndex: number;\n}\n\n/**\n * Resolves the value for a flag that takes one: the `=`-attached value when\n * there is one, otherwise the next token in `argv`.\n */\nfunction readFlagValue(\n label: string,\n inline: string | undefined,\n argv: readonly string[],\n index: number,\n): FlagValue {\n if (inline !== undefined) {\n return { value: inline, nextIndex: index };\n }\n const value = argv[index];\n if (value === undefined) {\n throw new UsageError(`option '${label}' requires a value`);\n }\n return { value, nextIndex: index + 1 };\n}\n\n/** Parses a `--mode` value, rejecting anything but the two supported modes. */\nfunction parseModeValue(label: string, raw: string): RepairMode {\n if (raw === 'safe' || raw === 'aggressive') {\n return raw;\n }\n throw new UsageError(`option '${label}' must be 'safe' or 'aggressive', received '${raw}'`);\n}\n\n/**\n * Parses a count-like value (`--max-length`, `--max-depth`, `--max-repairs`),\n * rejecting anything that is not a plain non-negative integer.\n *\n * Range limits beyond that (for example `maxDepth` exceeding what the\n * library supports) are intentionally left to `repairJson` itself, which\n * reports them as `INVALID_INPUT` — the CLI only needs to guard against\n * values that are not integers at all.\n */\nfunction parseCountValue(label: string, raw: string): number {\n const value = parseNonNegativeInteger(raw);\n if (value === undefined) {\n throw new UsageError(`option '${label}' must be a non-negative integer, received '${raw}'`);\n }\n return value;\n}\n\n/** Parses an `--indent` value, which is CLI-only and has no library-side range check. */\nfunction parseIndentValue(label: string, raw: string): number {\n const value = parseNonNegativeInteger(raw);\n if (value === undefined || value > MAX_INDENT) {\n throw new UsageError(\n `option '${label}' must be an integer between 0 and ${MAX_INDENT}, received '${raw}'`,\n );\n }\n return value;\n}\n\n/**\n * Parses a string as a non-negative integer without using a regular\n * expression: every character must be an ASCII digit, and the whole string\n * must be non-empty and within `Number`'s safe integer range.\n */\nfunction parseNonNegativeInteger(raw: string): number | undefined {\n if (raw.length === 0) {\n return undefined;\n }\n\n for (let index = 0; index < raw.length; index += 1) {\n const code = raw.charCodeAt(index);\n if (code < 0x30 || code > 0x39) {\n return undefined;\n }\n }\n\n const value = Number(raw);\n return Number.isSafeInteger(value) ? value : undefined;\n}\n","#!/usr/bin/env node\n\n/**\n * Executable entry point for the `json-repair` command.\n *\n * Everything that talks to the operating system lives here and nowhere else\n * in `src/`: the library bundle is checked to contain no Node built-ins so it\n * stays usable in browsers and other non-Node runtimes, and the CLI is built\n * as a separate bundle specifically so it can depend on them. This file's\n * only job is to wire the real process — `argv`, stdin, stdout, stderr, the\n * exit code — to the host-agnostic {@link run} function, which does the\n * actual work and is what gets unit-tested.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport process from 'node:process';\n\nimport { run, type CliIo } from './run.js';\n\n/**\n * Reads `process.stdin` to completion as UTF-8 text.\n *\n * Resolves to `undefined` when stdin is a TTY, which is how `run` tells\n * \"nothing was piped in\" apart from \"an empty document was piped in\" — an\n * empty pipe still resolves to the empty string, not `undefined`, so that a\n * genuinely empty input reaches the repair engine and fails there with a\n * proper `NO_JSON_FOUND` error instead of being mistaken for \"no input at\n * all\".\n */\nasync function readStdin(): Promise<string | undefined> {\n if (process.stdin.isTTY) {\n return undefined;\n }\n\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8'));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nconst io: CliIo = {\n readStdin,\n readFile: (path) => readFile(path, 'utf8'),\n write: (text) => {\n process.stdout.write(text);\n },\n writeError: (text) => {\n process.stderr.write(text);\n },\n};\n\n/**\n * Runs the CLI and translates its result into `process.exitCode`.\n *\n * Setting `process.exitCode` rather than calling `process.exit()` lets Node\n * finish flushing any pending writes — including stdout when it is piped\n * into another process — before the process actually terminates. Calling\n * `process.exit()` immediately can truncate that output.\n */\nasync function main(): Promise<void> {\n process.exitCode = await run(process.argv.slice(2), io);\n}\n\nmain().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`json-repair: unexpected error: ${message}\\n`);\n process.exitCode = 1;\n});\n"]}
|