@isdk/json-repair 0.1.2 → 0.2.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/README.cn.md +245 -14
- package/README.md +293 -14
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +777 -23
- package/dist/index.d.ts +777 -23
- package/dist/index.js +1 -1
- package/docs/README.md +293 -14
- package/docs/_media/README.cn.md +245 -14
- package/docs/classes/RepairParser.md +71 -5
- package/docs/classes/SchemaWalker.md +126 -6
- package/docs/functions/compareScores.md +32 -0
- package/docs/functions/discardedText.md +42 -0
- package/docs/functions/expectsArrayRoot.md +23 -0
- package/docs/functions/findImplicitRecordRegion.md +32 -0
- package/docs/functions/jsonRepair.md +4 -3
- package/docs/functions/jsonRepairResult.md +50 -0
- package/docs/functions/locateJsonCandidates.md +33 -0
- package/docs/functions/looksLikeSchemaEcho.md +29 -0
- package/docs/functions/renderValidatorErrors.md +32 -0
- package/docs/functions/scoreCandidate.md +45 -0
- package/docs/functions/validateValue.md +38 -0
- package/docs/globals.md +19 -0
- package/docs/interfaces/CandidateScore.md +63 -0
- package/docs/interfaces/JsonCandidate.md +71 -0
- package/docs/interfaces/LocatedJson.md +48 -0
- package/docs/interfaces/RepairOptions.md +257 -19
- package/docs/interfaces/RepairResult.md +58 -0
- package/docs/interfaces/ValidationError.md +27 -0
- package/docs/type-aliases/CommentStyle.md +13 -0
- package/docs/type-aliases/EscapeMode.md +13 -0
- package/docs/type-aliases/JSONPath.md +1 -1
- package/docs/type-aliases/LiteralDialect.md +13 -0
- package/docs/type-aliases/RepairFlag.md +11 -0
- package/package.json +38 -12
- package/.prettierignore +0 -4
- package/.prettierrc +0 -8
- package/.versionrc +0 -36
- package/CHANGELOG.md +0 -18
- package/TODO +0 -0
- package/eslint.config.mjs +0 -31
- package/setupVitest.mjs +0 -15
- package/tsconfig.json +0 -19
- package/tsconfig.spec.json +0 -19
- package/tsup.config.ts +0 -34
- package/typedoc.config.cjs +0 -7
- package/vite.config.mjs +0 -16
package/dist/index.js
CHANGED
|
@@ -1 +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,e=await h.dereference(i);return new s(e)}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 e,r=!1;if('"'===t||"'"===t)try{e=this.consumeString();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if(this.isDigit(t)||"-"===t)try{e=this.consumeNumber();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if("t"===t||"f"===t||"n"===t)try{e="n"===t?this.consumeNull():this.consumeBoolean();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}if(r)return this.options.coerceTypes&&s?this.coerceValue(e,s):e;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=[];let i=!1,h="";for(;this.pos<this.input.length;){const e=this.peek();if(0===s.length&&this.isAtDelimiter())break;if(i){if(e===h){let t=0,s=this.pos-1;for(;s>=0&&"\\"===this.input[s];)t++,s--;t%2==0&&(i=!1)}}else if('"'===e||"'"===e)i=!0,h=e;else if("("===e||"["===e||"{"===e)s.push(e);else if(")"===e||"]"===e||"}"===e){const t=s[s.length-1];(")"===e&&"("===t||"]"===e&&"["===t||"}"===e&&"{"===t)&&s.pop()}t+=this.next()}let e=t.trim();if(e.length>=2){const t=e[0],s=e[e.length-1];if(('"'===t||"'"===t)&&t===s){const s=e.slice(1,-1);let i=0;for(let h=0;h<s.length;h++)s[h]!==t||0!==h&&"\\"===s[h-1]||i++;if(i%2==1||0===i)return s}}return e}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 e=null===t?"null":typeof t;if(i.length>0&&i.includes(e))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,e={}){const r=h instanceof s?h:await s.create(h);return new i(r,e).parse(t)}export{i as RepairParser,s as SchemaWalker,h as jsonRepair};
|
|
1
|
+
import{dereference as t}from"@apidevtools/json-schema-ref-parser";import{cloneDeep as e}from"lodash-es";var s=class s{dereferencedSchema;options;constructor(t,e={}){this.dereferencedSchema=t,this.options=e}static async create(i,r={}){if(!i)return new s({},r);const n=await t(e(i));return new s(n,r)}getSchemaForPath(t){let e=this.dereferencedSchema;for(const s of t){if(!e)return;if("object"===e.type||e.properties)e=e.properties?.[s]||e.additionalProperties;else{if("array"!==e.type&&!e.items)return 0===Object.keys(e).length?{}:void 0;e=Array.isArray(e.items)?e.items[s]||e.additionalItems:e.items}}return e}isValidProperty(t,e){const s=this.getSchemaForPath(t);return!s||(0===Object.keys(s).length||(!s.type||"object"===s.type)&&(s.properties&&null!==this.matchProperty(t,e)||!1!==s.additionalProperties))}matchProperty(t,e){const i=this.declaredPropertyNames(t);if(i.includes(e))return e;const r=this.options.keyMatching;if(!r||0===i.length)return null;if("function"==typeof r){const t=r(e,i);return"string"==typeof t&&""!==t?t:null}const n=s.normalizeName(e);return i.find(t=>s.normalizeName(t)===n)??null}declaredPropertyNames(t){const e=this.getSchemaForPath(t)?.properties;return e?Object.keys(e):[]}static normalizeName(t){return t.replace(/[\s_\-.]/g,"").toLowerCase()}isDeclaredProperty(t,e){const s=this.getSchemaForPath(t);return!!s?.properties&&Object.prototype.hasOwnProperty.call(s.properties,e)}hasDeclaredProperties(t){const e=this.getSchemaForPath(t);return!!e?.properties&&Object.keys(e.properties).length>0}getExpectedTypes(t,e){const s=this.getSchemaForPath(t),i=s?.properties?.[e];return i?Array.isArray(i.type)?i.type:i.type?[i.type]:[]:[]}},i=class{constructor(t){this.max=t}max;entries=new Map;compute(t,e){const s=this.entries.get(t);if(void 0!==s)return s;const i=e(t);return this.entries.set(t,i),this.entries.size>this.max&&this.entries.delete(this.entries.keys().next().value),i}get size(){return this.entries.size}};function r(t,e,s=e){return void 0===t?[...s]:"boolean"==typeof t?t?[...e]:[]:[...t]}var n=["js","python"],o=["line","block","hash"],h=[],u=512,c=new RegExp(String.raw`^\s*(?:"((?:\\.|[^"\\]){0,${u}})"|'((?:\\.|[^'\\]){0,${u}})'|([^\s"',:{}\[\]]{1,${u}}))\s*:`),a=class t{input="";pos=0;pathStack=[];walker;options;readFlags=new Set;dropped=[];commentStyles;literalDialects;constructor(t,e={}){this.walker=t,this.options={coerceTypes:!0,...e},this.commentStyles=r(this.options.comments,o,h),this.literalDialects=r(this.options.literals,n,n)}get consumed(){return this.pos}get droppedText(){return this.dropped}get flags(){return this.readFlags}get remainder(){return this.input.slice(this.pos)}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.cachedPath=null,this.cachedDeclaredKeys=[],this.readFlags.clear(),this.dropped=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const e=this.peek(),s=this.walker.getSchemaForPath(this.pathStack);if(this.pathStack.length>=t.MAX_NESTING&&("["===e||"{"===e||!1!==this.options.wrapArrays&&t.declaresArray(s)&&this.isLookingAtKey([...this.pathStack,0])||t.declaresObject(s)&&this.isLookingAtKey(this.pathStack)))return void this.readFlags.add("nesting-limited");if("["===e)return this.consumeArray();if(!1!==this.options.wrapArrays&&t.declaresArray(s)&&("{"===e||this.isLookingAtKey([...this.pathStack,0])))return this.consumeArray(!0);if("{"===e||t.declaresObject(s)&&this.isLookingAtKey(this.pathStack))return this.consumeObject();const i=this.pos,r=this.tryConsumeStrictValue(e);if(r.ok)return this.options.coerceTypes&&s?this.coerceValue(r.value,s,r.raw):r.value;this.pos=i;const n=this.consumeUnterminatedString()??this.consumeGreedyString();this.swallowedComment(this.input.slice(i,this.pos))&&this.readFlags.add("comment-in-value");let o=t.guidesScalar(s)?void 0:this.dialectLiteral(n);if(!o&&s){const e=this.dialectLiteral(n);e&&t.allows(s,e.value)&&(o=e)}return o?(this.readFlags.add("non-json-literal"),o.value):this.options.coerceTypes&&s?this.coerceValue(n,s):n}static allows(t,e){return t.enum?t.enum.some(t=>t===e):"const"in t&&t.const===e}static guidesScalar(t){return!!t&&(void 0!==t.type||void 0!==t.enum||void 0!==t.const)}dialectLiteral(e){return this.literalDialects.includes("python")&&t.PYTHON_LITERALS.has(e)?{value:t.PYTHON_LITERALS.get(e)}:this.literalDialects.includes("js")&&t.JS_LITERALS.has(e)?{value:t.JS_LITERALS.get(e)}:void 0}static PYTHON_LITERALS=new Map([["True",!0],["False",!1],["None",null]]);static JS_LITERALS=new Map([["undefined",null]]);consumeUnterminatedString(){const t=this.options.unescapedQuotes??"keep";if("keep"===t||'"'!==this.peek())return;const e="declared"===t;for(let t=this.pos+1;t<this.input.length;t++){if("\\"===this.input[t]){t++;continue}if('"'!==this.input[t]||!this.closesValueAt(t,e))continue;this.next();let s="";for(;this.pos<t;)s+="\\"===this.peek()&&this.pos+1<t?this.consumeEscape():this.next();return this.next(),this.readFlags.add("unescaped-quote-inferred"),s}}closesValueAt(t,e){const s=this.pos;this.pos=t+1;const i=this.isAtDelimiter("structural");if(this.pos=s,!i)return!1;if(!e)return!0;const r=this.nextMemberPos(t+1);if(r>=this.input.length)return!0;if("}"===this.input[r]||"]"===this.input[r])return!0;const n=this.pathStack.slice(0,-1),o=this.matchKey(r+(","===this.input[r]?1:0));return null!==o&&null!==this.walker.matchProperty(n,o)}skipMemberGap(){if(this.skipWhitespace(),0===this.commentStyles.length)return;let t=!1;for(;this.skipOneComment();)t=!0,this.skipWhitespace();t&&this.readFlags.add("comment-skipped")}skipOneComment(){const t=this.input.slice(this.pos,this.pos+2);if("/*"===t&&this.commentStyles.includes("block")){const t=this.input.indexOf("*/",this.pos+2);return-1!==t&&(this.pos=t+2,!0)}return("//"===t&&this.commentStyles.includes("line")||!("#"!==t[0]||!this.commentStyles.includes("hash")))&&this.skipToLineEnd()}static COMMENT_GAP=/[\s{[,]/;swallowedComment(e){let s=null,i=!1;for(let r=0;r<e.length;r++){const n=e[r];if(s){i?i=!1:"\\"===n?i=!0:n===s&&(s=null);continue}if('"'===n||"'"===n){s=n;continue}if(0===r||!t.COMMENT_GAP.test(e[r-1]))continue;const o="#"===n?"hash":"/"===n&&"/"===e[r+1]?"line":"/"===n&&"*"===e[r+1]?"block":null;if(null!==o&&!this.commentStyles.includes(o))return!0}return!1}nextMemberPos(t){const e=this.pos;this.pos=t,this.skipMemberGap();const s=this.pos;return this.pos=e,s}skipToLineEnd(){const t=this.input.indexOf("\n",this.pos);return this.pos=-1===t?this.input.length:t,!0}tryConsumeStrictValue(e){const s=this.pos;let i=null;if('"'===e||"'"===e?i=()=>this.consumeString():this.isDigit(e)||"-"===e||"+"===e?i=()=>this.consumeNumber():"t"!==e&&"f"!==e&&"n"!==e||(i=()=>"n"===e?this.consumeNull():this.consumeBoolean()),!i)return{ok:!1,value:void 0};try{const r=i(),n=this.input.slice(s,this.pos);this.skipMemberGap();const o='"'!==e&&"'"!==e||t.closesString(n);if(this.isAtDelimiter("structural",o)||this.pos>=this.input.length)return{ok:!0,value:r,raw:n}}catch(t){}return this.pos=s,{ok:!1,value:void 0}}static MAX_NESTING=1e3;static declaresObject(t){return!!t&&(Array.isArray(t.type)?t.type.includes("object"):"object"===t.type||!!t.properties)}consumeObject(){const e={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipMemberGap();this.pos<this.input.length&&"}"!==this.peek();){this.skipMemberGap();const i=this.danglingTail();if(i){this.dropped.push(i.text),this.readFlags.add("dangling-dropped"),this.pos=i.end;break}const r=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const n=this.consumeKey(this.pathStack);if(null===n)break;const o=[...this.pathStack],h=this.walker.matchProperty(o,n)??n;if(!s&&Object.prototype.hasOwnProperty.call(e,h)){this.pos=r;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==r||void 0!==s&&""!==s)&&this.isKeptProperty(o,h)&&t.setOwn(e,h,s)}finally{this.pathStack.pop()}if(this.skipMemberGap(),","===this.peek()){const t=this.nextMemberPos(this.pos+1);if(this.isLookingAtKey(this.pathStack,t)||s&&"}"===this.input[t])this.consumeChar(","),this.skipMemberGap();else{if(!s)break;this.consumeChar(","),this.skipMemberGap()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===r)break}return s&&"}"===this.peek()&&this.consumeChar("}"),e}isKeptProperty(t,e){return"remove"!==this.options.additionalProperties||(!this.walker.hasDeclaredProperties(t)||this.walker.isDeclaredProperty(t,e))}static setOwn(t,e,s){Object.defineProperty(t,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}static declaresArray(t){return!!t&&(Array.isArray(t.type)?t.type.includes("array"):"array"===t.type||!!t.items)}consumeArray(t=!1){const e=[];t||this.consumeChar("["),this.skipMemberGap();let s=0;for(;this.pos<this.input.length;){if(this.skipMemberGap(),"]"===this.peek()){if(this.consumeChar("]"),this.skipWhitespace(),!this.startsAnotherRecord())break;continue}if("}"===this.peek())break;const t=this.pos;this.pathStack.push(s);try{const i=this.consumeValue();this.pos!==t&&(e.push(i),s++)}finally{this.pathStack.pop()}if(this.skipMemberGap(),","===this.peek()&&(this.consumeChar(","),this.skipMemberGap()),this.pos===t)break}return e}startsAnotherRecord(){const t=[...this.pathStack,0],e=this.walker.getSchemaForPath(t);if(!e)return!1;if("object"!==e.type&&!e.properties)return!1;if("{"===this.peek())return!0;if(this.matchDeclaredKey(this.pos,t))return!0;const s=this.matchKey(this.pos);return null!==s&&null!==this.walker.matchProperty(t,s)}consumeKey(t=this.pathStack){if(this.skipWhitespace(),this.pos>=this.input.length)return null;if('"'===this.peek()||"'"===this.peek())return this.consumeString();if("{"===this.peek()||"["===this.peek())return null;const e=this.matchDeclaredKey(this.pos,t);if(e)return this.pos+=e.length,e.key;let s="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek()&&'"'!==this.peek()&&"'"!==this.peek();)s+=this.next();return s}consumeGreedyString(){let t="";const e=[];let s=!1,i="";for(;this.pos<this.input.length;){const r=this.peek();if(0===e.length&&this.isAtDelimiter("greedy",!s))break;if(s){if(r===i){let t=0,e=this.pos-1;for(;e>=0&&"\\"===this.input[e];)t++,e--;t%2==0&&(s=!1)}}else if('"'===r||"'"===r)s=!0,i=r;else if("("===r||"["===r||"{"===r)e.push(r);else if(")"===r||"]"===r||"}"===r){const t=e[e.length-1];(")"===r&&"("===t||"]"===r&&"["===t||"}"===r&&"{"===t)&&e.pop()}t+=this.next()}let r=t.trim();if(r.length>=2){const t=r[0],e=r[r.length-1];if(('"'===t||"'"===t)&&t===e){const e=r.slice(1,-1);let s=0;for(let i=0;i<e.length;i++)e[i]!==t||0!==i&&"\\"===e[i-1]||s++;if(s%2==1||0===s)return e}}return r}static WORD_CHAR=/[\p{L}\p{N}_]/u;static declaredKeyPatterns=new i(2e3);cachedPath=null;cachedDeclaredKeys=[];declaredMultiWordKeys(e){if(this.cachedPath&&this.cachedPath.length===e.length&&this.cachedPath.every((t,s)=>t===e[s]))return this.cachedDeclaredKeys;const s=!0===this.options.keyMatching,i=this.walker.declaredPropertyNames(e).filter(t=>/\s/.test(t.trim())).map(e=>{const i=`${s?"i":""}:${e}`,r=t.declaredKeyPatterns.compute(i,()=>{const t=e.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");return new RegExp(`^${t}(?=\\s*:)`,s?"i":"")});return{name:e,pattern:r}}).sort((t,e)=>e.name.length-t.name.length);return this.cachedPath=[...e],this.cachedDeclaredKeys=i,i}matchDeclaredKey(e,s=this.pathStack){let i=e;for(;i<this.input.length&&this.isWhitespace(this.input[i]);)i++;if(i>0&&t.WORD_CHAR.test(this.input[i-1]))return null;const r=this.declaredMultiWordKeys(s);if(0===r.length)return null;const n=this.input.slice(i);let o=null;for(const{name:t,pattern:e}of r){const s=n.match(e);s&&(!o||s[0].length>o.length)&&(o={key:t,length:s[0].length})}return o}isAtDelimiter(t="greedy",e=!0){if(this.pos>=this.input.length)return!0;const s=this.peek();if("}"===s||"]"===s)return!0;const i="number"==typeof this.pathStack[this.pathStack.length-1];if(","===s){if(i)return!0;const s=this.nextMemberPos(this.pos+1),r=this.input.slice(s);return!!/^[}\]]/.test(r)||(""===r.trimEnd()||(!(!e||!this.isDanglingTail(s))||this.isBoundaryAhead(s,t)))}if(this.isBoundaryAhead(this.pos,t))return!0;if(this.isWhitespace(s)){const e=this.pos;this.skipMemberGap();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isBoundaryAhead(this.pos,t);return this.pos=e,i}return!1}isLookingAtKey(t,e=this.pos){if(null!==this.matchDeclaredKey(e,t))return!0;const s=this.matchKey(e);return null!==s&&this.walker.isValidProperty(t,s)}matchKey(e=this.pos){if(e>0&&t.WORD_CHAR.test(this.input[e-1]))return null;const s=this.input.slice(e).match(c);if(!s)return null;const i=void 0!==s[1]||void 0!==s[2];let r=s[1]??s[2]??s[3];return i&&(r=r.replace(/\\(["'\\])/g,"$1")),r}static DANGLING_TAIL=new RegExp(String.raw`^\s*("(?:\\.|[^"\\]){0,${u}}"?|'(?:\\.|[^'\\]){0,${u}}'?|[^\s"',:{}\[\]]{1,${u}})\s*[}\]]*\s*(?:\{|\[|$)`);danglingTail(e=this.pos){if(!1===this.options.dangling)return;const s=this.input.slice(e),i=t.DANGLING_TAIL.exec(s);if(!i)return;const r=i[1];return'"'!==r[0]&&"'"!==r[0]&&/^[\d.+-]+$/.test(r)?void 0:{text:r,end:e+i.index+r.length}}isDanglingTail(t=this.pos){return void 0!==this.danglingTail(t)}static closesString(t){const e=t[0];if(t.length<2||t[t.length-1]!==e)return!1;let s=0;for(let e=t.length-2;e>=0&&"\\"===t[e];e--)s++;return s%2==0}static PATH_NOT_KEY=/^\s*[^\s"',:{}\[\]]+:[/\\]/;isBoundaryAhead(e,s){const i=this.pathStack.slice(0,-1);if(null!==this.matchDeclaredKey(e,i))return!0;const r=this.matchKey(e);return null!==r&&(!t.PATH_NOT_KEY.test(this.input.slice(e))&&("structural"===s||("conservative"===this.options.stringCaptureStrategy||(this.walker.hasDeclaredProperties(i)?null!==this.walker.matchProperty(i,r):this.walker.isValidProperty(i,r)))))}coerceValue(e,s,i){const r=Array.isArray(s.type)?s.type:s.type?[s.type]:[],n=String(e).trim();if(s.enum){const i=t.enumSpelling(e);if(null!==i)for(const e of s.enum)if(t.enumSpelling(e)===i)return e}const o=null===e?"null":typeof e;if(r.length>0&&r.includes(o))return e;if(r.includes("string"))return null===e||"object"==typeof e||"string"==typeof e?e:void 0!==i?i.trim():String(e);if(r.includes("number")||r.includes("integer")){const t=n.replace(/(?<=\d)[,,](?=\d)/g,""),e=t.match(/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?/),s=e?parseFloat(e[0]):NaN;if(!isNaN(s))return e&&this.reportNumberCoercion(t,e),r.includes("integer")?Math.round(s):s}if(r.includes("boolean")){const t=n.toLowerCase(),e=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(e.includes(t))return!1}return r.includes("null")&&"null"===n.toLowerCase()?null:e}reportNumberCoercion(e,s){const i=s.index??0,r=(e.slice(0,i)+e.slice(i+s[0].length)).replace(t.COERCED_EDGE,"");""!==r&&(this.readFlags.add("coerced-text-dropped"),(r.split(/\s+/).length>=3||r.length>=20)&&this.dropped.push(r))}static COERCED_EDGE=/^[\s,]+|[\s,]+$/g;static enumSpelling(t){if("string"!=typeof t&&"number"!=typeof t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]/g,"");return""===e?null:e}static ESCAPE_MAP={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};consumeEscape(){const e=this.options.escapes??"json5";if(this.next(),this.pos>=this.input.length)return"\\";const s=this.next(),i=t.ESCAPE_MAP[s],r="raw"===e||void 0!==i?0:"u"===s?4:"x"===s&&"json5"===e?2:0,n=r>0?this.readHex(r):null;return void 0!==i||null!==n&&"u"===s||this.readFlags.add("invalid-escape"),"raw"===e?`\\${s}`:void 0!==i?i:null!==n?String.fromCharCode(n):0===r&&"json5"===e?s:`\\${s}`}readHex(t){let e=0;for(let s=0;s<t;s++){const t=parseInt(this.input[this.pos+s],16);if(Number.isNaN(t))return null;e=16*e+t}return this.pos+=t,e}consumeString(){const t=this.next();let e="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?e+=this.consumeEscape():e+=this.next();return this.peek()===t&&this.next(),e}static NUMBER_PATTERN=/^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?/;consumeNumber(){const e=this.input.slice(this.pos).match(t.NUMBER_PATTERN);return e?(this.pos+=e[0].length,parseFloat(e[0])):NaN}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++}},f=/(?:```|~~~)[ \t]*[A-Za-z0-9+_-]*\s*$/,l=/^\s*(?:```|~~~)/;function d(t){const e=t.getSchemaForPath([]);return!!e&&(Array.isArray(e.type)?e.type.includes("array"):"array"===e.type||!!e.items)}function p(t,e){const s=function(t){const e=[];let s=0,i=-1,r=!1,n=!1;for(let o=0;o<t.length;o++){const h=t[o];r?n?n=!1:"\\"===h?n=!0:('"'===h||"\n"===h)&&(r=!1):'"'!==h?"{"!==h&&"["!==h?("}"===h||"]"===h)&&s>0&&(s--,0===s&&(e.push(b(t,i,o+1)),i=-1)):(0===s&&(i=o),s++):r=!0}s>0&&i>=0&&e.push(b(t,i,t.length,["truncated-candidate"]));return e}(t),i=e?m(t,e):void 0;if(i&&(0===s.length||i.start<s[0].start)){const e=s.filter(t=>t.end>i.end||t.start<i.start);return[i,...e].map(e=>$(t,e))}const r=e&&d(e)&&function(t){const e=t.getSchemaForPath([0]);return!(!e||"object"!==e.type&&!e.properties)}(e)?function(t,e){const s=[];for(const i of e){const e=s[s.length-1];e&&/^[\s,]*$/.test(t.slice(e.end,i.start))?s[s.length-1]=b(t,e.start,i.end,[...e.flags.filter(t=>"truncated-candidate"!==t),...i.flags,"sibling-objects-merged"]):s.push(i)}return s}(t,s):s;return r.map(e=>$(t,e))}function m(t,e){const s=[...e.declaredPropertyNames([]),...d(e)?e.declaredPropertyNames([0]):[]];if(0===s.length)return;let i;for(const e of s){const s=y(e).exec(t),r=s?.indices?.[1]?.[0];void 0!==r&&(void 0===i||r<i)&&(i=r)}return void 0!==i?b(t,i,t.length,["implicit-structure"]):void 0}var g=new i(2e3);function y(t){return g.compute(t,()=>{return new RegExp(`(?:^|[{[,\\s])(${e=t,e.replace(/[.*+?^${}()|[\\]\\]/g,"\\$&")})\\s*:`,"id");var e})}function b(t,e,s,i=[]){return{start:e,end:s,text:t.slice(e,s),flags:i}}function $(t,e){const s=[...e.flags],i=t.slice(0,e.start),r=t.slice(e.end);return!f.test(i)||!l.test(r)&&r.trim()||s.unshift("markdown-fence"),{...e,flags:s}}function v(t,e,s){const i=s.map(t=>t.text),r=[e,...s].sort((t,e)=>t.start-e.start),n=[];let o=0;for(const e of r){const s=t.slice(o,e.start).trim();s&&n.push({text:s,start:o}),o=Math.max(o,e.end)}const h=t.slice(o).trim();return h&&n.push({text:h,start:o}),{prose:n,fragments:i}}function w(t,e){const s={errors:0,requiredCovered:0,declaredCovered:0,undeclaredKeys:0,schemaEchoKeys:0},i=new Set;let r=0;const n=(t,o)=>{const h=e.getSchemaForPath(o);if(h){if(null!==t&&"object"==typeof t&&!Array.isArray(t)){const e=h.properties,u=new Set(Array.isArray(h.required)?h.required:[]);if(e)for(const r of Object.keys(e))Object.hasOwn(t,r)&&void 0!==t[r]&&(A(t[r],e[r])?(s.declaredCovered++,u.has(r)&&s.requiredCovered++):u.has(r)&&"string"==typeof t[r]&&""===t[r].trim()&&i.add("empty-required"));for(const i of Object.keys(t))e&&!(i in e)&&(s.undeclaredKeys++,x.has(i)&&(s.schemaEchoKeys++,r++)),n(t[i],[...o,i]);return}Array.isArray(t)&&t.forEach((e,s)=>n(t[s],[...o,s]))}};return n(t,[]),r>=2&&i.add("schema-echo-detected"),{score:s,flags:[...i]}}function S(t){return"string"==typeof t?(t.match(O)?.length??0)>=2:!(!t||"object"!=typeof t||Array.isArray(t))&&Object.keys(t).filter(t=>j.has(t)).length>=2}var O=/(?:^|[{,]\s*)["']?(?:\$schema|\$id|\$ref|\$defs|additionalProperties|properties|required|definitions|enum|anyOf|allOf|oneOf|items)["']?\s*:/g,j=new Set("$schema $id $ref $defs additionalProperties properties required definitions enum anyOf allOf oneOf items".split(" "));function A(t,e){if(void 0===t)return!1;if(null===t){return(Array.isArray(e?.type)?e.type:e?.type?[e.type]:[]).includes("null")}return"string"!=typeof t||""!==t.trim()}function N(t,e){return t.errors-e.errors||e.requiredCovered-t.requiredCovered||e.declaredCovered-t.declaredCovered||t.schemaEchoKeys-e.schemaEchoKeys}var x=new Set(["type","properties","required","additionalProperties","items","enum","allOf","anyOf","oneOf","not","format","pattern","minimum","maximum","minLength","maxLength","minItems","maxItems","definitions","$defs","$schema","$id","$ref","title","description","default"]);function k(t,e){const s=[];return P(t,[],e,s),s}function E(t,e=6){return t.slice(0,e).map(t=>{return`- ${e=t.path,0===e.length?"<root>":e.join(".")}: ${t.message}`;var e}).join("\n")}function P(t,e,s,i){const r=s.getSchemaForPath(e);if(r&&0!==Object.keys(r).length)if(function(t,e,s,i){const r=function(t){return null===t?"null":Array.isArray(t)?"array":void 0===t?"undefined":typeof t}(t);if(void 0!==e.type){const n=Array.isArray(e.type)?e.type:[e.type];n.some(e=>function(t,e,s){return e===s||"integer"===e&&("number"===s&&Number.isInteger(t))}(t,e,r))||i.push({path:s,message:`expected ${n.join(" or ")}, got ${r}`})}"const"in e&&!T(t,e.const)&&i.push({path:s,message:`expected the constant ${JSON.stringify(e.const)}`});if(Array.isArray(e.enum)){e.enum.some(e=>T(t,e))||i.push({path:s,message:`expected one of ${e.enum.map(t=>JSON.stringify(t)).join(", ")}, got ${JSON.stringify(t)}`})}"string"==typeof t&&("string"!=typeof e.pattern||function(t,e){try{return new RegExp(e).test(t)}catch{return!0}}(t,e.pattern)||i.push({path:s,message:`does not match pattern ${e.pattern}`}),"string"!=typeof e.format||function(t,e){const s=M[e];return!s||s.test(t)}(t,e.format)||i.push({path:s,message:`does not match format ${e.format}`}),"number"==typeof e.minLength&&t.length<e.minLength&&i.push({path:s,message:`shorter than minLength ${e.minLength}`}),"number"==typeof e.maxLength&&t.length>e.maxLength&&i.push({path:s,message:`longer than maxLength ${e.maxLength}`}));"number"==typeof t&&("number"==typeof e.minimum&&t<e.minimum&&i.push({path:s,message:`below minimum ${e.minimum}`}),"number"==typeof e.maximum&&t>e.maximum&&i.push({path:s,message:`above maximum ${e.maximum}`}),!0===e.exclusiveMinimum&&"number"==typeof e.minimum&&t===e.minimum&&i.push({path:s,message:`must be above minimum ${e.minimum}`}),!0===e.exclusiveMaximum&&"number"==typeof e.maximum&&t===e.maximum&&i.push({path:s,message:`must be below maximum ${e.maximum}`}));Array.isArray(t)&&("number"==typeof e.minItems&&t.length<e.minItems&&i.push({path:s,message:`fewer than minItems ${e.minItems}`}),"number"==typeof e.maxItems&&t.length>e.maxItems&&i.push({path:s,message:`more than maxItems ${e.maxItems}`}))}(t,r,e,i),Array.isArray(t))r.items&&t.forEach((r,n)=>P(t[n],[...e,n],s,i));else if(null!==t&&"object"==typeof t){const n=Array.isArray(r.required)?r.required:[];for(const s of n)Object.hasOwn(t,s)&&void 0!==t[s]||i.push({path:[...e,s],message:"missing required property"});for(const n of function(t){return Object.keys(t)}(t)){!r.properties||n in r.properties||!1!==r.additionalProperties||i.push({path:[...e,n],message:"property is not declared by the Schema"}),P(t[n],[...e,n],s,i)}}}function T(t,e){return function(t,e){if(t===e)return!0;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}(t,e)||function(t,e){const s=L(t),i=L(e);return null!==s&&null!==i&&s===i}(t,e)}function L(t){if("number"==typeof t)return Number.isFinite(t)?String(t):null;if("string"!=typeof t)return null;const e=t.trim();if(!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e))return null;const s=Number(e);return Number.isFinite(s)?String(s):null}var M={date:/^\d{4}-\d{2}-\d{2}$/,"date-time":/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/,email:/^[^@\s]+@[^@\s]+\.[^@\s]+$/,uri:/^[a-z][a-z0-9+.-]*:\S*/i,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i};async function R(t,e,s={}){return(await _(t,e,s)).value}async function _(t,e,i={}){const r=e instanceof s?e:await s.create(e,i),n=t.trim();if(!1===i.locate||function(t){try{return JSON.parse(t),!0}catch{return!1}}(n)){const t=C(n,r,i),e=[...t.dropped,...t.leftover?[t.leftover]:[]];D(e,i);const s=[...t.flags];return S(t.value)&&s.push("schema-echo-detected"),{value:t.value,flags:s,errors:k(t.value,r),candidates:[],discarded:"ignore"===i.onDiscard?[]:e}}const o=p(n,r);if(0===o.length){const t=new a(r,i),e=t.parse(n),s=new Set(t.flags),o=[];null!==e&&"object"==typeof e&&s.add("implicit-structure");const h=t.remainder.trim();return h&&(s.add("trailing-chatter"),o.push(h)),D(o,i),{value:e,flags:[...s],errors:k(e,r),candidates:[],discarded:"ignore"===i.onDiscard?[]:o}}const h=o.map(t=>{const e=C(t.text,r,i),{score:s,flags:n}=w(e.value,r),o=k(e.value,r);return s.errors=o.length,S(t.text)&&n.push("schema-echo-detected"),{region:{...t,score:s},value:e.value,errors:o,read:e.flags,leftover:[...e.dropped,...e.leftover?[e.leftover]:[]],suspicion:n}}),{ordered:u,duplicates:c}=function(t,e){const s=new Set;if(t.length>1){const e=new Map;for(const s of t)e.set(J(s.value),s);for(const i of t)e.get(J(i.value))!==i&&s.add(i.region);t=t.filter(t=>!s.has(t.region))}if(t.length>1&&"throw"===e)throw new Error(`Found ${t.length} JSON candidates where one was expected: ${t.map((t,e)=>`#${e+1} ${JSON.stringify(t.region.text.slice(0,60))} {errors: ${t.region.score.errors}, requiredCovered: ${t.region.score.requiredCovered}}`).join("; ")}`);if("last"===e)return{ordered:[...t].sort((t,e)=>e.region.start-t.region.start),duplicates:s};if("first"===e)return{ordered:[...t].sort((t,e)=>t.region.start-e.region.start),duplicates:s};const i=[...t].sort((t,e)=>N(t.region.score,e.region.score)||e.region.start-t.region.start);return{ordered:i,duplicates:s}}(h,i.onMultiple??"best"),f=u[0],l=u.slice(1),d="best"===(i.onMultiple??"best")&&l.length>0&&0===N(f.region.score,l[0].region.score),{prose:m,fragments:g}=v(n,f.region,h.filter(t=>t!==f).map(t=>t.region)),y=new Set([...f.region.flags,...f.read]);m.some(t=>t.start<f.region.start)&&y.add("prose-prefix"),m.some(t=>t.start>=f.region.end)&&y.add("trailing-chatter"),l.length>0&&y.add("extra-fragments-dropped"),c.size>0&&y.add("duplicate-candidates"),d&&y.add("ambiguous-candidates");for(const t of h)for(const e of t.suspicion)y.add(e);const b=[...m.map(t=>t.text),...g,...f.leftover];return D(b,i),{value:f.value,flags:[...y],errors:f.errors,candidates:h.map(t=>t.region),discarded:"ignore"===i.onDiscard?[]:b}}function C(t,e,s){const i=new a(e,s);let r=i.parse(t);!1!==s.wrapArrays&&d(e)&&void 0!==r&&!Array.isArray(r)&&(r=[r]);const n=i.remainder.trim(),o=[...i.flags];return n&&!o.includes("dangling-dropped")&&o.push("unparsed-tail"),{value:r,flags:o,dropped:[...i.droppedText],leftover:n}}function D(t,e){if("throw"===e.onDiscard&&0!==t.length)throw new Error(`Repair discarded ${t.length} piece(s) of the input: ${JSON.stringify(t)}`)}function J(t){return JSON.stringify(t)??String(t)}export{a as RepairParser,s as SchemaWalker,N as compareScores,v as discardedText,d as expectsArrayRoot,m as findImplicitRecordRegion,R as jsonRepair,_ as jsonRepairResult,p as locateJsonCandidates,S as looksLikeSchemaEcho,E as renderValidatorErrors,w as scoreCandidate,k as validateValue};
|
package/docs/README.md
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
# @isdk/json-repair
|
|
6
6
|
|
|
7
7
|
> 【English|[中文](_media/README.cn.md)】
|
|
8
|
+
|
|
8
9
|
---
|
|
9
10
|
|
|
10
11
|
A powerful, schema-guided JSON repair library specifically designed to fix "broken" JSON generated by LLMs (Large Language Models).
|
|
@@ -34,7 +35,15 @@ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses you
|
|
|
34
35
|
- **Fuzzy Enum Matching**: Matches "Processing!" to `"processing"` if defined in Schema enums.
|
|
35
36
|
- **Noisy Number Extraction**: Extracts `1200.5` from `"Approx. 1,200.50 USD"`.
|
|
36
37
|
- **Boolean Variants**: Recognizes `yes/no`, `on/off`, `1/0`, `确定/取消` as booleans.
|
|
38
|
+
- **Declared Strings Stay Text**: `{ Population: 12 }` against `{ type: 'string' }` yields `"12"`, and the digits are taken from the document, so `{ id: 01234 }` yields `"01234"`.
|
|
37
39
|
- **Implicit Structure Support**: Automatically repairs missing braces in objects and arrays.
|
|
40
|
+
- **Escape-Faithful Strings**: a string the parser reads decodes exactly as `JSON.parse` does (`\n`, `\t`, `\/`, `\uXXXX`, surrogate pairs). JSON5-style `\xNN` decodes to the character it names, an escape of a character that never needs one is unwrapped (`"\$10"` → `"$10"`), and every escape strict JSON would reject is reported as `invalid-escape`. Set `escapes` when a backslash is content rather than an escape.
|
|
41
|
+
- **Robust Property Boundaries**: quoted keys may contain spaces and punctuation (`"Official language": "Italian"`), and a multi-word key the Schema declares is recognised even when the document leaves it unquoted; a value that parses cleanly is never re-tokenized, so valid JSON round-trips exactly like `JSON.parse`.
|
|
42
|
+
- **Fuzzy Key Matching**: `user_name`, `userName` and `USER NAME` resolve to the property your Schema declares, and the output carries the declared name.
|
|
43
|
+
- **Prototype-Safe Output**: keys such as `__proto__` or `constructor` are stored as own data properties, exactly as `JSON.parse` leaves them.
|
|
44
|
+
- **Locates the JSON First**: Markdown fences, `Sure! Here is the JSON:` preambles and trailing chatter are found and set aside — quote-aware, so a fence that lives _inside_ a string value survives.
|
|
45
|
+
- **Structure Is Split and Merged**: records written side by side under an `array` Schema become items; when a reply holds several fragments, the one that fits the Schema best wins.
|
|
46
|
+
- **Diagnostics, Not Only a Value**: `jsonRepairResult()` reports what it noticed (`flags`), what still fails (`errors`, ready to feed a retry), what it chose between (`candidates`) and what it threw away (`discarded`).
|
|
38
47
|
- **Performance**: Support for reusing `SchemaWalker` instances for high-throughput batch processing.
|
|
39
48
|
|
|
40
49
|
## 📦 Installation
|
|
@@ -52,21 +61,38 @@ pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
|
|
|
52
61
|
This is the most powerful way to use the library. Providing a schema enables advanced features like semantic coercion, greedy capture, and accurate disambiguation.
|
|
53
62
|
|
|
54
63
|
```typescript
|
|
55
|
-
import { jsonRepair } from '@isdk/json-repair'
|
|
64
|
+
import { jsonRepair } from '@isdk/json-repair'
|
|
56
65
|
|
|
57
66
|
const schema = {
|
|
58
67
|
type: 'object',
|
|
59
68
|
properties: {
|
|
60
69
|
query: { type: 'string' },
|
|
61
|
-
status: { enum: ['success', 'error'] }
|
|
62
|
-
}
|
|
63
|
-
}
|
|
70
|
+
status: { enum: ['success', 'error'] },
|
|
71
|
+
},
|
|
72
|
+
}
|
|
64
73
|
|
|
65
|
-
const brokenJson = '{ query: "python" OR "js", status: Success! }'
|
|
74
|
+
const brokenJson = '{ query: "python" OR "js", status: Success! }'
|
|
66
75
|
|
|
67
|
-
const result = await jsonRepair(brokenJson, schema)
|
|
68
|
-
console.log(result)
|
|
76
|
+
const result = await jsonRepair(brokenJson, schema)
|
|
77
|
+
console.log(result)
|
|
69
78
|
// Output: { query: '"python" OR "js"', status: 'success' }
|
|
79
|
+
|
|
80
|
+
// A multi-word key the Schema declares is found even when the document leaves it unquoted.
|
|
81
|
+
const countrySchema = {
|
|
82
|
+
type: 'object',
|
|
83
|
+
properties: {
|
|
84
|
+
Capital: { type: 'string' },
|
|
85
|
+
'Official language': { type: 'string' },
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
console.log(
|
|
90
|
+
await jsonRepair(
|
|
91
|
+
'{ Capital: Berlin, Official language: Italian }',
|
|
92
|
+
countrySchema
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
// Output: { Capital: 'Berlin', 'Official language': 'Italian' }
|
|
70
96
|
```
|
|
71
97
|
|
|
72
98
|
### 2. Simple Usage (Without Schema)
|
|
@@ -74,10 +100,16 @@ console.log(result);
|
|
|
74
100
|
For basic syntax repair where schema guidance isn't required:
|
|
75
101
|
|
|
76
102
|
```typescript
|
|
77
|
-
import { jsonRepair } from '@isdk/json-repair'
|
|
103
|
+
import { jsonRepair } from '@isdk/json-repair'
|
|
104
|
+
|
|
105
|
+
const result = await jsonRepair('{ name: John, age: 30 }')
|
|
106
|
+
console.log(result) // { name: 'John', age: 30 }
|
|
78
107
|
|
|
79
|
-
|
|
80
|
-
|
|
108
|
+
// Quoted keys may contain spaces and punctuation; valid JSON round-trips untouched.
|
|
109
|
+
const country = await jsonRepair(
|
|
110
|
+
'{ "Capital": "Berlin", "Official language": "Italian" }'
|
|
111
|
+
)
|
|
112
|
+
console.log(country) // { Capital: 'Berlin', 'Official language': 'Italian' }
|
|
81
113
|
```
|
|
82
114
|
|
|
83
115
|
### Advanced: Reusing SchemaWalker (Batch Processing)
|
|
@@ -85,23 +117,270 @@ console.log(result); // { name: 'John', age: 30 }
|
|
|
85
117
|
For better performance when processing many items with the same schema:
|
|
86
118
|
|
|
87
119
|
```typescript
|
|
88
|
-
import { jsonRepair, SchemaWalker } from '@isdk/json-repair'
|
|
120
|
+
import { jsonRepair, SchemaWalker } from '@isdk/json-repair'
|
|
89
121
|
|
|
90
|
-
|
|
122
|
+
// Options that concern the Schema itself (`keyMatching`) belong to the walker.
|
|
123
|
+
const walker = await SchemaWalker.create(mySchema, { keyMatching: true })
|
|
91
124
|
|
|
92
125
|
for (const item of brokenItems) {
|
|
93
|
-
const result = await jsonRepair(item, walker)
|
|
126
|
+
const result = await jsonRepair(item, walker)
|
|
94
127
|
// ...
|
|
95
128
|
}
|
|
96
129
|
```
|
|
97
130
|
|
|
131
|
+
## 🧭 Where the JSON Starts
|
|
132
|
+
|
|
133
|
+
A model's reply is text, not a document. It wraps the JSON in a fence, and dresses it up in
|
|
134
|
+
sentences. `jsonRepair` finds the JSON first, then repairs it:
|
|
135
|
+
|
|
136
|
+
````typescript
|
|
137
|
+
await jsonRepair('```json\n{ name: Ada }\n```', schema)
|
|
138
|
+
// { name: 'Ada' } flags: ['markdown-fence']
|
|
139
|
+
|
|
140
|
+
await jsonRepair('```json\n{ name: Ada }\n```\nHope this helps!', schema)
|
|
141
|
+
// { name: 'Ada' } flags: ['markdown-fence', 'prose-prefix', 'trailing-chatter']
|
|
142
|
+
|
|
143
|
+
await jsonRepair('Here you go:\nname: Ada', schema)
|
|
144
|
+
// { name: 'Ada' } flags: ['prose-prefix', 'implicit-structure']
|
|
145
|
+
````
|
|
146
|
+
|
|
147
|
+
- The scan is quote-aware and bracket-aware, so `{ "code": "```json\n{}\n```" }` keeps its
|
|
148
|
+
content intact. A regular expression that strips fences would hand you `{}` instead.
|
|
149
|
+
- Input that already parses as JSON is never relocated, which is what keeps valid JSON
|
|
150
|
+
round-tripping exactly like `JSON.parse`.
|
|
151
|
+
- Everything the locating step threw away — wrapper prose, fences, losing fragments — is
|
|
152
|
+
listed in `discarded`. `onDiscard: 'throw'` refuses a repair that discards anything, for
|
|
153
|
+
callers that cannot afford to lose content. What a coercion gives up from inside a value is
|
|
154
|
+
reported by a flag, and follows the rule described under
|
|
155
|
+
[Known Limitations](#-known-limitations--disambiguation).
|
|
156
|
+
|
|
157
|
+
### More than one fragment
|
|
158
|
+
|
|
159
|
+
A reply often holds several JSON fragments: a draft and a final answer, a decoy, or records laid
|
|
160
|
+
out side by side where the Schema expects an array. The Schema says which one to keep, so it is a
|
|
161
|
+
measurement rather than a guess. Fragments are ranked by:
|
|
162
|
+
|
|
163
|
+
| Compared first | Then |
|
|
164
|
+
| --- | --- |
|
|
165
|
+
| fewer Schema violations (`errors`) | more `required` fields carrying a real value (`""` carries nothing) |
|
|
166
|
+
| more declared fields carrying a real value | fewer JSON Schema keywords reproduced into the answer (`schemaEchoKeys`) |
|
|
167
|
+
|
|
168
|
+
A tie is decided by position — the **last** fragment first, because a model normally drafts
|
|
169
|
+
before it answers — and is reported as `ambiguous-candidates` instead of being hidden.
|
|
170
|
+
`onMultiple` changes the policy to `'first'`, `'last'`, or `'throw'`. Without a Schema the
|
|
171
|
+
ranking has no information to work with, so it collapses to the position rule; say so in your
|
|
172
|
+
own logs if that matters to you.
|
|
173
|
+
|
|
174
|
+
Records sitting side by side under an `array` Schema — `{"name": "Noah"} {"name": "Ada"}`, or the
|
|
175
|
+
same records without any braces — are read as one document holding two items
|
|
176
|
+
(`sibling-objects-merged`). The structure was declared, so that is not a guess either.
|
|
177
|
+
|
|
178
|
+
### Auditing the repair: valid is not correct
|
|
179
|
+
|
|
180
|
+
A value can satisfy the Schema and still say nothing: `"name": ""`, a placeholder phone number,
|
|
181
|
+
the first enum entry picked by default. `jsonRepairResult()` returns what it noticed along with
|
|
182
|
+
the value:
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
185
|
+
import { jsonRepairResult, renderValidatorErrors } from '@isdk/json-repair'
|
|
186
|
+
|
|
187
|
+
const { value, errors, flags, candidates, discarded } = await jsonRepairResult(
|
|
188
|
+
reply,
|
|
189
|
+
schema
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
flags
|
|
193
|
+
// ['markdown-fence', 'prose-prefix', 'empty-required']
|
|
194
|
+
errors
|
|
195
|
+
// [{ path: ['email'], message: 'missing required property' }]
|
|
196
|
+
|
|
197
|
+
renderValidatorErrors(errors, 6)
|
|
198
|
+
// - email: missing required property
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`errors` is what a retry prompt needs, and `renderValidatorErrors` keeps it to the few lines a
|
|
202
|
+
small model actually follows. Repair first, then retry: syntax, type and structure are settled
|
|
203
|
+
deterministically and cost nothing, so a second model call is spent only on what no code can
|
|
204
|
+
know — an answer that is well formed and wrong.
|
|
205
|
+
|
|
206
|
+
A retry cannot see a placeholder either. `"name": ""` satisfies the Schema, and a model asked to
|
|
207
|
+
fix an error it does not have writes the placeholder again, so the repair names it:
|
|
208
|
+
`empty-required` (a required string left empty), `schema-echo-detected` (the Schema copied back as the answer, even when the copy
|
|
209
|
+
parses perfectly), `ambiguous-candidates` (two fragments that fit equally well), `coerced-text-dropped` (a coercion kept part of a value and gave up the text around it). Every decision the
|
|
210
|
+
repair made is in `flags` — the full list is `RepairFlag` in the API docs — so accepting,
|
|
211
|
+
retrying or escalating is a decision made on evidence, not on "it parsed".
|
|
212
|
+
|
|
213
|
+
## 🧭 How Property Boundaries Are Detected
|
|
214
|
+
|
|
215
|
+
While repairing a value, the parser must decide at every position whether an upcoming
|
|
216
|
+
`"foo":` starts the **next property** or is just part of the **current value**. It uses two modes:
|
|
217
|
+
|
|
218
|
+
1. **Structural mode** — applies right after a value was parsed by the strict JSON path
|
|
219
|
+
(a balanced `"string"`, a well-formed number, `true`/`false`/`null`).
|
|
220
|
+
Any key-shaped token followed by `:` counts as the next property, _including quoted keys
|
|
221
|
+
that contain whitespace or punctuation_ (`"Official language":`, `"a, b":`, `"a: b":`).
|
|
222
|
+
A successful strict parse is **never** discarded, which is why valid JSON always yields
|
|
223
|
+
exactly what `JSON.parse` would return.
|
|
224
|
+
2. **Greedy mode** — applies when the value could not be parsed strictly (unquoted text,
|
|
225
|
+
unescaped inner quotes, `"A" OR "B"` expressions, DSL snippets such as `@func(a="x, y")`).
|
|
226
|
+
- If the Schema declares property names for the current level, capture stops **only at a
|
|
227
|
+
declared key**. Text that merely looks like a key stays inside the value:
|
|
228
|
+
`{ "query": he said "hello there": loudly, "intent": "x" }` keeps
|
|
229
|
+
`query = 'he said "hello there": loudly'`.
|
|
230
|
+
- If the Schema declares no property names for that level (no schema, `type: "object"`
|
|
231
|
+
without `properties`, or only `additionalProperties`), the parser falls back to
|
|
232
|
+
“the first key-shaped token ends the value”.
|
|
233
|
+
- A **declared** name is additionally searched for literally, so it is a breakpoint (and a key)
|
|
234
|
+
even when the document left it unquoted and it contains whitespace. The generic key scanner
|
|
235
|
+
cannot see a bare `Official language:` as one key — the Schema can:
|
|
236
|
+
`{ Capital: Berlin, Official language: Italian }` yields
|
|
237
|
+
`{ Capital: 'Berlin', 'Official language': 'Italian' }`. Under `keyMatching`, separator and
|
|
238
|
+
case variants of a declared key (`user_name` for `userName`) end a value too.
|
|
239
|
+
|
|
240
|
+
Set `stringCaptureStrategy: 'conservative'` to make greedy mode stop at _any_ key-shaped
|
|
241
|
+
token, whatever the Schema declares (see [Repair Options](#-repair-options)).
|
|
242
|
+
|
|
243
|
+
### Thinking about the heuristic
|
|
244
|
+
|
|
245
|
+
Ambiguity is missing information, not magic: `{ "note": see "foo bar": baz here, "b": 2 }`
|
|
246
|
+
cannot be decided without a schema, because both readings are plausible. The principles the
|
|
247
|
+
parser follows are:
|
|
248
|
+
|
|
249
|
+
- A **cleanly parsed** value is trusted; whatever follows it is assumed to be structure.
|
|
250
|
+
- A **messy** value is preserved as text whenever the Schema can name the real anchors.
|
|
251
|
+
- A name the Schema **declares** is matched literally, so a multi-word key does not need quotes in the document to be recognised; a multi-word name the Schema does not declare is never treated as a key.
|
|
252
|
+
- Consequently, **declaring the `properties` of the current level is the single most effective
|
|
253
|
+
way to steer the repair** — declared keys act as breakpoints for greedy capture, and
|
|
254
|
+
declared `type`/`enum` enable semantic coercion.
|
|
255
|
+
- A level counts as an object when the Schema declares `properties` or `type: 'object'`, so
|
|
256
|
+
omitting `type: 'object'` does not degrade a brace-less document into a scalar value.
|
|
257
|
+
- If a value may legitimately contain `word:` or `"phrase":`, prefer having the model emit
|
|
258
|
+
properly escaped JSON (then the strict parse wins outright), or declare that level's
|
|
259
|
+
properties in the Schema.
|
|
260
|
+
- If a value looks truncated right at something key-shaped, that level is probably missing
|
|
261
|
+
`properties` in your Schema — add them and re-run.
|
|
262
|
+
|
|
263
|
+
A value that stops at a quote the model never closed is the other ambiguous case:
|
|
264
|
+
`{"t": "The "Best" Paper", "y": 2020}`. By default (`unescapedQuotes: 'keep'`) it keeps the
|
|
265
|
+
delimiters the document spelled. `'declared'` ends it at the first quote after which a member
|
|
266
|
+
the Schema declares begins — the declared member is the anchor, so the boundary is read rather
|
|
267
|
+
than guessed. `'lookahead'` applies the same rule to the text alone, for documents with no
|
|
268
|
+
Schema.
|
|
269
|
+
|
|
270
|
+
Numeric literals support scientific notation (`1e5`, `-2E2`) as well as the lax LLM forms
|
|
271
|
+
`+5`, `.5` and `5.`. A partial literal such as `1.2.3` is kept as a string and then coerced
|
|
272
|
+
according to the Schema.
|
|
273
|
+
|
|
274
|
+
A declared `type: 'string'` is honoured in the other direction too: `12` becomes `"12"`, and
|
|
275
|
+
because the text comes from the document rather than the parsed number, a leading zero
|
|
276
|
+
survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never stringified.
|
|
277
|
+
|
|
278
|
+
### How Escapes Are Read
|
|
279
|
+
|
|
280
|
+
Escapes are decoded, not guessed:
|
|
281
|
+
|
|
282
|
+
| The document writes | The value contains |
|
|
283
|
+
| --- | --- |
|
|
284
|
+
| `"a\nb"`, `"\t"`, `"\/"` | the control character, `/` — exactly what `JSON.parse` yields |
|
|
285
|
+
| `"café"`, `"\ud83d\ude00"` | `é`, `😀`; an unpaired surrogate stays where `JSON.parse` puts it |
|
|
286
|
+
| `"\xa0"` (the JSON5-style hex escape) | the character U+00A0 |
|
|
287
|
+
| `"\$10"`, `"a\qb"` (an escape of a character that needs none) | `$10`, `aqb` |
|
|
288
|
+
| `note: first line\nsecond` (a captured, unquoted value) | the text as written, backslash included — greedy capture does not decode |
|
|
289
|
+
|
|
290
|
+
Decoding stops at decoding. An NBSP, a zero-width space or a smart quote that the document
|
|
291
|
+
wrote stays in the value: rewriting those would change the model's content, not its syntax.
|
|
292
|
+
|
|
293
|
+
An escape strict JSON would reject is always reported as `invalid-escape`, whatever is done
|
|
294
|
+
with it: a value gained or lost a backslash, and the caller is owed that information.
|
|
295
|
+
`escapes` decides how far a backslash is trusted:
|
|
296
|
+
|
|
297
|
+
| `escapes` | `"\$10"` | `"C:\Users"` | `"C:\temp"` | `"\x41"` | `"a\nb"` |
|
|
298
|
+
| --- | --- | --- | --- | --- | --- |
|
|
299
|
+
| `'json5'` (default) | `$10` | `C:Users` | `C:`, tab, `emp` | `A` | a newline |
|
|
300
|
+
| `'json'` | `\$10` | `C:\Users` | `C:`, tab, `emp` | `\x41` | a newline |
|
|
301
|
+
| `'raw'` | `\$10` | `C:\Users` | `C:\temp` | `\x41` | `\n` — two characters |
|
|
302
|
+
|
|
303
|
+
`'json'` repairs only the syntax it is sure of and leaves every escape JSON does not define as
|
|
304
|
+
the document wrote it, which is what markdown- and LaTeX-trained models write. `'raw'` treats
|
|
305
|
+
every backslash as content, which is what a document of Windows paths, regular expressions or
|
|
306
|
+
LaTeX wants (`"C:\temp"` is a path, not a tab; `"\frac{a}{b}"` is a command, not a form feed)
|
|
307
|
+
at the price it names: no value can carry a newline any more.
|
|
308
|
+
|
|
309
|
+
A backslash stays structural at every setting — it is always the reason the character behind it
|
|
310
|
+
remains inside the string — so the choice cannot change where a value ends. An incomplete hex
|
|
311
|
+
escape (`"\xg"`, `"\uZZ"`) decodes nothing in every setting and is left exactly as written.
|
|
312
|
+
|
|
98
313
|
## ⚠️ Known Limitations & Disambiguation
|
|
99
314
|
|
|
100
315
|
- **The "Parity Rule"**: When a string is wrapped in quotes and contains internal quotes, we count the internal ones.
|
|
101
316
|
- Odd count (e.g., `"a"b"`): We assume the outer quotes are delimiters -> `a"b`.
|
|
102
317
|
- Even count (e.g., `"A" OR "B"`): We assume the outer quotes are part of the expression -> `"A" OR "B"`.
|
|
103
318
|
- **Limitation**: Highly unusual patterns like `"a"b"c"` might remain ambiguous.
|
|
104
|
-
- **
|
|
319
|
+
- **Key-shaped text inside a broken value (no schema guidance)**: when the Schema declares no property names for the current level, the first key-shaped token ends the value.
|
|
320
|
+
`{ "note": see "foo bar": baz here, "b": 2 }` without a schema is therefore read as `{ note: 'see', 'foo bar': 'baz here', b: 2 }`. Declaring that level's `properties` makes greedy capture stop only at real keys and restores `{ note: 'see "foo bar": baz here', b: 2 }` (see [Thinking about the heuristic](#thinking-about-the-heuristic)).
|
|
321
|
+
- **Unquoted multi-word keys need a declaration.** `{ Capital: Berlin, Official language: Italian }` becomes two properties because the Schema declares `Official language`. A spaced key that is _not_ declared is not a key: `{ Capital: Berlin, Official Lang: Italian }` keeps the whole text in `Capital` under the default `'aggressive'` strategy, and splits at the space (`{ Capital: 'Berlin, Official', Lang: 'Italian' }`) under `'conservative'`.
|
|
322
|
+
- **Prose that repeats a declared key is cut there.** Declared keys are breakpoints, so `{ summary: the Official language: Italian is wrong, Official language: Italian }` reads `summary = 'the'`. If a value may legitimately repeat a declared key, have the model quote its keys or pick a less colliding property name.
|
|
323
|
+
- **A backslash that was meant as a path separator cannot be recognised as one.** `{ "path": "C:\new\test" }` really does contain the escapes `\n` and `\t`, so the default reads `C:`, a newline, `ew`, a tab and `est`; only `"C:\\new\\test"` is a Windows path, and no repairer can tell the two apart, so we do not guess. What you can choose is how much a backslash is trusted: `escapes: 'json'` keeps an escape JSON does not define (`"C:\Users"` stays `C:\Users`), and `escapes: 'raw'` keeps every backslash, which is the only setting that survives `C:\temp` intact — at the cost of `"\n"` no longer being a newline. Either way `invalid-escape` says the document contained one.
|
|
324
|
+
- **Trailing prose after a record that has no braces is kept**: `Here you go:\nname: Ada\nHope this helps!` yields `name = 'Ada\nHope this helps!'`. A brace-less value can only be cut where the Schema names the next key — a `city:` after it would cut, a sentence after it cannot be known to be prose.
|
|
325
|
+
- **A number coercion cuts a value where the number ends.** `{ "age": 30 more words }` reads `age = 30`: the value keeps the first well-formed numeric token and gives up the text around it, which is what makes `约 1,200.50 元` read as `1200.5`. Greedy capture can run a value into the prose a model wrote after it (`{ age: 30\n\nHope this helps!}`), so what the coercion gave up is reported: `coerced-text-dropped` always, and the text itself in `RepairResult.discarded` when it reads as a sentence rather than as a qualifier — three words, or twenty characters with no space to count them by. `Approx. USD` stays out of `discarded`; `Hope this helps!` does not.
|
|
326
|
+
- **Fences and prose are located, not rewritten**: the wrapper text around the JSON is dropped and listed in `RepairResult.discarded`. Set `locate: false` to treat the whole string as one JSON document — nothing is located, so the locating step discards nothing (a coercion that gives up a sentence still says so).
|
|
327
|
+
- **Nesting deeper than 1000 levels stops the parse.** A document written `{"a": {"a": …` thousands deep is a model caught in a loop rather than a document worth reading, and walking it recursively would end in a stack overflow instead of an answer. The parser closes what it opened, flags `nesting-limited`, and lists the text it never read in `discarded`.
|
|
328
|
+
|
|
329
|
+
## ⚙️ Repair Options
|
|
330
|
+
|
|
331
|
+
`jsonRepair(input, schema, options)` takes a fourth argument of type `RepairOptions`:
|
|
332
|
+
|
|
333
|
+
| Option | Default | What it does |
|
|
334
|
+
| --- | --- | --- |
|
|
335
|
+
| `coerceTypes` | `true` | Converts a value to the type the Schema declares: `"Approx. 1,200.50 USD"` → `1200.5`, `"yes"` → `true`, `"Processing!"` → `"processing"` when the enum says so, `12` → `"12"` under `type: 'string'` (the digits come from the document, so `{ id: 01234 }` → `"01234"`). `null` and structures are never stringified. A coercion that gives up text around the value it keeps flags `coerced-text-dropped`; text long enough to read as a sentence, rather than as a unit, is listed in `discarded` too. |
|
|
336
|
+
| `keyMatching` | `false` | Resolves incoming keys to the names the Schema declares. `true` ignores case and separators, so `user_name`, `userName` and `USER NAME` all match `userName`; a function `(key, properties) => string \| undefined` decides itself (`undefined` keeps the key as it is). A match renames the key in the output, which also re-enables coercion for that subtree. With `true` it also decides where greedy capture stops: `user_name:` ends a value when the Schema declares `userName`. |
|
|
337
|
+
| `additionalProperties` | `'keep'` | `'remove'` drops keys the Schema does not declare. Applied only at levels that do declare `properties` — a free-form level has no “extra” keys and is left untouched. Independent of the JSON Schema keyword `additionalProperties: false`, which is honoured on its own. |
|
|
338
|
+
| `stringCaptureStrategy` | `'aggressive'` | `'conservative'` ends greedy capture at any key-shaped token instead of only at declared Schema keys: less risk of one broken value swallowing the rest of the document, at the cost of cutting values short. |
|
|
339
|
+
| `locate` | `true` | Whether to look for the JSON inside the text first (fences, prose, several fragments). `false` treats the whole string as one JSON document - the behaviour up to 0.1.x. Input that already parses is never relocated either way. |
|
|
340
|
+
| `onMultiple` | `'best'` | How to choose when the text holds more than one fragment: `'best'` ranks them by how well they fit the Schema and takes the winner (ties go to the last fragment, reported as `ambiguous-candidates`); `'last'` / `'first'` ignore the ranking; `'throw'` rejects the input and lists the fragments with their scores. |
|
|
341
|
+
| `onDiscard` | `'report'` | `'throw'` refuses a repair that had to drop prose, a losing fragment, or a sentence a value had swallowed; `'ignore'` drops them without listing them in `RepairResult.discarded`. |
|
|
342
|
+
| `wrapArrays` | `true` | Whether a record the Schema expects inside a list is read as an item: `{ name: Ada }` under an array Schema becomes `[{ name: 'Ada' }]`, and sibling records written side by side become the items. `false` keeps what the document wrote, at the cost of the record's keys no longer being resolved against `items` (no coercion, values can run together). |
|
|
343
|
+
| `dangling` | `true` | Drops a key or separator the output was cut off at (`{"a": 1, "b"` → `{ a: 1 }`), listing the fragment in `discarded` and flagging `dangling-dropped`. `false` keeps the fragment inside the field in front of it. Dropping does not stop the parse: a record written after the closing brace is still read, so `{"a": 1, "b"} {"c": 2}` becomes `[{ a: 1 }, { c: 2 }]`. |
|
|
344
|
+
| `literals` | `true` | Which bare tokens are read as a literal of another language: `'python'` (`True`/`False`/`None`), `'js'` (`undefined`), `true` for both, `false` or `[]` for neither. A Schema that names a type at the path outranks it, and a quoted `"True"` is always a string. |
|
|
345
|
+
| `comments` | `false` | Which comment styles are skipped between members: `'line'` (`//`), `'block'` (`/* */`, only when closed), `'hash'` (`#`), `true` for all three. Never read inside a string or a bare token, so `https://x` and `#123` are safe at every setting; nor is one read where a value belongs - after a `:` the text is the model's, comment-shaped or not, and can end up inside the value. When one does, the repair flags `comment-in-value`. |
|
|
346
|
+
| `unescapedQuotes` | `'keep'` | Where a quoted value ends when the model left a quote unescaped: `'declared'` uses a Schema-declared member after the quote as the anchor, `'lookahead'` judges by the text alone. `'keep'` infers nothing. |
|
|
347
|
+
| `escapes` | `'json5'` | How much a backslash is trusted. `'json5'` decodes JSON's escapes plus `\xNN` and unwraps the rest (`"\$10"` → `$10`); `'json'` leaves anything JSON does not define as written (`"C:\Users"` → `C:\Users`); `'raw'` decodes nothing, so paths, regular expressions and LaTeX survive whole and `"\n"` is two characters. A backslash is structural in all three, and an escape strict JSON rejects raises `invalid-escape`. |
|
|
348
|
+
|
|
349
|
+
```typescript
|
|
350
|
+
const schema = {
|
|
351
|
+
type: 'object',
|
|
352
|
+
properties: {
|
|
353
|
+
userName: { type: 'string' },
|
|
354
|
+
userAge: { type: 'number' },
|
|
355
|
+
},
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
|
|
359
|
+
keyMatching: true,
|
|
360
|
+
coerceTypes: true,
|
|
361
|
+
})
|
|
362
|
+
// { userName: 'Ada', userAge: 36 }
|
|
363
|
+
|
|
364
|
+
await jsonRepair('{ userName: "Ada", reasoning: "let me think…" }', schema, {
|
|
365
|
+
additionalProperties: 'remove',
|
|
366
|
+
})
|
|
367
|
+
// { userName: 'Ada' }
|
|
368
|
+
|
|
369
|
+
const querySchema = {
|
|
370
|
+
type: 'object',
|
|
371
|
+
properties: { query: { type: 'string' }, intent: { type: 'string' } },
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
await jsonRepair(
|
|
375
|
+
'{ "query": he said "hello there": loudly, "intent": "x" }',
|
|
376
|
+
querySchema,
|
|
377
|
+
{ stringCaptureStrategy: 'conservative' }
|
|
378
|
+
)
|
|
379
|
+
// { query: 'he said', 'hello there': 'loudly', intent: 'x' }
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
`keyMatching` is read from the options passed to `SchemaWalker.create()` when you reuse a
|
|
383
|
+
walker; the other options are read on every `jsonRepair()` call.
|
|
105
384
|
|
|
106
385
|
## 📄 License
|
|
107
386
|
|