@isdk/json-repair 0.1.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -9
- package/README.cn.md +143 -9
- package/README.md +181 -12
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +828 -41
- package/dist/index.d.ts +828 -41
- package/dist/index.js +1 -1
- package/package.json +30 -7
- package/.prettierignore +0 -12
- package/.prettierrc +0 -8
- package/.versionrc +0 -36
- package/TODO +0 -0
- package/docs/README.md +0 -246
- package/docs/_media/README.cn.md +0 -214
- package/docs/classes/RepairParser.md +0 -64
- package/docs/classes/SchemaWalker.md +0 -241
- package/docs/functions/jsonRepair.md +0 -48
- package/docs/globals.md +0 -24
- package/docs/interfaces/RepairOptions.md +0 -96
- package/docs/type-aliases/JSONPath.md +0 -14
- package/eslint.config.mjs +0 -65
- package/setupVitest.mjs +0 -15
- package/tsconfig.json +0 -20
- package/tsconfig.release.json +0 -21
- package/tsup.config.ts +0 -38
- package/typedoc.config.cjs +0 -9
- package/vite.config.mjs +0 -21
package/dist/index.d.ts
CHANGED
|
@@ -3,22 +3,26 @@
|
|
|
3
3
|
*/
|
|
4
4
|
interface RepairOptions {
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
6
|
+
* Which spellings of a declared property name the document may use.
|
|
7
7
|
*
|
|
8
8
|
* - `false` (default): Only an exactly declared key counts as a match.
|
|
9
|
-
* - `true`:
|
|
10
|
-
* `
|
|
9
|
+
* - `true`: every form on - case- and separator-insensitive, so `user_name`, `userName`,
|
|
10
|
+
* `USER-NAME` and `user name` all resolve to the declared key.
|
|
11
|
+
* - `KeyMatchSpec`: names the forms one by one (`{ forms: ['case'] }`), the separator
|
|
12
|
+
* characters, and the alternative names the Schema declares under another keyword
|
|
13
|
+
* (`aliases`) - a caller that owns its own key grammar passes that grammar here rather
|
|
14
|
+
* than inheriting this library's.
|
|
11
15
|
* - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic;
|
|
12
16
|
* it receives the incoming key and the declared names, and returns the name to use
|
|
13
17
|
* (or `undefined` to fall back to the incoming key).
|
|
14
18
|
*
|
|
15
19
|
* A match renames the key to the Schema's name in the output and makes nested Schema
|
|
16
20
|
* lookups (and therefore type coercion) work for it.
|
|
17
|
-
* It also decides where greedy capture stops:
|
|
18
|
-
*
|
|
21
|
+
* It also decides where greedy capture stops: a selected form makes the variant of a declared
|
|
22
|
+
* key (`user_name:` for `userName`) end the value in front of it.
|
|
19
23
|
* When you reuse a `SchemaWalker`, pass this option to `SchemaWalker.create()`.
|
|
20
24
|
*/
|
|
21
|
-
keyMatching?: boolean | ((key: string, properties: string[]) => string | undefined);
|
|
25
|
+
keyMatching?: boolean | KeyMatchSpec | ((key: string, properties: string[]) => string | undefined);
|
|
22
26
|
/**
|
|
23
27
|
* Strategy for greedy string capture when the strict JSON path failed for a value.
|
|
24
28
|
*
|
|
@@ -50,53 +54,495 @@ interface RepairOptions {
|
|
|
50
54
|
* parsed to, so a leading zero survives: `{ id: 01234 }` becomes `"01234"`.
|
|
51
55
|
* `null` and structures (`{}` / `[]`) are never stringified - `"null"` and
|
|
52
56
|
* `"[object Object]"` are not what a `type: 'string'` declaration asks for.
|
|
57
|
+
*
|
|
58
|
+
* A coercion that keeps part of a value and gives up the text around it says so:
|
|
59
|
+
* `coerced-text-dropped`. A unit given up that way (`Approx. USD`) is the option doing its
|
|
60
|
+
* job; text long enough to read as a sentence is listed in {@link RepairResult.discarded}
|
|
61
|
+
* too, because greedy capture can run a value into prose the model wrote after it
|
|
62
|
+
* (`age: 30\n\nHope this helps!}` -> `30`) and the sentence would otherwise leave no trace.
|
|
53
63
|
*/
|
|
54
64
|
coerceTypes?: boolean;
|
|
55
65
|
/**
|
|
56
|
-
*
|
|
66
|
+
* The JSON Schema keyword `additionalProperties`, given as the default for every level that
|
|
67
|
+
* does not state it itself. One keyword, one rule: a Schema that writes
|
|
68
|
+
* `additionalProperties: false` on a level needs no option for that level to obey it, and a
|
|
69
|
+
* level that writes its own outranks the default here.
|
|
70
|
+
*
|
|
71
|
+
* - `true` (the default, and what JSON Schema assumes): keys the level does not declare are
|
|
72
|
+
* kept in the output.
|
|
73
|
+
* - `false`: such keys are dropped, listed in {@link RepairResult.discarded} and flagged
|
|
74
|
+
* `undeclared-keys-dropped`, so the value fits the Schema without content going missing.
|
|
75
|
+
* - a Schema (e.g. `{ type: 'string' }`): such keys are kept, and their values are coerced
|
|
76
|
+
* and validated against that Schema - the way to describe a free-form map (`labels`,
|
|
77
|
+
* `counts`) once instead of at every level.
|
|
78
|
+
*
|
|
79
|
+
* Dropping applies only at a level that declares `properties`. A level that declares none
|
|
80
|
+
* (`type: 'object'` alone, or no Schema at all) is free-form: it has no "extra" keys, and
|
|
81
|
+
* emptying it would destroy the answer rather than tighten it.
|
|
82
|
+
*/
|
|
83
|
+
additionalProperties?: boolean | object;
|
|
84
|
+
/**
|
|
85
|
+
* Where a quoted value ends when the model left one of its quotes unescaped -
|
|
86
|
+
* `{"t": "The "Best" Paper", "y": 2020}`.
|
|
87
|
+
*
|
|
88
|
+
* - `'keep'` (default) - what the document spells, delimiters included:
|
|
89
|
+
* `t = '"The "Best" Paper"'`. Nothing is inferred, which is the rule the README section
|
|
90
|
+
* "How Property Boundaries Are Detected" describes.
|
|
91
|
+
* - `'declared'` - the first quote after which a member the Schema declares begins:
|
|
92
|
+
* `t = 'The "Best" Paper'`. The Schema named that member, so the boundary is known rather
|
|
93
|
+
* than guessed - and where the Schema names nothing at that level, nothing is inferred
|
|
94
|
+
* either.
|
|
95
|
+
* - `'lookahead'` - the same rule judged by the shape of the text alone, for documents with
|
|
96
|
+
* no Schema. It reads more, and guesses more.
|
|
97
|
+
*
|
|
98
|
+
* A document that `JSON.parse` accepts is never affected: the strict parse is tried first,
|
|
99
|
+
* and only a quoted value it could not close comes here. Emits `unescaped-quote-inferred`.
|
|
100
|
+
*/
|
|
101
|
+
unescapedQuotes?: 'keep' | 'declared' | 'lookahead';
|
|
102
|
+
/**
|
|
103
|
+
* Which comment styles are skipped, and only where a member is expected: between two
|
|
104
|
+
* fields, after `{` or `[`, before a closing bracket, and after a completed value.
|
|
105
|
+
*
|
|
106
|
+
* Strict JSON has no comments, so this is off by default - skipping one consumes
|
|
107
|
+
* characters, and only the caller knows which style its models write. Open the style you
|
|
108
|
+
* actually see.
|
|
109
|
+
*
|
|
110
|
+
* - `'line'` - `//` to the end of the line (JSONC, and most JavaScript-trained models).
|
|
111
|
+
* - `'block'` - `/* ... *\/`, and only when it is closed: an unterminated `/*` stays text.
|
|
112
|
+
* - `'hash'` - `#` to the end of the line (Python-trained models).
|
|
113
|
+
* - `true` - all three. `false` or `[]` - none, which is the default.
|
|
114
|
+
*
|
|
115
|
+
* A style is never recognised inside a string or inside a bare token, so
|
|
116
|
+
* `url: https://x.com/a`, `issue: #123` and `"#ff0000"` survive every setting. With the
|
|
117
|
+
* default, a comment written between two fields ends up inside one of them; turning the
|
|
118
|
+
* switch on is what prevents that. Emits `comment-skipped`.
|
|
119
|
+
*/
|
|
120
|
+
comments?: boolean | CommentStyle[];
|
|
121
|
+
/**
|
|
122
|
+
* Which bare tokens (tokens with no quotes around them) are read as a literal of another
|
|
123
|
+
* language.
|
|
124
|
+
*
|
|
125
|
+
* `ok: True` means `true`, not the word `True`: the token carries no quotes, so it is not a
|
|
126
|
+
* string in any JSON dialect either - reading it as a literal is reading the model, while
|
|
127
|
+
* turning it into `'True'` invents a value.
|
|
128
|
+
*
|
|
129
|
+
* - `'python'` - `True` -> `true`, `False` -> `false`, `None` -> `null`.
|
|
130
|
+
* - `'js'` - `undefined` -> `null`. `NaN` is left as the text it spells: no JSON number
|
|
131
|
+
* can carry it, so the reported errors point at the field instead of the parser inventing
|
|
132
|
+
* a value that cannot be serialised.
|
|
133
|
+
* - `true` - both dialects, which is the default. `false` or `[]` - neither: the token
|
|
134
|
+
* becomes the string it spells.
|
|
135
|
+
*
|
|
136
|
+
* A model trained on JavaScript does not write `None` and a Python-trained one rarely writes
|
|
137
|
+
* `undefined`, so the list is how you say which of them can occur. It never applies to a
|
|
138
|
+
* quoted `"True"` (always a string), never to a key, and never to a path whose Schema names
|
|
139
|
+
* a type - there {@link coerceTypes} decides, and it already reads `True` as `true`.
|
|
140
|
+
* Emits `non-json-literal`.
|
|
141
|
+
*/
|
|
142
|
+
literals?: boolean | LiteralDialect[];
|
|
143
|
+
/**
|
|
144
|
+
* How much the parser trusts the backslashes a document writes.
|
|
145
|
+
*
|
|
146
|
+
* The three settings read as one axis - how far the document's escapes are escapes:
|
|
147
|
+
*
|
|
148
|
+
* - `'json5'` (default): JSON's own escapes decode, the JSON5-style `\xNN` decodes to the
|
|
149
|
+
* character it names, and an escape of a character that needs none is unwrapped
|
|
150
|
+
* (`"\$10"` -> `$10`, `"C:\Users"` -> `C:Users`) the way JSON5 reads one.
|
|
151
|
+
* - `'json'`: only the escapes JSON defines decode. Anything else stays exactly as the
|
|
152
|
+
* document wrote it, backslash included (`"C:\Users"` -> `C:\Users`), so markdown and
|
|
153
|
+
* LaTeX punctuation keeps its backslashes and a path keeps its separators.
|
|
154
|
+
* - `'raw'`: nothing decodes - a backslash is content. `"C:\temp"` is a path, not a tab,
|
|
155
|
+
* and `"\frac{a}{b}"` is a LaTeX command, not a form feed. The setting is honest about
|
|
156
|
+
* what it costs: it applies to escapes JSON defines too, so `"a\nb"` stays two characters
|
|
157
|
+
* and a value can no longer carry a newline. Use it when the values are paths, regular
|
|
158
|
+
* expressions or markup rather than prose.
|
|
159
|
+
*
|
|
160
|
+
* A backslash is structural in every setting: it always keeps the character behind it inside
|
|
161
|
+
* the string, so a value is never cut where the model escaped something. An incomplete hex
|
|
162
|
+
* escape (`\xg`, `\uZZ`) decodes nothing in every setting and stays as written.
|
|
163
|
+
* Whichever is chosen, an escape strict JSON would reject is reported as `invalid-escape`.
|
|
164
|
+
*/
|
|
165
|
+
escapes?: EscapeMode;
|
|
166
|
+
/**
|
|
167
|
+
* Whether a key or separator the output was cut off at is dropped or kept.
|
|
168
|
+
*
|
|
169
|
+
* `{"a": 1, "b`: `true` (default) gives `{ a: 1 }`. `false` gives `{ a: '1, "b' }` - the
|
|
170
|
+
* fragment written into a field that was already correct, which is exactly what this option
|
|
171
|
+
* exists to prevent. Dropping is the default, and the dropped text is listed in
|
|
172
|
+
* {@link RepairResult.discarded} and flagged `dangling-dropped`, so nothing disappears
|
|
173
|
+
* without a trace. Only the fragment is dropped: the container closes and a record written
|
|
174
|
+
* after it is still read, so under a Schema that expects a list `{"a": 1, "b"} {"c": 2}`
|
|
175
|
+
* becomes `[{ a: 1 }, { c: 2 }]`. Without that declaration the two records are scored as
|
|
176
|
+
* competing fragments and the loser is listed in {@link RepairResult.discarded}.
|
|
177
|
+
* A broken key with a value after it is syntax to repair, not a fragment, and is left alone.
|
|
178
|
+
*/
|
|
179
|
+
dangling?: boolean;
|
|
180
|
+
/**
|
|
181
|
+
* Whether a record the Schema expects inside a list is read as one item: a single object
|
|
182
|
+
* under a root `array` becomes `[object]`, and sibling records written side by side
|
|
183
|
+
* (`{...} {...}`, or the same without braces) become the items of that list.
|
|
57
184
|
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
185
|
+
* Enabled by default - the structure was declared by the Schema, so it is not a guess.
|
|
186
|
+
* Set it to `false` to keep the value exactly as the document wrote it and let the
|
|
187
|
+
* reported `errors` say what is missing. The cost: the record is no longer looked up
|
|
188
|
+
* against `items`, so its own keys lose their Schema guide - coercion stops applying and
|
|
189
|
+
* a value can run into the next key. That is why the default is `true`.
|
|
190
|
+
*/
|
|
191
|
+
wrapArrays?: boolean;
|
|
192
|
+
/**
|
|
193
|
+
* Whether to look for the JSON inside the input text first.
|
|
194
|
+
*
|
|
195
|
+
* LLM output is text, not a document: the JSON often sits inside a Markdown fence and
|
|
196
|
+
* between sentences. With `true` (the default) the input is scanned for
|
|
197
|
+
* quote-aware, escape-aware, bracket-balanced JSON regions and the best one is repaired;
|
|
198
|
+
* prose and fences around it are dropped and reported. With `false` the whole string is
|
|
199
|
+
* parsed as if it were already a JSON document (the behaviour up to 0.1.x).
|
|
200
|
+
*
|
|
201
|
+
* Input that already parses as JSON is never touched either way.
|
|
202
|
+
*/
|
|
203
|
+
locate?: boolean;
|
|
204
|
+
/**
|
|
205
|
+
* How to choose when the input contains more than one JSON fragment.
|
|
206
|
+
*
|
|
207
|
+
* - `'best'` (default): rank the fragments by how well they fit the Schema - fewer
|
|
208
|
+
* validation errors, more `required` fields carrying real values, more declared fields,
|
|
209
|
+
* fewer Schema keywords in the answer - and take the winner. A tie is decided by position,
|
|
210
|
+
* last first, because a model usually drafts before it answers; the tie is then reported as
|
|
211
|
+
* `ambiguous-candidates` rather than hidden. An extra key the Schema never named is not held
|
|
212
|
+
* against a fragment ({@link CandidateScore.undeclaredKeys} reports it); only an answer built
|
|
213
|
+
* out of the Schema itself is.
|
|
214
|
+
* - `'last'` / `'first'`: take the position regardless of how well the fragment fits. The
|
|
215
|
+
* Schema errors of the chosen fragment are still reported.
|
|
216
|
+
* - `'throw'`: reject the input outright and list the candidates with their scores.
|
|
61
217
|
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
218
|
+
* Without a Schema the ranking has no information to work with, so it collapses to the
|
|
219
|
+
* position rule (the last fragment).
|
|
64
220
|
*/
|
|
65
|
-
|
|
221
|
+
onMultiple?: 'best' | 'last' | 'first' | 'throw';
|
|
222
|
+
/**
|
|
223
|
+
* What to do with text the repair dropped on the floor (prose, fences, losing fragments).
|
|
224
|
+
*
|
|
225
|
+
* - `'report'` (default): drop it, but list it in `RepairResult.discarded`.
|
|
226
|
+
* - `'throw'`: refuse the input - a caller that cannot afford to lose content should not
|
|
227
|
+
* accept a repair that discards any.
|
|
228
|
+
* - `'ignore'`: drop it silently.
|
|
229
|
+
*/
|
|
230
|
+
onDiscard?: 'report' | 'throw' | 'ignore';
|
|
66
231
|
}
|
|
67
232
|
/**
|
|
68
233
|
* Represents the current path in a JSON structure.
|
|
69
234
|
* A list of strings (keys) and numbers (indices).
|
|
70
235
|
*/
|
|
71
236
|
type JSONPath = (string | number)[];
|
|
237
|
+
/**
|
|
238
|
+
* A named observation about the input or about the choices the repair made.
|
|
239
|
+
* Flags exist so that a caller can see which failures it is paying for instead of
|
|
240
|
+
* guessing from the output - the failure taxonomy of LLM output is what tells an operator
|
|
241
|
+
* whether another model call is worth spending.
|
|
242
|
+
*
|
|
243
|
+
* - Input shape: `markdown-fence`, `prose-prefix`, `trailing-chatter`,
|
|
244
|
+
* `implicit-structure`, `truncated-candidate`
|
|
245
|
+
* - Decisions taken: `sibling-objects-merged`, `extra-fragments-dropped`,
|
|
246
|
+
* `duplicate-candidates`, `ambiguous-candidates`, `undeclared-keys-dropped` (a key the
|
|
247
|
+
* level's `additionalProperties` forbids), `coerced-text-dropped` (a coercion gave up
|
|
248
|
+
* the text around the value it kept)
|
|
249
|
+
* - Content suspicions: `empty-required` (a `required` string field satisfied by `""` -
|
|
250
|
+
* schema-valid and information-free), `schema-echo-detected` (the model reproduced the
|
|
251
|
+
* Schema instead of filling it in)
|
|
252
|
+
* - Limits reached: `nesting-limited` (a document deeper than the parser reads, with the text
|
|
253
|
+
* it never reached listed in `discarded`)
|
|
254
|
+
*/
|
|
255
|
+
/**
|
|
256
|
+
* A difference in how a declared property name is spelled that `keyMatching` may be told to
|
|
257
|
+
* ignore. Named one at a time because a caller that owns a key grammar buys these separately:
|
|
258
|
+
* a minimal contract may accept the Schema's display name while keeping case and separators
|
|
259
|
+
* byte-exact, and `true` cannot say that.
|
|
260
|
+
*
|
|
261
|
+
* - `case`: `USER-NAME` is `user-name`.
|
|
262
|
+
* - `separators`: the written boundary between words is free, so `user_name`, `user-name` and
|
|
263
|
+
* `user name` are one name. camelCase writes that boundary as a letter-case change, so
|
|
264
|
+
* `userName` only collides with them when `case` is selected too - a boundary written as a
|
|
265
|
+
* case difference is invisible to a case-sensitive comparison.
|
|
266
|
+
*/
|
|
267
|
+
type KeyMatchForm = 'case' | 'separators';
|
|
268
|
+
/**
|
|
269
|
+
* `keyMatching` spelled out: the forms in force, which characters count as a separator, and
|
|
270
|
+
* the alternative names the Schema declares under keywords this library does not read.
|
|
271
|
+
*/
|
|
272
|
+
interface KeyMatchSpec {
|
|
273
|
+
/** Which spelling differences are not differences. `true` takes every form, `false`/`[]` none. */
|
|
274
|
+
forms?: boolean | readonly KeyMatchForm[];
|
|
275
|
+
/**
|
|
276
|
+
* The characters that count as a word separator when the `separators` form is on.
|
|
277
|
+
* Default: {@link KEY_SEPARATORS}. A caller with its own separator set passes it, so the
|
|
278
|
+
* same bytes resolve the same way in every channel it reads.
|
|
279
|
+
*/
|
|
280
|
+
separators?: readonly string[];
|
|
281
|
+
/** Canonical declared property name -> other names the document may use for it. */
|
|
282
|
+
aliases?: Record<string, readonly string[]>;
|
|
283
|
+
}
|
|
284
|
+
/** A comment style. See {@link RepairOptions.comments}. */
|
|
285
|
+
type CommentStyle = 'line' | 'block' | 'hash';
|
|
286
|
+
/** A language whose bare-token literals a model may write. See {@link RepairOptions.literals}. */
|
|
287
|
+
type LiteralDialect = 'js' | 'python';
|
|
288
|
+
/** How much a backslash is trusted as an escape. See {@link RepairOptions.escapes}. */
|
|
289
|
+
type EscapeMode = 'json5' | 'json' | 'raw';
|
|
290
|
+
type RepairFlag = 'markdown-fence' | 'prose-prefix' | 'trailing-chatter' | 'implicit-structure' | 'truncated-candidate' | 'sibling-objects-merged' | 'extra-fragments-dropped' | 'duplicate-candidates' | 'ambiguous-candidates' | 'empty-required' | 'schema-echo-detected'
|
|
291
|
+
/** A quoted value's closing quote was inferred (see `unescapedQuotes`). */
|
|
292
|
+
| 'unescaped-quote-inferred'
|
|
293
|
+
/** A comment was skipped between two members (see `comments`). */
|
|
294
|
+
| 'comment-skipped'
|
|
295
|
+
/**
|
|
296
|
+
* A comment in a style that was not asked for ended up inside a value. `comments` decides
|
|
297
|
+
* whether a comment is read, and {@link RepairOptions.comments} says what the default costs;
|
|
298
|
+
* this is that cost, named, so it can be seen without reading the value back.
|
|
299
|
+
*/
|
|
300
|
+
| 'comment-in-value'
|
|
301
|
+
/** A bare token was read as a literal of another language (see `literals`). */
|
|
302
|
+
| 'non-json-literal'
|
|
303
|
+
/**
|
|
304
|
+
* The document contains an escape strict JSON would reject (`"\$10"`, `"a\qb"`, `"\x41"`,
|
|
305
|
+
* `"\xg"). How it was read depends on {@link RepairOptions.escapes} - unwrapped, or left as
|
|
306
|
+
* written - but the caller is told either way, because the value lost or gained a backslash.
|
|
307
|
+
*/
|
|
308
|
+
| 'invalid-escape'
|
|
309
|
+
/** A key the output never finished was dropped; its text is in `discarded`. */
|
|
310
|
+
| 'dangling-dropped'
|
|
311
|
+
/**
|
|
312
|
+
* A key the level's effective `additionalProperties` forbids was dropped; its text is in
|
|
313
|
+
* `discarded` too, so a strict Schema does not silently eat what the model wrote.
|
|
314
|
+
*/
|
|
315
|
+
| 'undeclared-keys-dropped'
|
|
316
|
+
/** The parser stopped before the end of the region it was given. */
|
|
317
|
+
| 'unparsed-tail'
|
|
318
|
+
/**
|
|
319
|
+
* A coercion kept part of a value and gave up the text around it (`"Approx. 1,200.50 USD"`
|
|
320
|
+
* -> `1200.5` gives up `Approx. USD`). Giving a unit up is what
|
|
321
|
+
* {@link RepairOptions.coerceTypes} is for, so only text that reads as a sentence rather than
|
|
322
|
+
* a qualifier is listed in {@link RepairResult.discarded} as well - three words, or twenty
|
|
323
|
+
* characters with no space to count them by.
|
|
324
|
+
*/
|
|
325
|
+
| 'coerced-text-dropped'
|
|
326
|
+
/**
|
|
327
|
+
* The document is nested deeper than the parser reads (1,000 levels). The value came back as
|
|
328
|
+
* far as the parser went and {@link RepairResult.discarded} holds the text it never reached -
|
|
329
|
+
* the alternative was a stack overflow, which is not an outcome a caller can report on.
|
|
330
|
+
*/
|
|
331
|
+
| 'nesting-limited';
|
|
332
|
+
/**
|
|
333
|
+
* How well one fragment fits the Schema. Compared in this order:
|
|
334
|
+
* `errors` ascending, then `requiredCovered`, `declaredCovered` descending,
|
|
335
|
+
* then `schemaEchoKeys` ascending. A single extra key is not held against a fragment -
|
|
336
|
+
* `additionalProperties` is the caller's business, not a ranking signal - but a fragment
|
|
337
|
+
* built out of Schema keywords is.
|
|
338
|
+
*
|
|
339
|
+
* Coverage counts only fields that carry a usable value: `""` and a `null` the Schema does
|
|
340
|
+
* not allow are not "covered", which is what stops a placeholder-only fragment from beating
|
|
341
|
+
* a fragment with real data.
|
|
342
|
+
*/
|
|
343
|
+
interface CandidateScore {
|
|
344
|
+
errors: number;
|
|
345
|
+
requiredCovered: number;
|
|
346
|
+
declaredCovered: number;
|
|
347
|
+
/**
|
|
348
|
+
* Keys the Schema never declared, by name or by `patternProperties`. Reported, and used to
|
|
349
|
+
* rank only via `schemaEchoKeys`.
|
|
350
|
+
*/
|
|
351
|
+
undeclaredKeys: number;
|
|
352
|
+
/** How many of those undeclared keys are JSON Schema keywords - the echo signature. */
|
|
353
|
+
schemaEchoKeys: number;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* A JSON region located inside a larger piece of text, given as offsets into that text so
|
|
357
|
+
* the caller can line it up against what the model actually returned.
|
|
358
|
+
*/
|
|
359
|
+
interface LocatedJson {
|
|
360
|
+
start: number;
|
|
361
|
+
end: number;
|
|
362
|
+
text: string;
|
|
363
|
+
flags: RepairFlag[];
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* A JSON fragment found in the input text, with the score it earned against the Schema.
|
|
367
|
+
*/
|
|
368
|
+
interface JsonCandidate extends LocatedJson {
|
|
369
|
+
score: CandidateScore;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* A JSON Schema violation, located by path so it can be handed back to a model verbatim.
|
|
373
|
+
*/
|
|
374
|
+
interface ValidationError {
|
|
375
|
+
path: JSONPath;
|
|
376
|
+
message: string;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Everything a repair produced: the value, what was noticed about the input, what still
|
|
380
|
+
* fails against the Schema, and what was discarded to get there.
|
|
381
|
+
*/
|
|
382
|
+
interface RepairResult<T = any> {
|
|
383
|
+
value: T;
|
|
384
|
+
flags: RepairFlag[];
|
|
385
|
+
errors: ValidationError[];
|
|
386
|
+
candidates: JsonCandidate[];
|
|
387
|
+
discarded: string[];
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* The characters that count as a word separator when the `separators` form is on.
|
|
392
|
+
* camelCase is not in this list: it writes the boundary as a letter-case change, which only a
|
|
393
|
+
* case-folding comparison can see - see {@link KeyMatchForm}.
|
|
394
|
+
*/
|
|
395
|
+
declare const KEY_SEPARATORS: readonly string[];
|
|
396
|
+
/** What a `keyMatching` option resolves to. One place, so no reader of the option re-derives it. */
|
|
397
|
+
interface ResolvedKeyMatching {
|
|
398
|
+
/** The `case` form: compare without regard to letter case. */
|
|
399
|
+
foldCase: boolean;
|
|
400
|
+
/** The separator characters in force, or `null` when the `separators` form is off. */
|
|
401
|
+
separators: readonly string[] | null;
|
|
402
|
+
/** Canonical declared name -> the other names the document may use for it. */
|
|
403
|
+
aliases: Record<string, readonly string[]>;
|
|
404
|
+
/** A caller-supplied resolver; it decides itself and replaces the forms. */
|
|
405
|
+
matcher: ((key: string, properties: string[]) => string | undefined) | null;
|
|
406
|
+
}
|
|
72
407
|
|
|
73
408
|
/**
|
|
74
409
|
* Navigates through a JSON Schema based on a JSON Path.
|
|
75
410
|
* Handles $ref resolution and provides type information for specific paths.
|
|
411
|
+
*
|
|
412
|
+
* Before it is walked, the Schema is also flattened over the keywords that describe the same
|
|
413
|
+
* value from another angle - `allOf`, `anyOf` and `oneOf` - so a type or a property declared
|
|
414
|
+
* inside one of them is still seen at the level it describes.
|
|
76
415
|
*/
|
|
77
416
|
declare class SchemaWalker {
|
|
78
417
|
private dereferencedSchema;
|
|
79
418
|
private options;
|
|
419
|
+
/** `options.keyMatching`, read once. See {@link SchemaWalker.keyMatching}. */
|
|
420
|
+
private resolvedKeyMatching?;
|
|
80
421
|
private constructor();
|
|
81
422
|
/**
|
|
82
423
|
* Static factory method to create a SchemaWalker instance.
|
|
83
|
-
* Asynchronously dereferences the provided JSON Schema.
|
|
424
|
+
* Asynchronously dereferences the provided JSON Schema, then flattens its combinators.
|
|
84
425
|
*
|
|
85
426
|
* The Schema is dereferenced on a deep copy: `$RefParser.dereference()` replaces every
|
|
86
|
-
* `$ref` in place, which would otherwise rewrite the object the caller passed in.
|
|
427
|
+
* `$ref` in place, which would otherwise rewrite the object the caller passed in. Both
|
|
428
|
+
* that copy and the flattening stay inside the walker.
|
|
87
429
|
*
|
|
88
430
|
* @param schema - The JSON Schema object to walk.
|
|
89
431
|
* @param options - Repair options that concern the Schema itself (`keyMatching`).
|
|
90
432
|
* @returns A promise that resolves to a SchemaWalker instance.
|
|
91
433
|
*/
|
|
92
434
|
static create(schema: any, options?: RepairOptions): Promise<SchemaWalker>;
|
|
435
|
+
/** Keywords that describe the value at a level instead of a deeper one. */
|
|
436
|
+
private static readonly COMBINATORS;
|
|
437
|
+
/** Keywords whose value is a map of name to sub-schema. */
|
|
438
|
+
private static readonly SCHEMA_MAPS;
|
|
439
|
+
/** Keywords whose value is a sub-schema, or a list of them. */
|
|
440
|
+
private static readonly SCHEMA_NODES;
|
|
441
|
+
/**
|
|
442
|
+
* What an `anyOf` / `oneOf` branch may add to the level it describes.
|
|
443
|
+
*
|
|
444
|
+
* A branch that applies only sometimes can still say what the value may be (`type`), which
|
|
445
|
+
* names the level may hold (`properties`), what a list holds (`items`) and which values are
|
|
446
|
+
* listed (`enum`) - folding those in is what lets the walker navigate and coerce a Schema
|
|
447
|
+
* built out of branches. A branch's own constraints (`pattern`, `required`, the bounds) say
|
|
448
|
+
* something about that branch alone, so they are left where they are rather than merged into
|
|
449
|
+
* a level that may be using a different branch.
|
|
450
|
+
*/
|
|
451
|
+
private static readonly SHARED_KEYWORDS;
|
|
452
|
+
/**
|
|
453
|
+
* Folds `allOf` / `anyOf` / `oneOf` into the level they describe.
|
|
454
|
+
*
|
|
455
|
+
* Without this the node the walker hands back for a path is `{ anyOf: [{ type: 'string' }] }`:
|
|
456
|
+
* `type` is missing, so `coerceValue()` leaves the scalar exactly as the document wrote it and
|
|
457
|
+
* `validateValue()` finds nothing to complain about - the same value coerces under
|
|
458
|
+
* `{ type: 'string' }` and not under a branch that says the same thing.
|
|
459
|
+
*
|
|
460
|
+
* - `allOf`: every branch applies, so a branch merges into the level completely, its
|
|
461
|
+
* constraints included.
|
|
462
|
+
* - `anyOf` / `oneOf`: one branch applies, so only {@link SHARED_KEYWORDS} merge.
|
|
463
|
+
*
|
|
464
|
+
* Where a level and a branch say different things about one thing, the types are listed
|
|
465
|
+
* together (`type: ['string', 'number']`) - the Schema allows either, so a value that already
|
|
466
|
+
* reads as one of them is left alone and only a value that matches none gets coerced.
|
|
467
|
+
*
|
|
468
|
+
* The pass runs once per Schema and keeps a recursive Schema cyclic instead of endless:
|
|
469
|
+
* a node already seen is reused, and a branch is never merged into a node twice.
|
|
470
|
+
*/
|
|
471
|
+
private static flatten;
|
|
472
|
+
/** The sub-schemas held by a map keyword (`properties`, `$defs`, ...). */
|
|
473
|
+
private static flattenMap;
|
|
474
|
+
/**
|
|
475
|
+
* The flattened form of one Schema node: its own keywords, its sub-schemas flattened below
|
|
476
|
+
* them, and its branches applied. `const`, `enum` and `default` hold data rather than
|
|
477
|
+
* sub-schemas, so they are copied and never walked - a document's own value may well contain
|
|
478
|
+
* the word `allOf`.
|
|
479
|
+
*/
|
|
480
|
+
private static flattenNode;
|
|
481
|
+
/**
|
|
482
|
+
* Applies one branch to the level it describes: `every` when the branch always applies
|
|
483
|
+
* (`allOf`), `one` when it applies only if chosen (`anyOf` / `oneOf`).
|
|
484
|
+
*/
|
|
485
|
+
private static mergeInto;
|
|
486
|
+
/** The two lists together, without repeating what both already say. */
|
|
487
|
+
private static unique;
|
|
93
488
|
/**
|
|
94
489
|
* Retrieves the sub-schema for a given JSON path.
|
|
95
490
|
*
|
|
491
|
+
* A key the Schema does not name is described by a `patternProperties` entry that matches it,
|
|
492
|
+
* or by the level's effective `additionalProperties` when that is a Schema itself - which is
|
|
493
|
+
* how one declaration covers a whole free-form map.
|
|
494
|
+
*
|
|
96
495
|
* @param path - The path to navigate to.
|
|
97
496
|
* @returns The sub-schema at the specified path, or undefined if not found.
|
|
98
497
|
*/
|
|
99
498
|
getSchemaForPath(path: JSONPath): any;
|
|
499
|
+
/**
|
|
500
|
+
* The `additionalProperties` value that applies at `path`: what the Schema says there, or
|
|
501
|
+
* what {@link RepairOptions.additionalProperties} says for every level that does not.
|
|
502
|
+
*
|
|
503
|
+
* Neither speaking means the JSON Schema default: any value is allowed.
|
|
504
|
+
*/
|
|
505
|
+
additionalPropertiesAt(path: JSONPath): unknown;
|
|
506
|
+
/**
|
|
507
|
+
* The keyword value that governs the children of a Schema node - the node's own if it states
|
|
508
|
+
* one, the option's otherwise, and JSON Schema's own assumption (`true`) when neither does.
|
|
509
|
+
*/
|
|
510
|
+
private effectiveAdditionalProperties;
|
|
511
|
+
/**
|
|
512
|
+
* The sub-schema one of those children gets when the node names no property for it, or
|
|
513
|
+
* `undefined` when the effective keyword names none (`true`, `false`).
|
|
514
|
+
*
|
|
515
|
+
* This is what lets one Schema describe a whole free-form map: the value of an undeclared
|
|
516
|
+
* key is coerced and validated against it, exactly as a declared property's value is.
|
|
517
|
+
*/
|
|
518
|
+
private valueSchemaOf;
|
|
519
|
+
/**
|
|
520
|
+
* The `patternProperties` Schema that names `key` at `path` - the first pattern it matches.
|
|
521
|
+
*
|
|
522
|
+
* A pattern is a key the level describes by shape rather than by name, so it carries the same
|
|
523
|
+
* three things a declared property does: what the value is, whether it fits, and whether the
|
|
524
|
+
* key belongs here.
|
|
525
|
+
*/
|
|
526
|
+
patternSchemaFor(path: JSONPath, key: string | number): any;
|
|
527
|
+
/** What one Schema node's `patternProperties` says about `key`, or `undefined`. */
|
|
528
|
+
private patternSchemaForNode;
|
|
529
|
+
/**
|
|
530
|
+
* Whether a `patternProperties` entry at `path` covers `key`, so it is not an extra one.
|
|
531
|
+
*
|
|
532
|
+
* A pattern the host engine cannot compile covers every key and describes none: failing to
|
|
533
|
+
* read the guard is no reason to call the document's key extra (and drop it under
|
|
534
|
+
* `additionalProperties: false`), and no reason to invent a type for it either.
|
|
535
|
+
*/
|
|
536
|
+
matchesKeyPattern(path: JSONPath, key: string): boolean;
|
|
537
|
+
/** Whether the level at `path` describes keys by shape at all. */
|
|
538
|
+
hasKeyPatterns(path: JSONPath): boolean;
|
|
539
|
+
private static patternEntries;
|
|
540
|
+
/**
|
|
541
|
+
* The compiled pattern, or `null` when the host regex engine cannot compile it. The same
|
|
542
|
+
* patterns are asked again for every key of every document, so they are kept compiled.
|
|
543
|
+
*/
|
|
544
|
+
private static readonly patterns;
|
|
545
|
+
private static patternOf;
|
|
100
546
|
/**
|
|
101
547
|
* Determines if a property key is valid for the given path according to the Schema.
|
|
102
548
|
*
|
|
@@ -105,13 +551,24 @@ declare class SchemaWalker {
|
|
|
105
551
|
* @returns True if the property is defined in the Schema or allowed by additionalProperties.
|
|
106
552
|
*/
|
|
107
553
|
isValidProperty(path: JSONPath, key: string): boolean;
|
|
554
|
+
/**
|
|
555
|
+
* Whether the level at `path` may hold `key` at all: it is declared there, or the effective
|
|
556
|
+
* {@link additionalPropertiesAt} allows keys the Schema does not name.
|
|
557
|
+
*
|
|
558
|
+
* A level that declares no property names is free-form: none of its keys is an "extra" one,
|
|
559
|
+
* so `additionalProperties: false` never empties it. That is the one place the repair reads
|
|
560
|
+
* the keyword more loosely than strict JSON Schema does, and it is deliberate - emptying a
|
|
561
|
+
* `labels` or `metadata` map is destroying the answer, not tightening it.
|
|
562
|
+
*/
|
|
563
|
+
allowsProperty(path: JSONPath, key: string): boolean;
|
|
108
564
|
/**
|
|
109
565
|
* Resolves an incoming property name to the name declared by the Schema at `path`.
|
|
110
566
|
*
|
|
111
|
-
* Without `keyMatching` this only accepts an exact declaration.
|
|
112
|
-
*
|
|
113
|
-
* (`user_name` / `userName` / `USER NAME`)
|
|
114
|
-
*
|
|
567
|
+
* Without `keyMatching` this only accepts an exact declaration. The selected forms say what
|
|
568
|
+
* may differ from it: `case` ignores letter case, `separators` ignores the word boundary
|
|
569
|
+
* (`user_name` / `userName` / `USER NAME`), and `aliases` adds the alternative names the
|
|
570
|
+
* Schema declares under a keyword this library does not read. A function matcher decides
|
|
571
|
+
* itself and may return a name the Schema does not declare.
|
|
115
572
|
*
|
|
116
573
|
* Besides renaming, the result is what makes a key a breakpoint for greedy string capture:
|
|
117
574
|
* the parser calls this while deciding whether an upcoming `key:` ends the value in front of it.
|
|
@@ -122,14 +579,19 @@ declare class SchemaWalker {
|
|
|
122
579
|
*/
|
|
123
580
|
matchProperty(path: JSONPath, key: string): string | null;
|
|
124
581
|
/**
|
|
125
|
-
* The
|
|
582
|
+
* The resolved `options.keyMatching` this walker was built with - the one place the option is
|
|
583
|
+
* read. The parser asks for it rather than reading the option itself: `keyMatching` describes
|
|
584
|
+
* how the Schema's names may be spelled, so a walker built with it (the documented way to
|
|
585
|
+
* reuse a Schema) has to give the same answer to every reader, both the key lookup above and
|
|
586
|
+
* the parser's scan for a declared key written across several words.
|
|
587
|
+
*
|
|
588
|
+
* Cached: it does not change while this walker lives.
|
|
126
589
|
*/
|
|
127
|
-
|
|
590
|
+
get keyMatching(): ResolvedKeyMatching;
|
|
128
591
|
/**
|
|
129
|
-
*
|
|
130
|
-
* snake_case, kebab-case, camelCase and spaced keys collide.
|
|
592
|
+
* The property names the Schema declares at `path` (empty when the level is free-form).
|
|
131
593
|
*/
|
|
132
|
-
|
|
594
|
+
declaredPropertyNames(path: JSONPath): string[];
|
|
133
595
|
/**
|
|
134
596
|
* Whether a property name is explicitly declared in the Schema at the given path.
|
|
135
597
|
*
|
|
@@ -142,6 +604,8 @@ declare class SchemaWalker {
|
|
|
142
604
|
* Whether the Schema at the given path declares any property names at all.
|
|
143
605
|
* Used to decide whether key matching can be strict or has to stay lenient.
|
|
144
606
|
*
|
|
607
|
+
* `patternProperties` declares keys of another kind - see {@link hasKeyPatterns}.
|
|
608
|
+
*
|
|
145
609
|
* @param path - The current parent path.
|
|
146
610
|
*/
|
|
147
611
|
hasDeclaredProperties(path: JSONPath): boolean;
|
|
@@ -165,6 +629,15 @@ declare class RepairParser {
|
|
|
165
629
|
private pathStack;
|
|
166
630
|
private walker;
|
|
167
631
|
private options;
|
|
632
|
+
private readFlags;
|
|
633
|
+
/**
|
|
634
|
+
* Text the parser deliberately dropped - a key the output never finished, dropped as a
|
|
635
|
+
* fragment rather than merged into the field before it. Reported to the caller, because text
|
|
636
|
+
* never goes away silently.
|
|
637
|
+
*/
|
|
638
|
+
private dropped;
|
|
639
|
+
private readonly commentStyles;
|
|
640
|
+
private readonly literalDialects;
|
|
168
641
|
/**
|
|
169
642
|
* Creates a new RepairParser instance.
|
|
170
643
|
*
|
|
@@ -172,6 +645,18 @@ declare class RepairParser {
|
|
|
172
645
|
* @param options - Configuration options for the repair process.
|
|
173
646
|
*/
|
|
174
647
|
constructor(walker: SchemaWalker, options?: RepairOptions);
|
|
648
|
+
/**
|
|
649
|
+
* Where the last {@link parse} call stopped, as an offset into the trimmed string the
|
|
650
|
+
* parser worked on. Whatever follows it is not part of the document - the text a caller
|
|
651
|
+
* needs when it wants to know what a repair left behind.
|
|
652
|
+
*/
|
|
653
|
+
get consumed(): number;
|
|
654
|
+
/** The text the last {@link parse} call dropped as an unfinished fragment. */
|
|
655
|
+
get droppedText(): readonly string[];
|
|
656
|
+
/** How the last {@link parse} call read the document (see {@link RepairFlag}). */
|
|
657
|
+
get flags(): ReadonlySet<RepairFlag>;
|
|
658
|
+
/** The text after the parsed document, as the parser saw it (see {@link consumed}). */
|
|
659
|
+
get remainder(): string;
|
|
175
660
|
/**
|
|
176
661
|
* Parses the input string and returns the repaired JavaScript object.
|
|
177
662
|
*
|
|
@@ -184,6 +669,66 @@ declare class RepairParser {
|
|
|
184
669
|
* Uses Schema guidance to decide whether to use standard parsing or greedy capture.
|
|
185
670
|
*/
|
|
186
671
|
private consumeValue;
|
|
672
|
+
/** Whether the Schema's own listed values include `value`. */
|
|
673
|
+
private static allows;
|
|
674
|
+
/** Whether the Schema says what kind of value belongs at this path. */
|
|
675
|
+
private static guidesScalar;
|
|
676
|
+
/**
|
|
677
|
+
* The literal a bare token stands for in one of the dialects `RepairOptions.literals`
|
|
678
|
+
* allows, or `undefined` when the token is ordinary text. Exact match only: `None-ish` and
|
|
679
|
+
* `True story` are text, and a token that carries any of it cannot be a literal.
|
|
680
|
+
*/
|
|
681
|
+
private dialectLiteral;
|
|
682
|
+
private static readonly PYTHON_LITERALS;
|
|
683
|
+
private static readonly JS_LITERALS;
|
|
684
|
+
/**
|
|
685
|
+
* A value that begins with a `"` the model never closed -
|
|
686
|
+
* `{"t": "The "Best" Paper", "y": 2020}`. Each later quote is a candidate for where the
|
|
687
|
+
* value meant to end, and it is one only if a member follows it. With `'declared'` that
|
|
688
|
+
* member also has to be one the Schema names at this level, which is the difference between
|
|
689
|
+
* knowing the boundary and guessing it.
|
|
690
|
+
*
|
|
691
|
+
* @returns the content of the value, or `undefined` when no candidate is confirmed (in
|
|
692
|
+
* which case greedy capture reads it, as it always did).
|
|
693
|
+
*/
|
|
694
|
+
private consumeUnterminatedString;
|
|
695
|
+
/**
|
|
696
|
+
* Whether the quote at `quoteAt` ends the value: a member separator, a closing bracket or
|
|
697
|
+
* the end of the document has to follow it - and under `'declared'`, the member has to be a
|
|
698
|
+
* key the Schema declares.
|
|
699
|
+
*/
|
|
700
|
+
private closesValueAt;
|
|
701
|
+
/**
|
|
702
|
+
* Skips whitespace and, where a member is expected, the comments
|
|
703
|
+
* {@link RepairOptions.comments} allows. A comment is only ever recognised at a member
|
|
704
|
+
* position - never after a `:` and never inside a bare token - which is what keeps
|
|
705
|
+
* `issue: #123` and `url: https://x.com/a` intact at every setting.
|
|
706
|
+
*/
|
|
707
|
+
private skipMemberGap;
|
|
708
|
+
/** Consumes one comment at the current position, when an allowed style matches one. */
|
|
709
|
+
private skipOneComment;
|
|
710
|
+
/**
|
|
711
|
+
* Characters a comment can follow at a member gap: the start of a container, a separator, or
|
|
712
|
+
* whitespace. Anything else - the `:` of `issue: #123`, the `:` of `https://x` - is a value
|
|
713
|
+
* position, where the text belongs to the model and a comment is never read.
|
|
714
|
+
*/
|
|
715
|
+
private static readonly COMMENT_GAP;
|
|
716
|
+
/**
|
|
717
|
+
* Whether the text a capture took in hides a comment in a style the caller did not ask for.
|
|
718
|
+
*
|
|
719
|
+
* Quoted runs are skipped (so `"#ff0000"` is a color), a marker glued to a token is skipped
|
|
720
|
+
* (so `https://x.com/a` is a URL), and a marker that starts the capture is skipped (so
|
|
721
|
+
* `issue: #123` is an issue number) - the three positions where the parser never reads a
|
|
722
|
+
* comment, at any setting.
|
|
723
|
+
*/
|
|
724
|
+
private swallowedComment;
|
|
725
|
+
/**
|
|
726
|
+
* Where the next token begins, looking past whitespace and (where a member gap is allowed)
|
|
727
|
+
* past the comments that were asked for. Does not move the parser.
|
|
728
|
+
*/
|
|
729
|
+
private nextMemberPos;
|
|
730
|
+
/** Consumes to (not including) the next newline, or to the end of the input. */
|
|
731
|
+
private skipToLineEnd;
|
|
187
732
|
/**
|
|
188
733
|
* Attempts a strict JSON scalar parse (string / number / boolean / null) at the current
|
|
189
734
|
* position and rewinds when the token is not followed by a boundary.
|
|
@@ -194,26 +739,25 @@ declare class RepairParser {
|
|
|
194
739
|
* always parses exactly like `JSON.parse`.
|
|
195
740
|
*/
|
|
196
741
|
private tryConsumeStrictValue;
|
|
742
|
+
/**
|
|
743
|
+
* How deep a document the parser reads. The host stack overflows somewhere around 2,500
|
|
744
|
+
* levels of this recursion; 1,000 leaves room for the validator and the scorer, which walk
|
|
745
|
+
* the same structure, and is far past any document a model writes.
|
|
746
|
+
*/
|
|
747
|
+
private static readonly MAX_NESTING;
|
|
197
748
|
/**
|
|
198
749
|
* Whether the Schema describes an object at the current path.
|
|
199
750
|
*
|
|
200
|
-
* `SchemaWalker` navigates on `type === 'object' || properties`, so
|
|
201
|
-
* detection has to use the same rule: a level that declares `properties`
|
|
202
|
-
* `type: ['object', ...]` union) is an object even when it never spells
|
|
751
|
+
* `SchemaWalker` navigates on `type === 'object' || properties || patternProperties`, so
|
|
752
|
+
* implicit-object detection has to use the same rule: a level that declares `properties`
|
|
753
|
+
* or key shapes (or a `type: ['object', ...]` union) is an object even when it never spells
|
|
754
|
+
* out `type`.
|
|
203
755
|
*/
|
|
204
756
|
private static declaresObject;
|
|
205
757
|
/**
|
|
206
758
|
* Parses a JSON object, handling both standard and implicit (no braces) structures.
|
|
207
759
|
*/
|
|
208
760
|
private consumeObject;
|
|
209
|
-
/**
|
|
210
|
-
* Whether a property belongs in the output, according to `RepairOptions.additionalProperties`.
|
|
211
|
-
*
|
|
212
|
-
* `'remove'` only drops keys at a level whose Schema declares property names: a level
|
|
213
|
-
* that is free-form (`type: 'object'` without `properties`, or no Schema at all) has no
|
|
214
|
-
* notion of an "extra" key, so dropping everything there would be destructive.
|
|
215
|
-
*/
|
|
216
|
-
private isKeptProperty;
|
|
217
761
|
/**
|
|
218
762
|
* Assigns an own enumerable property without going through setters.
|
|
219
763
|
*
|
|
@@ -222,10 +766,29 @@ declare class RepairParser {
|
|
|
222
766
|
* loses the key and leaks inherited properties into the repaired document.
|
|
223
767
|
*/
|
|
224
768
|
private static setOwn;
|
|
769
|
+
/**
|
|
770
|
+
* Whether the Schema describes an array at the current path.
|
|
771
|
+
*
|
|
772
|
+
* `items` alone counts: `SchemaWalker` navigates children on `type === 'array' || items`,
|
|
773
|
+
* so an implicit list has to be recognised under the same rule.
|
|
774
|
+
*/
|
|
775
|
+
private static declaresArray;
|
|
225
776
|
/**
|
|
226
777
|
* Parses a JSON array.
|
|
778
|
+
*
|
|
779
|
+
* @param implicit - True when the document has no opening bracket and the list is implied
|
|
780
|
+
* by the Schema: successive records are read as items until the input runs out.
|
|
227
781
|
*/
|
|
228
782
|
private consumeArray;
|
|
783
|
+
/**
|
|
784
|
+
* Whether the Schema expects records as items and the text right here begins one. Used to
|
|
785
|
+
* decide whether a list continues after its bracket closed.
|
|
786
|
+
*
|
|
787
|
+
* Deliberately narrow: a bare key continues the list only when the items Schema declares
|
|
788
|
+
* it, so the next property of the enclosing object (`[{...}] "title": "x"`) is not
|
|
789
|
+
* mistaken for another item.
|
|
790
|
+
*/
|
|
791
|
+
private startsAnotherRecord;
|
|
229
792
|
/**
|
|
230
793
|
* Consumes a property key, handling both quoted and unquoted keys.
|
|
231
794
|
*
|
|
@@ -260,7 +823,9 @@ declare class RepairParser {
|
|
|
260
823
|
private static readonly WORD_CHAR;
|
|
261
824
|
/**
|
|
262
825
|
* Compiled "declared key literally here" patterns, shared across instances.
|
|
263
|
-
* Keyed by `
|
|
826
|
+
* Keyed by `foldCase` + name because the `i` flag follows the `case` form of `keyMatching`,
|
|
827
|
+
* and bounded: the names come from the Schema in play, and a long-lived process sees many of
|
|
828
|
+
* them.
|
|
264
829
|
*/
|
|
265
830
|
private static readonly declaredKeyPatterns;
|
|
266
831
|
/**
|
|
@@ -274,12 +839,19 @@ declare class RepairParser {
|
|
|
274
839
|
* The property names declared at `path` that contain whitespace, with a pattern that matches
|
|
275
840
|
* them literally: the name escaped, internal whitespace runs relaxed to `\s+`, and a `:`
|
|
276
841
|
* required after it. Single-word names are deliberately excluded - the generic key-shaped
|
|
277
|
-
* regex of {@link RepairParser.matchKey} already covers them.
|
|
842
|
+
* regex of {@link RepairParser.matchKey} already covers them. The alternative spellings a
|
|
843
|
+
* caller declares through `keyMatching.aliases` are included: for this scanner they are just
|
|
844
|
+
* as multi-word as the name they stand for.
|
|
845
|
+
*
|
|
846
|
+
* The forms in force come from the walker, not from this parser's options: `keyMatching`
|
|
847
|
+
* belongs to the Schema, and a caller who hands one walker to many `jsonRepair()` calls has
|
|
848
|
+
* stated it there. Reading it twice, once per place, is what lets one key in a document match
|
|
849
|
+
* while the next one does not.
|
|
278
850
|
*/
|
|
279
851
|
private declaredMultiWordKeys;
|
|
280
852
|
/**
|
|
281
853
|
* Matches a Schema-declared property name that contains whitespace at `startPos`, literally
|
|
282
|
-
* (case as declared, unless `keyMatching` folds
|
|
854
|
+
* (case as declared, unless the `case` form of `keyMatching` folds it).
|
|
283
855
|
*
|
|
284
856
|
* The generic key scanner cannot help here: its bare-key branch excludes whitespace, so an
|
|
285
857
|
* unquoted `Official language:` in the document is never seen as one key. Declaring the name
|
|
@@ -303,6 +875,21 @@ declare class RepairParser {
|
|
|
303
875
|
* whitespace/commas/colons (`"Official language":`), and returns the decoded key.
|
|
304
876
|
*/
|
|
305
877
|
private matchKey;
|
|
878
|
+
/**
|
|
879
|
+
* Whether the text here is a key that never got its colon or value: `{"a": 1, "b`.
|
|
880
|
+
* Closing brackets may follow the name, because a model can close the container and still
|
|
881
|
+
* leave the key hanging - and what follows the brackets may be the next record, since two
|
|
882
|
+
* records joined into one document are read by the same parser. Off with
|
|
883
|
+
* {@link RepairOptions.dangling}.
|
|
884
|
+
*/
|
|
885
|
+
private static readonly DANGLING_TAIL;
|
|
886
|
+
private danglingTail;
|
|
887
|
+
/** Whether the text here is a key the output never finished. */
|
|
888
|
+
private isDanglingTail;
|
|
889
|
+
/** Whether `raw` is a string literal that closed itself (ran to input end: it did not). */
|
|
890
|
+
private static closesString;
|
|
891
|
+
/** A token followed by a colon and then a path separator - a scheme or a path, not a key. */
|
|
892
|
+
private static readonly PATH_NOT_KEY;
|
|
306
893
|
/**
|
|
307
894
|
* Is a property boundary (a key followed by ':') ahead of `startPos`?
|
|
308
895
|
*
|
|
@@ -325,6 +912,74 @@ declare class RepairParser {
|
|
|
325
912
|
* there. Coercing to `string` uses it so that `{ zip: 01234 }` yields `'01234'`.
|
|
326
913
|
*/
|
|
327
914
|
private coerceValue;
|
|
915
|
+
/**
|
|
916
|
+
* Reporting the text a number coercion gave up to keep the number in it.
|
|
917
|
+
*
|
|
918
|
+
* Giving up the unit is what makes `"约 1,200.50 元"` read as `1200.5`, and a unit is not a
|
|
919
|
+
* loss. The same path is also where a sentence goes missing: greedy capture runs a value into
|
|
920
|
+
* whatever follows it, so `age: 30\n\nHope this helps!}` hands the value `30\n\nHope this
|
|
921
|
+
* helps!` and the coercion throws the sentence away with the rest - out of the value, out of
|
|
922
|
+
* `flags` and out of `discarded`, which is how a repair that lost content reads as a perfect
|
|
923
|
+
* parse (`errors: [] flags: [] discarded: []`).
|
|
924
|
+
*
|
|
925
|
+
* Both are flagged `coerced-text-dropped`. Only text that reads as a sentence rather than as
|
|
926
|
+
* a qualifier is listed in `discarded`: that is what keeps `onDiscard: 'throw'` meaning "no
|
|
927
|
+
* content went missing" rather than "the document held no units", which no caller writing
|
|
928
|
+
* noisy numbers could use.
|
|
929
|
+
*
|
|
930
|
+
* @param written - the whole text this value was read from, digit-group separators relaxed.
|
|
931
|
+
* @param taken - the numeric match the value keeps inside it.
|
|
932
|
+
*/
|
|
933
|
+
private reportNumberCoercion;
|
|
934
|
+
/**
|
|
935
|
+
* Text around a numeric token that is structure rather than content: whitespace, and the
|
|
936
|
+
* member separator the parser crossed on its way into the value.
|
|
937
|
+
*/
|
|
938
|
+
private static readonly COERCED_EDGE;
|
|
939
|
+
/**
|
|
940
|
+
* How a value is spelled when comparing it to an `enum` entry: lower case, separators gone,
|
|
941
|
+
* so `Processing!` matches `'processing'` and `"user-name"` matches `userName`. `null` means
|
|
942
|
+
* there is no spelling to compare - a structured entry, `null`, a boolean, or text that says
|
|
943
|
+
* nothing once its punctuation is dropped. Only an exact match counts for those, and the
|
|
944
|
+
* Schema decides through the reported errors.
|
|
945
|
+
*/
|
|
946
|
+
private static enumSpelling;
|
|
947
|
+
/**
|
|
948
|
+
* The single-character escapes JSON defines.
|
|
949
|
+
*/
|
|
950
|
+
private static readonly ESCAPE_MAP;
|
|
951
|
+
/**
|
|
952
|
+
* Reads one escape sequence, backslash included.
|
|
953
|
+
*
|
|
954
|
+
* A valid JSON escape decodes exactly as `JSON.parse` decodes it, so a document that parses
|
|
955
|
+
* cleanly never loses what it wrote. `\uXXXX` is decoded one code unit at a time, which makes
|
|
956
|
+
* a surrogate pair come out as the astral character without extra handling - and leaves an
|
|
957
|
+
* unpaired surrogate where `JSON.parse` leaves it.
|
|
958
|
+
*
|
|
959
|
+
* Past JSON, {@link RepairOptions.escapes} decides how far the trust in a backslash reaches:
|
|
960
|
+
* - `'json5'` (default) reads `\xNN` as the character it names, and unwraps an escape of a
|
|
961
|
+
* character that never needs one (`"\$10"` -> `$10`), the way JSON5 does. Dropping the
|
|
962
|
+
* backslash of `\xNN` instead would leave the letters of the escape in the value
|
|
963
|
+
* (`"a\xa0b"` -> `axa0b`); dropping the one of `\U` is what turns a Windows path into
|
|
964
|
+
* `C:Usersme`. Both raise `invalid-escape`.
|
|
965
|
+
* - `'json'` leaves everything JSON does not define as the document wrote it, backslash
|
|
966
|
+
* included.
|
|
967
|
+
* - `'raw'` leaves every escape alone, so a backslash is content: paths, regular expressions
|
|
968
|
+
* and LaTeX survive whole, and `"a\nb"` is two characters rather than a newline.
|
|
969
|
+
*
|
|
970
|
+
* The backslash itself is structural in all three: it always keeps the character behind it
|
|
971
|
+
* inside the string, so the mode cannot change where a value ends. An incomplete hex escape
|
|
972
|
+
* decodes nothing and is left as written - `readHex` did not consume its digits.
|
|
973
|
+
*
|
|
974
|
+
* Decoding stops there: a decoded or literal NBSP, a zero-width character, a smart quote all
|
|
975
|
+
* stay in the value. Rewriting those would change the model's content, not repair its syntax.
|
|
976
|
+
*/
|
|
977
|
+
private consumeEscape;
|
|
978
|
+
/**
|
|
979
|
+
* Reads `count` hexadecimal digits, consuming them only when all `count` are digits, so an
|
|
980
|
+
* incomplete escape leaves the rest of the text to the caller.
|
|
981
|
+
*/
|
|
982
|
+
private readHex;
|
|
328
983
|
/**
|
|
329
984
|
* Consumes a standard JSON string.
|
|
330
985
|
*/
|
|
@@ -341,6 +996,18 @@ declare class RepairParser {
|
|
|
341
996
|
* Consumes a standard JSON number.
|
|
342
997
|
*/
|
|
343
998
|
private consumeNumber;
|
|
999
|
+
/**
|
|
1000
|
+
* Consumes one of JSON's own literals - `true`, `false`, `null` - only when the whole token
|
|
1001
|
+
* is that word: the character after it has to end the token, not continue it.
|
|
1002
|
+
*
|
|
1003
|
+
* A bare `n` is the model's word, not `null`. Reading a prefix as the literal invents a missing
|
|
1004
|
+
* value where the document wrote text, and inventing `null` is the one mistake no caller
|
|
1005
|
+
* notices: it is exactly what a truncated answer usually looks like. {@link consumeValue}
|
|
1006
|
+
* falls back to greedy capture when nothing is consumed here, so the text comes back whole.
|
|
1007
|
+
*
|
|
1008
|
+
* @returns whether the token was the literal.
|
|
1009
|
+
*/
|
|
1010
|
+
private consumeKeyword;
|
|
344
1011
|
/**
|
|
345
1012
|
* Consumes a standard JSON boolean.
|
|
346
1013
|
*/
|
|
@@ -358,10 +1025,11 @@ declare class RepairParser {
|
|
|
358
1025
|
}
|
|
359
1026
|
|
|
360
1027
|
/**
|
|
361
|
-
* Repairs and parses a
|
|
1028
|
+
* Repairs and parses a string generated by an LLM, guided by a JSON Schema.
|
|
362
1029
|
* This is the main entry point for the library.
|
|
363
1030
|
*
|
|
364
|
-
* @param input - The
|
|
1031
|
+
* @param input - The text the model returned: broken JSON, or JSON wrapped in a Markdown
|
|
1032
|
+
* fence and prose. See {@link RepairOptions.locate}.
|
|
365
1033
|
* @param schema - Either a plain JSON Schema object or a pre-initialized SchemaWalker instance for better performance in batch processing.
|
|
366
1034
|
* @param options - Optional configuration to tune the repair process.
|
|
367
1035
|
* @returns A promise that resolves to the repaired and parsed JavaScript object.
|
|
@@ -374,5 +1042,124 @@ declare class RepairParser {
|
|
|
374
1042
|
* ```
|
|
375
1043
|
*/
|
|
376
1044
|
declare function jsonRepair(input: string, schema?: any | SchemaWalker, options?: RepairOptions): Promise<any>;
|
|
1045
|
+
/**
|
|
1046
|
+
* The same repair, plus what it noticed and what it had to give up.
|
|
1047
|
+
*
|
|
1048
|
+
* A repaired value that validates can still be the wrong answer, and a repair that had to
|
|
1049
|
+
* choose between fragments or throw prose away has made decisions the caller should be able
|
|
1050
|
+
* to see. `flags`, `errors`, `candidates` and `discarded` are what a caller needs to decide
|
|
1051
|
+
* whether to accept the value, hand the `errors` back to the model for another try, or give
|
|
1052
|
+
* up and ask a bigger model.
|
|
1053
|
+
*
|
|
1054
|
+
* @example
|
|
1055
|
+
* ```typescript
|
|
1056
|
+
* const { value, errors, flags } = await jsonRepairResult('```json\n{ name: Ada }\n```', schema)
|
|
1057
|
+
* if (errors.length) await retryWith(renderValidatorErrors(errors))
|
|
1058
|
+
* ```
|
|
1059
|
+
*/
|
|
1060
|
+
declare function jsonRepairResult<T = any>(input: string, schema?: any | SchemaWalker, options?: RepairOptions): Promise<RepairResult<T>>;
|
|
1061
|
+
|
|
1062
|
+
/** Whether the Schema expects an array at the root of the document. */
|
|
1063
|
+
declare function expectsArrayRoot(walker: SchemaWalker): boolean;
|
|
1064
|
+
/**
|
|
1065
|
+
* @param text - The text to scan, normally already trimmed by the caller.
|
|
1066
|
+
* @param walker - The Schema in play. It decides three things: whether adjacent sibling
|
|
1067
|
+
* records may be read as one array, where a record written without braces starts (a key only
|
|
1068
|
+
* the Schema can name), and nothing at all when no Schema is given.
|
|
1069
|
+
* @returns The regions in document order.
|
|
1070
|
+
*/
|
|
1071
|
+
declare function locateJsonCandidates(text: string, walker?: SchemaWalker): LocatedJson[];
|
|
1072
|
+
/**
|
|
1073
|
+
* Where a record that has no braces at all starts, when prose sits in front of it:
|
|
1074
|
+
* `Here you go:\nname: Noah, age: 30`. The only thing that can tell `name` is a key rather
|
|
1075
|
+
* than part of a sentence is the Schema declaring it, so the Schema supplies the offset.
|
|
1076
|
+
*
|
|
1077
|
+
* @returns A region running from the first declared key to the end of the text, or
|
|
1078
|
+
* `undefined` when the text names none of them.
|
|
1079
|
+
*/
|
|
1080
|
+
declare function findImplicitRecordRegion(text: string, walker: SchemaWalker): LocatedJson | undefined;
|
|
1081
|
+
/**
|
|
1082
|
+
* What the repair threw away around a chosen region: the prose between and around the JSON
|
|
1083
|
+
* regions (with offsets, so the caller can tell prefix from trailing chatter), and the
|
|
1084
|
+
* regions it did not pick. Reported separately from the flags because a caller that cannot
|
|
1085
|
+
* afford to lose content needs the text itself, not just a hint that something went.
|
|
1086
|
+
*/
|
|
1087
|
+
declare function discardedText(text: string, chosen: LocatedJson, others: LocatedJson[]): {
|
|
1088
|
+
prose: {
|
|
1089
|
+
text: string;
|
|
1090
|
+
start: number;
|
|
1091
|
+
}[];
|
|
1092
|
+
fragments: string[];
|
|
1093
|
+
};
|
|
1094
|
+
|
|
1095
|
+
/**
|
|
1096
|
+
* A small JSON Schema validator, kept inside this package on purpose: the repair already
|
|
1097
|
+
* knows the Schema through `SchemaWalker`, and the two things a caller needs after a repair
|
|
1098
|
+
* are "does this still fail?" (to decide whether another model call is worth it) and "where
|
|
1099
|
+
* does it fail?" (to tell the model). Pulling in a full validator would duplicate the
|
|
1100
|
+
* walking this library already does.
|
|
1101
|
+
*
|
|
1102
|
+
* The keywords covered are the ones that describe a shape an LLM can get wrong: `type`
|
|
1103
|
+
* (including `integer` and unions), `required`, `properties`, `patternProperties`,
|
|
1104
|
+
* `additionalProperties` (the Schema's own, or the default `RepairOptions.additionalProperties`
|
|
1105
|
+
* gives it), `items`,
|
|
1106
|
+
* `enum`, `const`, `pattern`, `format` for dates and times, numeric bounds, string length and
|
|
1107
|
+
* array length. Unknown keywords are ignored, and so is everything below a Schema that says
|
|
1108
|
+
* nothing.
|
|
1109
|
+
*
|
|
1110
|
+
* `allOf` / `anyOf` / `oneOf` are read where they describe the level - `SchemaWalker` folds
|
|
1111
|
+
* their types, declared names, `items` and listed values into it before this validator sees it,
|
|
1112
|
+
* and every `allOf` branch contributes its constraints. What is still not evaluated is what
|
|
1113
|
+
* belongs to one branch of an `anyOf` / `oneOf` (`pattern`, the bounds, `required`) and
|
|
1114
|
+
* `if` / `then` / `else`: a constraint that only one alternative makes is not a constraint on
|
|
1115
|
+
* the value, and reporting it would be reporting an error the Schema does not make.
|
|
1116
|
+
*/
|
|
1117
|
+
declare function validateValue(value: any, walker: SchemaWalker): ValidationError[];
|
|
1118
|
+
/**
|
|
1119
|
+
* Renders validation errors the way a repair prompt needs them: one `path: message` line
|
|
1120
|
+
* each, short enough that a 360M-parameter model still follows it. Paths point at the field,
|
|
1121
|
+
* so the model has something concrete to fix rather than a document to re-read.
|
|
1122
|
+
*
|
|
1123
|
+
* @param limit - How many lines to emit. More than a handful of simultaneous complaints is
|
|
1124
|
+
* wasted on a small model; it fixes the first few and breaks the rest.
|
|
1125
|
+
*/
|
|
1126
|
+
declare function renderValidatorErrors(errors: ValidationError[], limit?: number): string;
|
|
1127
|
+
|
|
1128
|
+
/**
|
|
1129
|
+
* How well a value fits the Schema, measured rather than felt.
|
|
1130
|
+
*
|
|
1131
|
+
* Counting declared keys is not the same as counting keys a model happened to write. Two
|
|
1132
|
+
* real failure modes make that difference decisive:
|
|
1133
|
+
*
|
|
1134
|
+
* - A model that copies the Schema into its answer (`type`, `properties`, `required`, ...)
|
|
1135
|
+
* produces the fragment with the *most* keys and the least data.
|
|
1136
|
+
* - A model that answers with `"name": ""` satisfies `type: string` exactly and says nothing.
|
|
1137
|
+
*
|
|
1138
|
+
* So coverage counts only fields carrying a usable value, and keys the Schema never declared
|
|
1139
|
+
* are counted against the fragment.
|
|
1140
|
+
*/
|
|
1141
|
+
declare function scoreCandidate(value: any, walker: SchemaWalker): {
|
|
1142
|
+
score: CandidateScore;
|
|
1143
|
+
flags: RepairFlag[];
|
|
1144
|
+
};
|
|
1145
|
+
/**
|
|
1146
|
+
* Whether the model reproduced the Schema instead of filling it in.
|
|
1147
|
+
*
|
|
1148
|
+
* Given the fragment's text, Schema keywords are counted where they are written - the usual
|
|
1149
|
+
* place to look, because an echo is often swallowed by greedy capture on the way to the real
|
|
1150
|
+
* keys. Given a repaired value, its own keys are counted: a weaker signal (a document with
|
|
1151
|
+
* one real `items` field is not an echo), which is why one keyword is never enough here
|
|
1152
|
+
* either way. Anything else - a number, a string that is not text - is not an echo.
|
|
1153
|
+
*/
|
|
1154
|
+
declare function looksLikeSchemaEcho(fragment: unknown): boolean;
|
|
1155
|
+
/**
|
|
1156
|
+
* Compare two scores the way {@link RepairOptions.onMultiple} promises: fewer errors first, then
|
|
1157
|
+
* more `required` fields with real values, then more declared fields, then fewer keys that are
|
|
1158
|
+
* JSON Schema keywords - the signature of an answer built out of the Schema itself. An undeclared
|
|
1159
|
+
* key that is not a keyword is reported but not held against a fragment.
|
|
1160
|
+
*
|
|
1161
|
+
* @returns a negative number when `a` should win, positive when `b` should.
|
|
1162
|
+
*/
|
|
1163
|
+
declare function compareScores(a: CandidateScore, b: CandidateScore): number;
|
|
377
1164
|
|
|
378
|
-
export { type JSONPath, type RepairOptions, RepairParser, SchemaWalker, jsonRepair };
|
|
1165
|
+
export { type CandidateScore, type CommentStyle, type EscapeMode, type JSONPath, type JsonCandidate, KEY_SEPARATORS, type KeyMatchForm, type KeyMatchSpec, type LiteralDialect, type LocatedJson, type RepairFlag, type RepairOptions, RepairParser, type RepairResult, type ResolvedKeyMatching, SchemaWalker, type ValidationError, compareScores, discardedText, expectsArrayRoot, findImplicitRecordRegion, jsonRepair, jsonRepairResult, locateJsonCandidates, looksLikeSchemaEcho, renderValidatorErrors, scoreCandidate, validateValue };
|