@isdk/json-repair 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import t from"@apidevtools/json-schema-ref-parser";var s=class s{dereferencedSchema;constructor(t){this.dereferencedSchema=t}static async create(i){if(!i)return new s({});const h=new t,r=await h.dereference(i);return new s(r)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&!!i.properties[s]||!1!==i.additionalProperties))}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),h=i?.properties?.[s];return h?Array.isArray(h.type)?h.type:h.type?[h.type]:[]:[]}},i=class{input="";pos=0;pathStack=[];walker;options;constructor(t,s={}){this.walker=t,this.options={coerceTypes:!0,...s}}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const t=this.peek(),s=this.walker.getSchemaForPath(this.pathStack),i=s?.type;if("{"===t||"object"===i&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===t)return this.consumeArray();const h=this.pos;let r,e=!1;if('"'===t||"'"===t)try{r=this.consumeString();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?e=!0:this.pos=h}catch(t){this.pos=h}else if(this.isDigit(t)||"-"===t)try{r=this.consumeNumber();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?e=!0:this.pos=h}catch(t){this.pos=h}else if("t"===t||"f"===t||"n"===t)try{r="n"===t?this.consumeNull():this.consumeBoolean();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?e=!0:this.pos=h}catch(t){this.pos=h}if(e)return this.options.coerceTypes&&s?this.coerceValue(r,s):r;this.pos=h;const n=this.consumeGreedyString();return this.options.coerceTypes&&s?this.coerceValue(n,s):n}consumeObject(){const t={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const i=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const h=this.consumeKey();if(!h)break;if(!s&&t.hasOwnProperty(h)){this.pos=i;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==i||void 0!==s&&""!==s)&&(t[h]=s)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||s&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!s)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===i)break}return s&&"}"===this.peek()&&this.consumeChar("}"),t}consumeArray(){const t=[];this.consumeChar("["),this.skipWhitespace();let s=0;for(;this.pos<this.input.length&&"]"!==this.peek()&&"}"!==this.peek();){const i=this.pos;this.pathStack.push(s);try{const h=this.consumeValue();this.pos!==i&&(t.push(h),s++)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()&&(this.consumeChar(","),this.skipWhitespace()),this.pos===i)break}return"]"===this.peek()&&this.consumeChar("]"),t}consumeKey(){if(this.skipWhitespace(),this.pos>=this.input.length)return"";if('"'===this.peek()||"'"===this.peek())return this.consumeString();let t="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek();)t+=this.next();return t}consumeGreedyString(){let t="";const s=this.pos;for(;this.pos<this.input.length&&!this.isAtDelimiter();)t+=this.next();this.pos===s&&this.pos<this.input.length&&!this.isAtDelimiter()&&(t+=this.next());let i=t.trim();if(i.length>=2){const t=i[0],s=i[i.length-1];if(('"'===t||"'"===t)&&t===s){const s=i.slice(1,-1);let h=0;for(let i=0;i<s.length;i++)s[i]!==t||0!==i&&"\\"===s[i-1]||h++;if(h%2==1||0===h)return s}}return i}isAtDelimiter(){if(this.pos>=this.input.length)return!0;const t=this.peek();if("}"===t||"]"===t)return!0;const s="number"==typeof this.pathStack[this.pathStack.length-1];if(","===t){if(s)return!0;const t=this.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(t)||this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)}if(this.isLookingAtKey(this.pathStack.slice(0,-1)))return!0;if(this.isWhitespace(t)){const t=this.pos;this.skipWhitespace();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isLookingAtKey(this.pathStack.slice(0,-1));return this.pos=t,i}return!1}isLookingAtKey(t,s=this.pos){const i=this.input.slice(s).match(/^\s*["']?([^"'\s:]+)["']?\s*:/);if(i){const s=i[1];return this.walker.isValidProperty(t,s)}return!1}coerceValue(t,s){const i=Array.isArray(s.type)?s.type:s.type?[s.type]:[],h=String(t).trim();if(s.enum){const t=h.toLowerCase().replace(/[^a-z0-9]/g,"");for(const i of s.enum){if(t===String(i).toLowerCase().replace(/[^a-z0-9]/g,""))return i}}const r=null===t?"null":typeof t;if(i.length>0&&i.includes(r))return t;if(i.includes("number")||i.includes("integer")){let t=h.replace(/([^0-9.\-])/g,t=>","===t||","===t?"":" ").trim().split(/\s+/)[0];const s=parseFloat(t);if(!isNaN(s))return i.includes("integer")?Math.round(s):s}if(i.includes("boolean")){const t=h.toLowerCase(),s=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(s.includes(t))return!1}return i.includes("null")&&"null"===h.toLowerCase()?null:t}consumeString(){const t=this.next();let s="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?(this.next(),this.pos<this.input.length&&(s+=this.next())):s+=this.next();return this.peek()===t&&this.next(),s}consumeNumber(){let t="";for(;this.pos<this.input.length&&/[0-9.\-]/.test(this.peek());)t+=this.next();return parseFloat(t)}consumeBoolean(){const t=this.input.slice(this.pos);return t.startsWith("true")?(this.pos+=4,!0):!!t.startsWith("false")&&(this.pos+=5,!1)}consumeNull(){return this.pos+=4,null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}};async function h(t,h,r={}){const e=h instanceof s?h:await s.create(h);return new i(e,r).parse(t)}export{i as RepairParser,s as SchemaWalker,h as jsonRepair};
package/docs/README.md ADDED
@@ -0,0 +1,107 @@
1
+ **@isdk/json-repair**
2
+
3
+ ***
4
+
5
+ # @isdk/json-repair
6
+
7
+ > 【English|[中文](_media/README.cn.md)】
8
+ ---
9
+
10
+ A powerful, schema-guided JSON repair library specifically designed to fix "broken" JSON generated by LLMs (Large Language Models).
11
+
12
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
13
+ [![npm version](https://badge.fury.io/js/@isdk%2Fjson-repair.svg)](https://www.npmjs.com/package/@isdk/json-repair)
14
+
15
+ ## 🚀 Why this library?
16
+
17
+ LLMs often output JSON that is syntactically invalid or semantically "noisy". Common issues include:
18
+
19
+ - Missing quotes around keys or values.
20
+ - Unescaped quotes inside strings (e.g., `"a"b"`).
21
+ - Missing commas or closing braces.
22
+ - Natural language mixed into values (e.g., `"age": "about 30 years old"`).
23
+ - Implicit structures (e.g., an array of objects without curly braces).
24
+
25
+ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses your **JSON Schema** as a map to intelligently navigate, repair, and coerce the output into valid, structured data.
26
+
27
+ ## ✨ Key Features
28
+
29
+ - **Schema-Guided Repair**: Uses your Schema to resolve ambiguities (e.g., knowing if a colon marks a new key or is part of a string).
30
+ - **Greedy String Capture**: Intelligently captures unquoted or broken strings until the next valid Schema key.
31
+ - **The "Parity Rule"**: Solves nested quote ambiguity (e.g., correctly distinguishing between `"A" OR "B"` and `"a"b"`).
32
+ - **Semantic Coercion**:
33
+ - **Fuzzy Enum Matching**: Matches "Processing!" to `"processing"` if defined in Schema enums.
34
+ - **Noisy Number Extraction**: Extracts `1200.5` from `"Approx. 1,200.50 USD"`.
35
+ - **Boolean Variants**: Recognizes `yes/no`, `on/off`, `1/0`, `确定/取消` as booleans.
36
+ - **Implicit Structure Support**: Automatically repairs missing braces in objects and arrays.
37
+ - **Performance**: Support for reusing `SchemaWalker` instances for high-throughput batch processing.
38
+
39
+ ## 📦 Installation
40
+
41
+ ```bash
42
+ npm install @isdk/json-repair @apidevtools/json-schema-ref-parser
43
+ # or
44
+ pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
45
+ ```
46
+
47
+ ## 🛠 Usage
48
+
49
+ ### 1. Schema-Guided Repair (Recommended)
50
+
51
+ This is the most powerful way to use the library. Providing a schema enables advanced features like semantic coercion, greedy capture, and accurate disambiguation.
52
+
53
+ ```typescript
54
+ import { jsonRepair } from '@isdk/json-repair';
55
+
56
+ const schema = {
57
+ type: 'object',
58
+ properties: {
59
+ query: { type: 'string' },
60
+ status: { enum: ['success', 'error'] }
61
+ }
62
+ };
63
+
64
+ const brokenJson = '{ query: "python" OR "js", status: Success! }';
65
+
66
+ const result = await jsonRepair(brokenJson, schema);
67
+ console.log(result);
68
+ // Output: { query: '"python" OR "js"', status: 'success' }
69
+ ```
70
+
71
+ ### 2. Simple Usage (Without Schema)
72
+
73
+ For basic syntax repair where schema guidance isn't required:
74
+
75
+ ```typescript
76
+ import { jsonRepair } from '@isdk/json-repair';
77
+
78
+ const result = await jsonRepair('{ name: John, age: 30 }');
79
+ console.log(result); // { name: 'John', age: 30 }
80
+ ```
81
+
82
+ ### Advanced: Reusing SchemaWalker (Batch Processing)
83
+
84
+ For better performance when processing many items with the same schema:
85
+
86
+ ```typescript
87
+ import { jsonRepair, SchemaWalker } from '@isdk/json-repair';
88
+
89
+ const walker = await SchemaWalker.create(mySchema);
90
+
91
+ for (const item of brokenItems) {
92
+ const result = await jsonRepair(item, walker);
93
+ // ...
94
+ }
95
+ ```
96
+
97
+ ## ⚠️ Known Limitations & Disambiguation
98
+
99
+ - **The "Parity Rule"**: When a string is wrapped in quotes and contains internal quotes, we count the internal ones.
100
+ - Odd count (e.g., `"a"b"`): We assume the outer quotes are delimiters -> `a"b`.
101
+ - Even count (e.g., `"A" OR "B"`): We assume the outer quotes are part of the expression -> `"A" OR "B"`.
102
+ - **Limitation**: Highly unusual patterns like `"a"b"c"` might remain ambiguous.
103
+ - **Markdown Blocks**: This library focuses on the JSON content. Please strip ```json ...``` markers before passing the string if your LLM includes them.
104
+
105
+ ## 📄 License
106
+
107
+ MIT © Riceball LEE
@@ -0,0 +1,101 @@
1
+ # @isdk/json-repair
2
+
3
+ > 【[English](./README.md)|中文】
4
+ ---
5
+
6
+ 一个强大的、基于 Schema 引导的 JSON 修复库,专为修复大语言模型 (LLM) 生成的“破碎” JSON 而设计。
7
+
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+ [![npm version](https://badge.fury.io/js/@isdk%2Fjson-repair.svg)](https://www.npmjs.com/package/@isdk/json-repair)
10
+
11
+ ## 🚀 为什么选择这个库?
12
+
13
+ LLM 生成的 JSON 经常包含语法错误或语义噪声。常见问题包括:
14
+
15
+ - 键或值缺少引号。
16
+ - 字符串内部引号未转义(例如 `"a"b"`)。
17
+ - 缺少逗号或结尾花括号。
18
+ - 值中混合了自然语言(例如 `"age": "大约 30 岁"`)。
19
+ - 隐式结构(例如数组中的对象缺少花括号)。
20
+
21
+ 传统的 `json-repair` 库仅在语法层面打补丁。**@isdk/json-repair** 利用 **JSON Schema** 作为导航图,智能地解析、修复并将数据强制转换为符合规范的结构化对象。
22
+
23
+ ## ✨ 核心特性
24
+
25
+ - **Schema 引导修复**:利用 Schema 解决歧义(例如通过判断冒号后面是否跟着 Schema 定义的 Key 来决定它是定界符还是字符串内容)。
26
+ - **贪婪字符串捕获**:智能捕获未加引号或破碎的字符串,直到遇到下一个合法的 Schema 键名。
27
+ - **“奇偶判定法”**:完美解决嵌套引号歧义(例如准确区分 `"A" OR "B"` 和 `"a"b"`)。
28
+ - **语义强制转换 (Coercion)**:
29
+ - **枚举模糊匹配**:如果 Schema 定义了枚举,能将 `"Processing!"` 自动匹配为 `"processing"`。
30
+ - **噪声数字提取**:能从 `"约 1,200.50 元"` 中提取出 `1200.5`。
31
+ - **布尔值变体**:识别 `yes/no`、`on/off`、`1/0`、`确定/取消`、`是/否` 为布尔值。
32
+ - **隐式结构支持**:自动修复对象或数组中缺失的花括号。
33
+ - **高性能**:支持复用 `SchemaWalker` 实例,适用于高吞吐量的批处理场景。
34
+
35
+ ## 📦 安装
36
+
37
+ ```bash
38
+ pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
39
+ ```
40
+
41
+ ## 🛠 用法
42
+
43
+ ### 1. Schema 引导修复 (推荐)
44
+
45
+ 这是最强大的使用方式。提供 Schema 可以开启语义强制转换、贪婪捕获和更精准的歧义消除等高级特性。
46
+
47
+ ```typescript
48
+ import { jsonRepair } from '@isdk/json-repair';
49
+
50
+ const schema = {
51
+ type: 'object',
52
+ properties: {
53
+ query: { type: 'string' },
54
+ status: { enum: ['success', 'error'] }
55
+ }
56
+ };
57
+
58
+ const brokenJson = '{ query: "python" OR "js", status: 成功 }';
59
+
60
+ const result = await jsonRepair(brokenJson, schema);
61
+ console.log(result);
62
+ // 输出: { query: '"python" OR "js"', status: 'success' }
63
+ ```
64
+
65
+ ### 2. 简单用法 (不使用 Schema)
66
+
67
+ 对于基础的语法修复,你可以不提供 Schema:
68
+
69
+ ```typescript
70
+ import { jsonRepair } from '@isdk/json-repair';
71
+
72
+ const result = await jsonRepair('{ name: 张三, age: 30 }');
73
+ console.log(result); // { name: '张三', age: 30 }
74
+ ```
75
+
76
+ ### 高级技巧:复用 SchemaWalker (批处理)
77
+
78
+ 如果你需要使用相同的 Schema 处理大量数据,预解析 Schema 可以显著提升性能:
79
+
80
+ ```typescript
81
+ import { jsonRepair, SchemaWalker } from '@isdk/json-repair';
82
+
83
+ const walker = await SchemaWalker.create(mySchema);
84
+
85
+ for (const item of brokenItems) {
86
+ const result = await jsonRepair(item, walker);
87
+ // ...
88
+ }
89
+ ```
90
+
91
+ ## ⚠️ 注意事项与歧义说明
92
+
93
+ - **“奇偶判定法”逻辑**:当字符串被引号包裹且内部包含引号时,我们会计算内部引号的数量。
94
+ - 奇数个 (如 `"a"b"`):认为外层是定界符 -> 结果 `a"b`。
95
+ - 偶数个 (如 `"A" OR "B"`):认为外层是内容的一部分 -> 结果 `"A" OR "B"`。
96
+ - **局限性**:极少数极端模式如 `"a"b"c"` 可能仍存在歧义。
97
+ - **Markdown 代码块**:本库专注于 JSON 内容修复。如果 LLM 的输出包含 ```json ...``` 标记,请在传入前自行剥离。
98
+
99
+ ## 📄 开源协议
100
+
101
+ MIT © Riceball LEE
@@ -0,0 +1,64 @@
1
+ [**@isdk/json-repair**](../README.md)
2
+
3
+ ***
4
+
5
+ [@isdk/json-repair](../globals.md) / RepairParser
6
+
7
+ # Class: RepairParser
8
+
9
+ Defined in: [parser.ts:8](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/parser.ts#L8)
10
+
11
+ A state-machine based parser that repairs and extracts structured data from broken JSON strings.
12
+ It uses a JSON Schema to guide the parsing process, especially for handling ambiguous or missing syntax.
13
+
14
+ ## Constructors
15
+
16
+ ### Constructor
17
+
18
+ > **new RepairParser**(`walker`, `options`): `RepairParser`
19
+
20
+ Defined in: [parser.ts:21](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/parser.ts#L21)
21
+
22
+ Creates a new RepairParser instance.
23
+
24
+ #### Parameters
25
+
26
+ ##### walker
27
+
28
+ [`SchemaWalker`](SchemaWalker.md)
29
+
30
+ An initialized SchemaWalker instance for Schema guidance.
31
+
32
+ ##### options
33
+
34
+ [`RepairOptions`](../interfaces/RepairOptions.md) = `{}`
35
+
36
+ Configuration options for the repair process.
37
+
38
+ #### Returns
39
+
40
+ `RepairParser`
41
+
42
+ ## Methods
43
+
44
+ ### parse()
45
+
46
+ > **parse**(`input`): `any`
47
+
48
+ Defined in: [parser.ts:35](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/parser.ts#L35)
49
+
50
+ Parses the input string and returns the repaired JavaScript object.
51
+
52
+ #### Parameters
53
+
54
+ ##### input
55
+
56
+ `string`
57
+
58
+ The potentially broken JSON string.
59
+
60
+ #### Returns
61
+
62
+ `any`
63
+
64
+ The parsed and repaired object.
@@ -0,0 +1,121 @@
1
+ [**@isdk/json-repair**](../README.md)
2
+
3
+ ***
4
+
5
+ [@isdk/json-repair](../globals.md) / SchemaWalker
6
+
7
+ # Class: SchemaWalker
8
+
9
+ Defined in: [walker/schema-walker.ts:8](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/walker/schema-walker.ts#L8)
10
+
11
+ Navigates through a JSON Schema based on a JSON Path.
12
+ Handles $ref resolution and provides type information for specific paths.
13
+
14
+ ## Methods
15
+
16
+ ### getExpectedTypes()
17
+
18
+ > **getExpectedTypes**(`path`, `key`): `string`[]
19
+
20
+ Defined in: [walker/schema-walker.ts:89](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/walker/schema-walker.ts#L89)
21
+
22
+ Gets the expected types for a specific property at a given path.
23
+
24
+ #### Parameters
25
+
26
+ ##### path
27
+
28
+ [`JSONPath`](../type-aliases/JSONPath.md)
29
+
30
+ The current parent path.
31
+
32
+ ##### key
33
+
34
+ `string`
35
+
36
+ The property key.
37
+
38
+ #### Returns
39
+
40
+ `string`[]
41
+
42
+ An array of expected type strings (e.g., ["string", "number"]).
43
+
44
+ ***
45
+
46
+ ### getSchemaForPath()
47
+
48
+ > **getSchemaForPath**(`path`): `any`
49
+
50
+ Defined in: [walker/schema-walker.ts:37](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/walker/schema-walker.ts#L37)
51
+
52
+ Retrieves the sub-schema for a given JSON path.
53
+
54
+ #### Parameters
55
+
56
+ ##### path
57
+
58
+ [`JSONPath`](../type-aliases/JSONPath.md)
59
+
60
+ The path to navigate to.
61
+
62
+ #### Returns
63
+
64
+ `any`
65
+
66
+ The sub-schema at the specified path, or undefined if not found.
67
+
68
+ ***
69
+
70
+ ### isValidProperty()
71
+
72
+ > **isValidProperty**(`path`, `key`): `boolean`
73
+
74
+ Defined in: [walker/schema-walker.ts:64](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/walker/schema-walker.ts#L64)
75
+
76
+ Determines if a property key is valid for the given path according to the Schema.
77
+
78
+ #### Parameters
79
+
80
+ ##### path
81
+
82
+ [`JSONPath`](../type-aliases/JSONPath.md)
83
+
84
+ The current parent path.
85
+
86
+ ##### key
87
+
88
+ `string`
89
+
90
+ The property key to check.
91
+
92
+ #### Returns
93
+
94
+ `boolean`
95
+
96
+ True if the property is defined in the Schema or allowed by additionalProperties.
97
+
98
+ ***
99
+
100
+ ### create()
101
+
102
+ > `static` **create**(`schema`): `Promise`\<`SchemaWalker`\>
103
+
104
+ Defined in: [walker/schema-walker.ts:22](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/walker/schema-walker.ts#L22)
105
+
106
+ Static factory method to create a SchemaWalker instance.
107
+ Asynchronously dereferences the provided JSON Schema.
108
+
109
+ #### Parameters
110
+
111
+ ##### schema
112
+
113
+ `any`
114
+
115
+ The JSON Schema object to walk.
116
+
117
+ #### Returns
118
+
119
+ `Promise`\<`SchemaWalker`\>
120
+
121
+ A promise that resolves to a SchemaWalker instance.
@@ -0,0 +1,48 @@
1
+ [**@isdk/json-repair**](../README.md)
2
+
3
+ ***
4
+
5
+ [@isdk/json-repair](../globals.md) / jsonRepair
6
+
7
+ # Function: jsonRepair()
8
+
9
+ > **jsonRepair**(`input`, `schema?`, `options?`): `Promise`\<`any`\>
10
+
11
+ Defined in: [repair.ts:21](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/repair.ts#L21)
12
+
13
+ Repairs and parses a JSON string generated by an LLM, guided by a JSON Schema.
14
+ This is the main entry point for the library.
15
+
16
+ ## Parameters
17
+
18
+ ### input
19
+
20
+ `string`
21
+
22
+ The potentially broken JSON string to be repaired.
23
+
24
+ ### schema?
25
+
26
+ `any`
27
+
28
+ Either a plain JSON Schema object or a pre-initialized SchemaWalker instance for better performance in batch processing.
29
+
30
+ ### options?
31
+
32
+ [`RepairOptions`](../interfaces/RepairOptions.md) = `{}`
33
+
34
+ Optional configuration to tune the repair process.
35
+
36
+ ## Returns
37
+
38
+ `Promise`\<`any`\>
39
+
40
+ A promise that resolves to the repaired and parsed JavaScript object.
41
+
42
+ ## Example
43
+
44
+ ```typescript
45
+ const schema = { type: 'object', properties: { name: { type: 'string' } } };
46
+ const result = await jsonRepair('{ name: John }', schema);
47
+ console.log(result); // { name: 'John' }
48
+ ```
@@ -0,0 +1,24 @@
1
+ [**@isdk/json-repair**](README.md)
2
+
3
+ ***
4
+
5
+ # @isdk/json-repair
6
+
7
+ A schema-guided JSON repair library specifically designed for LLM-generated outputs.
8
+
9
+ ## Classes
10
+
11
+ - [RepairParser](classes/RepairParser.md)
12
+ - [SchemaWalker](classes/SchemaWalker.md)
13
+
14
+ ## Interfaces
15
+
16
+ - [RepairOptions](interfaces/RepairOptions.md)
17
+
18
+ ## Type Aliases
19
+
20
+ - [JSONPath](type-aliases/JSONPath.md)
21
+
22
+ ## Functions
23
+
24
+ - [jsonRepair](functions/jsonRepair.md)
@@ -0,0 +1,63 @@
1
+ [**@isdk/json-repair**](../README.md)
2
+
3
+ ***
4
+
5
+ [@isdk/json-repair](../globals.md) / RepairOptions
6
+
7
+ # Interface: RepairOptions
8
+
9
+ Defined in: [types.ts:4](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/types.ts#L4)
10
+
11
+ Options for the JSON repair process.
12
+
13
+ ## Properties
14
+
15
+ ### additionalProperties?
16
+
17
+ > `optional` **additionalProperties**: `"keep"` \| `"remove"`
18
+
19
+ Defined in: [types.ts:35](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/types.ts#L35)
20
+
21
+ Defines how to handle properties not defined in the Schema.
22
+
23
+ - `'keep'` (default): Keeps these extra properties in the output.
24
+ - `'remove'`: Automatically removes properties not found in the Schema.
25
+
26
+ ***
27
+
28
+ ### coerceTypes?
29
+
30
+ > `optional` **coerceTypes**: `boolean`
31
+
32
+ Defined in: [types.ts:27](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/types.ts#L27)
33
+
34
+ Whether to attempt type coercion based on the Schema.
35
+
36
+ If `true`, the parser will try to convert values to the expected type (e.g., "123" to 123 for numbers, "yes" to true for booleans).
37
+
38
+ ***
39
+
40
+ ### keyMatching?
41
+
42
+ > `optional` **keyMatching**: `boolean` \| (`key`, `properties`) => `string` \| `undefined`
43
+
44
+ Defined in: [types.ts:12](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/types.ts#L12)
45
+
46
+ Fuzzy matching for keys.
47
+
48
+ - `false` (default): Strict matching against the Schema defined keys.
49
+ - `true`: Allows case-insensitive matching and conversion between snake_case and camelCase.
50
+ - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic to find a matching property name.
51
+
52
+ ***
53
+
54
+ ### stringCaptureStrategy?
55
+
56
+ > `optional` **stringCaptureStrategy**: `"conservative"` \| `"aggressive"`
57
+
58
+ Defined in: [types.ts:20](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/types.ts#L20)
59
+
60
+ Strategy for greedy string capture when standard JSON parsing fails.
61
+
62
+ - `'conservative'`: Stops at any text matching the `"key":` pattern.
63
+ - `'aggressive'` (default): Only stops if the key exists in the Schema and its following value type matches the expectations.
@@ -0,0 +1,14 @@
1
+ [**@isdk/json-repair**](../README.md)
2
+
3
+ ***
4
+
5
+ [@isdk/json-repair](../globals.md) / JSONPath
6
+
7
+ # Type Alias: JSONPath
8
+
9
+ > **JSONPath** = (`string` \| `number`)[]
10
+
11
+ Defined in: [types.ts:42](https://github.com/isdk/json-repair.js/blob/3f845b403701594c2cff6cea4e1759ad41923da5/src/types.ts#L42)
12
+
13
+ Represents the current path in a JSON structure.
14
+ A list of strings (keys) and numbers (indices).
@@ -0,0 +1,31 @@
1
+ import { defineConfig, globalIgnores } from "eslint/config";
2
+ import tsdoc from "eslint-plugin-tsdoc";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import js from "@eslint/js";
6
+ import { FlatCompat } from "@eslint/eslintrc";
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+ const compat = new FlatCompat({
11
+ baseDirectory: __dirname,
12
+ recommendedConfig: js.configs.recommended,
13
+ allConfig: js.configs.all
14
+ });
15
+
16
+ export default defineConfig([globalIgnores(["web/**/*", "docs/**/*"]), {
17
+ extends: compat.extends("prettier"),
18
+
19
+ plugins: {
20
+ tsdoc,
21
+ },
22
+
23
+ rules: {
24
+ "tsdoc/syntax": "off",
25
+ "no-cond-assign": "off",
26
+ "yml/plain-scalar": "off",
27
+ "yml/quotes": "off",
28
+ "unicorn/prefer-number-properties": "off",
29
+ "@typescript-eslint/no-explicit-any": "off",
30
+ },
31
+ }]);
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@isdk/json-repair",
3
+ "version": "0.1.1",
4
+ "description": "A powerful, schema-guided JSON repair library for fixing broken JSON generated by LLMs, featuring semantic coercion and fuzzy matching.",
5
+ "keywords": [
6
+ "json",
7
+ "repair",
8
+ "fix",
9
+ "llm",
10
+ "ai",
11
+ "schema",
12
+ "json-schema",
13
+ "parser",
14
+ "recovery",
15
+ "broken-json",
16
+ "semantic-coercion",
17
+ "fuzzy-matching"
18
+ ],
19
+ "author": "Riceball LEE <snowyu.lee@gmail.com>",
20
+ "homepage": "https://github.com/isdk/json-repair.js",
21
+ "repository": "https://github.com/isdk/json-repair.js",
22
+ "bugs": "https://github.com/@isdk/json-repair.js/issues",
23
+ "license": "MIT",
24
+ "main": "dist/index.js",
25
+ "types": "dist/index.d.ts",
26
+ "type": "module",
27
+ "exports": {
28
+ ".": "./dist/index.js"
29
+ },
30
+ "dependencies": {
31
+ "@apidevtools/json-schema-ref-parser": "^15.1.3",
32
+ "lodash-es": "^4.17.23"
33
+ },
34
+ "devDependencies": {
35
+ "@types/json-schema": "^7.0.15",
36
+ "@types/lodash-es": "^4.17.12",
37
+ "@types/node": "^25.1.0",
38
+ "eslint": "^9.39.2",
39
+ "eslint-config-prettier": "^10.1.8",
40
+ "eslint-plugin-tsdoc": "^0.5.0",
41
+ "prettier": "^3.8.1",
42
+ "terser": "^5.46.0",
43
+ "tsup": "^8.5.1",
44
+ "tsx": "^4.21.0",
45
+ "typedoc": "^0.28.16",
46
+ "typedoc-plugin-markdown": "^4.9.0",
47
+ "typescript": "~5.7.3",
48
+ "vite": "^7.3.1",
49
+ "vite-tsconfig-paths": "^6.0.5",
50
+ "vitest": "^4.0.18"
51
+ },
52
+ "scripts": {
53
+ "build-fast": "tsup",
54
+ "build": "pnpm run build-fast --dts-resolve --dts && pnpm run doc:md",
55
+ "clean": "rm -fr web docs dist",
56
+ "doc": "typedoc --plugin none --out web",
57
+ "doc:md": "typedoc --plugin typedoc-plugin-markdown --out docs",
58
+ "format": "pnpm run format:base -c",
59
+ "format:base": "prettier \"src/**/*.{ts,tsx,js,jsx,css,scss,sass,less,md}\"",
60
+ "format:fix": "pnpm run format:base --write",
61
+ "lint": "eslint .",
62
+ "lint:fix": "pnpm run lint --fix",
63
+ "style": "pnpm run format:base -c && pnpm run lint",
64
+ "style:fix": "pnpm run format:fix && npm run lint:fix",
65
+ "test": "vitest run",
66
+ "release": "pnpm run clean && pnpm run build && git add -f docs && git ci -m 'docs: update API docs' && pnpm dlx commit-and-tag-version -s",
67
+ "release.alpha": "pnpm run release -- --prerelease alpha"
68
+ }
69
+ }
@@ -0,0 +1,15 @@
1
+ // 这个 fetchMock 没有传递abort 中的 reason!
2
+
3
+ /*
4
+ import createFetchMock from 'vitest-fetch-mock';
5
+ import { vi } from 'vitest';
6
+ // import './fetch-polyfill.mjs';
7
+
8
+ const fetchMocker = createFetchMock(vi);
9
+
10
+ // sets globalThis.fetch and globalThis.fetchMock to our mocked version
11
+ fetchMocker.enableMocks();
12
+
13
+ // changes default behavior of fetchMock to use the real 'fetch' implementation and not mock responses
14
+ fetchMocker.dontMock();
15
+ */