@isdk/json-repair 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -3,31 +3,64 @@
3
3
  */
4
4
  interface RepairOptions {
5
5
  /**
6
- * Fuzzy matching for keys.
6
+ * Fuzzy matching of property keys against the Schema's declared `properties`.
7
7
  *
8
- * - `false` (default): Strict matching against the Schema defined keys.
9
- * - `true`: Allows case-insensitive matching and conversion between snake_case and camelCase.
10
- * - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic to find a matching property name.
8
+ * - `false` (default): Only an exactly declared key counts as a match.
9
+ * - `true`: Case-insensitive and separator-insensitive matching, so `user_name`,
10
+ * `userName`, `USER-NAME` and `user name` all resolve to the declared key.
11
+ * - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic;
12
+ * it receives the incoming key and the declared names, and returns the name to use
13
+ * (or `undefined` to fall back to the incoming key).
14
+ *
15
+ * A match renames the key to the Schema's name in the output and makes nested Schema
16
+ * lookups (and therefore type coercion) work for it.
17
+ * It also decides where greedy capture stops: with `true` a separator or case variant of a
18
+ * declared key (`user_name:` for `userName`) ends the value in front of it.
19
+ * When you reuse a `SchemaWalker`, pass this option to `SchemaWalker.create()`.
11
20
  */
12
21
  keyMatching?: boolean | ((key: string, properties: string[]) => string | undefined);
13
22
  /**
14
- * Strategy for greedy string capture when standard JSON parsing fails.
23
+ * Strategy for greedy string capture when the strict JSON path failed for a value.
24
+ *
25
+ * - `'aggressive'` (default): When the Schema declares property names for the current
26
+ * level, the captured value only ends at one of those declared keys. Text that merely
27
+ * looks like `"some words":` stays inside the value.
28
+ * - `'conservative'`: Any text matching the `"key":` / `key:` pattern ends the value,
29
+ * which keeps the structure of the document at the cost of cutting values short.
15
30
  *
16
- * - `'conservative'`: Stops at any text matching the `"key":` pattern.
17
- * - `'aggressive'` (default): Only stops if the key exists in the Schema and its following value type matches the expectations.
31
+ * A whitespace-containing key the Schema declares is a breakpoint in both strategies even
32
+ * when the document left it unquoted (`{ Capital: Berlin, Official language: Italian }`),
33
+ * because it can only be recognised from the declaration.
34
+ * Neither strategy affects values that were parsed by the strict JSON path; the
35
+ * boundary rules described in the README apply to those unchanged.
18
36
  */
19
37
  stringCaptureStrategy?: 'conservative' | 'aggressive';
20
38
  /**
21
- * Whether to attempt type coercion based on the Schema.
39
+ * Whether to coerce values to the type the Schema declares. Enabled by default.
40
+ *
41
+ * - `true` (default): `"Approx. 1,200.50 USD"` becomes `1200.5`, `"yes"` becomes `true`,
42
+ * `"Processing!"` becomes the enum entry it fuzzy matches, `12` becomes `"12"` when the
43
+ * Schema says `type: 'string'`.
44
+ * - `false`: values are returned exactly as they were parsed.
45
+ *
46
+ * Coercion needs the Schema of the property the value belongs to; a level that declares
47
+ * no types is left alone.
22
48
  *
23
- * If `true`, the parser will try to convert values to the expected type (e.g., "123" to 123 for numbers, "yes" to true for booleans).
49
+ * Coercing to a declared `string` reuses the text the document wrote, not the number it
50
+ * parsed to, so a leading zero survives: `{ id: 01234 }` becomes `"01234"`.
51
+ * `null` and structures (`{}` / `[]`) are never stringified - `"null"` and
52
+ * `"[object Object]"` are not what a `type: 'string'` declaration asks for.
24
53
  */
25
54
  coerceTypes?: boolean;
26
55
  /**
27
56
  * Defines how to handle properties not defined in the Schema.
28
57
  *
29
58
  * - `'keep'` (default): Keeps these extra properties in the output.
30
- * - `'remove'`: Automatically removes properties not found in the Schema.
59
+ * - `'remove'`: Drops them. Only applies at a level whose Schema declares `properties`;
60
+ * a free-form level has no "extra" keys and is left untouched.
61
+ *
62
+ * This option is independent from the JSON Schema keyword `additionalProperties: false`,
63
+ * which is respected on its own when validating incoming keys.
31
64
  */
32
65
  additionalProperties?: 'keep' | 'remove';
33
66
  }
@@ -43,15 +76,20 @@ type JSONPath = (string | number)[];
43
76
  */
44
77
  declare class SchemaWalker {
45
78
  private dereferencedSchema;
79
+ private options;
46
80
  private constructor();
47
81
  /**
48
82
  * Static factory method to create a SchemaWalker instance.
49
83
  * Asynchronously dereferences the provided JSON Schema.
50
84
  *
85
+ * 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.
87
+ *
51
88
  * @param schema - The JSON Schema object to walk.
89
+ * @param options - Repair options that concern the Schema itself (`keyMatching`).
52
90
  * @returns A promise that resolves to a SchemaWalker instance.
53
91
  */
54
- static create(schema: any): Promise<SchemaWalker>;
92
+ static create(schema: any, options?: RepairOptions): Promise<SchemaWalker>;
55
93
  /**
56
94
  * Retrieves the sub-schema for a given JSON path.
57
95
  *
@@ -67,6 +105,46 @@ declare class SchemaWalker {
67
105
  * @returns True if the property is defined in the Schema or allowed by additionalProperties.
68
106
  */
69
107
  isValidProperty(path: JSONPath, key: string): boolean;
108
+ /**
109
+ * Resolves an incoming property name to the name declared by the Schema at `path`.
110
+ *
111
+ * Without `keyMatching` this only accepts an exact declaration. With `keyMatching: true`
112
+ * the comparison ignores case and the separators used by the two common naming styles
113
+ * (`user_name` / `userName` / `USER NAME`). A function matcher decides itself and may
114
+ * return a name the Schema does not declare.
115
+ *
116
+ * Besides renaming, the result is what makes a key a breakpoint for greedy string capture:
117
+ * the parser calls this while deciding whether an upcoming `key:` ends the value in front of it.
118
+ *
119
+ * @param path - The current parent path.
120
+ * @param key - The property key found in the broken document.
121
+ * @returns The canonical Schema property name, or `null` when nothing matches.
122
+ */
123
+ matchProperty(path: JSONPath, key: string): string | null;
124
+ /**
125
+ * The property names the Schema declares at `path` (empty when the level is free-form).
126
+ */
127
+ declaredPropertyNames(path: JSONPath): string[];
128
+ /**
129
+ * Folding used for fuzzy key matching: case-insensitive and separator-insensitive, so
130
+ * snake_case, kebab-case, camelCase and spaced keys collide.
131
+ */
132
+ private static normalizeName;
133
+ /**
134
+ * Whether a property name is explicitly declared in the Schema at the given path.
135
+ *
136
+ * @param path - The current parent path.
137
+ * @param key - The property key to check.
138
+ * @returns True only when `key` appears in the Schema `properties` of that path.
139
+ */
140
+ isDeclaredProperty(path: JSONPath, key: string): boolean;
141
+ /**
142
+ * Whether the Schema at the given path declares any property names at all.
143
+ * Used to decide whether key matching can be strict or has to stay lenient.
144
+ *
145
+ * @param path - The current parent path.
146
+ */
147
+ hasDeclaredProperties(path: JSONPath): boolean;
70
148
  /**
71
149
  * Gets the expected types for a specific property at a given path.
72
150
  *
@@ -106,23 +184,112 @@ declare class RepairParser {
106
184
  * Uses Schema guidance to decide whether to use standard parsing or greedy capture.
107
185
  */
108
186
  private consumeValue;
187
+ /**
188
+ * Attempts a strict JSON scalar parse (string / number / boolean / null) at the current
189
+ * position and rewinds when the token is not followed by a boundary.
190
+ *
191
+ * The boundary test runs in `'structural'` mode: a cleanly parsed value is trusted, so
192
+ * anything that looks like the next key is treated as structure and the successful parse
193
+ * is never discarded in favour of greedy capture. This is what guarantees that valid JSON
194
+ * always parses exactly like `JSON.parse`.
195
+ */
196
+ private tryConsumeStrictValue;
197
+ /**
198
+ * Whether the Schema describes an object at the current path.
199
+ *
200
+ * `SchemaWalker` navigates on `type === 'object' || properties`, so implicit-object
201
+ * detection has to use the same rule: a level that declares `properties` (or a
202
+ * `type: ['object', ...]` union) is an object even when it never spells out `type`.
203
+ */
204
+ private static declaresObject;
109
205
  /**
110
206
  * Parses a JSON object, handling both standard and implicit (no braces) structures.
111
207
  */
112
208
  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
+ /**
218
+ * Assigns an own enumerable property without going through setters.
219
+ *
220
+ * `obj[key] = value` with a key such as `__proto__` rewrites the prototype of the result
221
+ * instead of storing a value (`JSON.parse` keeps it as a plain data property), which both
222
+ * loses the key and leaks inherited properties into the repaired document.
223
+ */
224
+ private static setOwn;
113
225
  /**
114
226
  * Parses a JSON array.
115
227
  */
116
228
  private consumeArray;
117
229
  /**
118
230
  * Consumes a property key, handling both quoted and unquoted keys.
231
+ *
232
+ * A quoted key keeps its exact content, including whitespace and punctuation
233
+ * (`"Official language"`); a bare key stops at quote characters so that a malformed
234
+ * document can never produce keys such as `language"`.
235
+ *
236
+ * A bare key that the Schema declares verbatim at `path` wins over the token scan, so a
237
+ * multi-word declaration (`Official language`) is read as one key even when the document
238
+ * left it unquoted (see {@link RepairParser.matchDeclaredKey}).
239
+ *
240
+ * @param path - The parent path the key belongs to; `pathStack` (the key is pushed later).
241
+ * @returns the key, or `null` when no key is present at all (an empty quoted key `""`
242
+ * is a valid key and returns the empty string).
119
243
  */
120
244
  private consumeKey;
121
245
  /**
122
- * Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
123
- * Implements the "Parity Rule" for smart quote stripping.
246
+ * Captures content greedily until it encounters a delimiter that marks the start of the
247
+ * next property or the end of a structure. This is the fallback used when the strict JSON
248
+ * path failed, so the boundary test runs in `'greedy'` mode: when the Schema declares
249
+ * property names for this level, capture stops only at a declared key (see
250
+ * {@link RepairParser.isBoundaryAhead}).
251
+ *
252
+ * It also tracks balanced delimiters (parentheses, brackets, braces) and quotes, so that
253
+ * structural markers inside DSL-like strings (e.g. `@weather(location="SH, CN")`) stay
254
+ * part of the captured value, and implements the "Parity Rule" for quote stripping.
124
255
  */
125
256
  private consumeGreedyString;
257
+ /**
258
+ * Characters that make the text before a candidate key part of a longer word.
259
+ */
260
+ private static readonly WORD_CHAR;
261
+ /**
262
+ * Compiled "declared key literally here" patterns, shared across instances.
263
+ * Keyed by `fuzzy` + name because the `i` flag depends on `keyMatching`.
264
+ */
265
+ private static readonly declaredKeyPatterns;
266
+ /**
267
+ * Memo of the last path the multi-word declarations were collected for.
268
+ * Greedy capture probes every character of a value while the path stays the same, so this
269
+ * avoids re-walking the Schema (and re-keying a Map) thousands of times per document.
270
+ */
271
+ private cachedPath;
272
+ private cachedDeclaredKeys;
273
+ /**
274
+ * The property names declared at `path` that contain whitespace, with a pattern that matches
275
+ * them literally: the name escaped, internal whitespace runs relaxed to `\s+`, and a `:`
276
+ * required after it. Single-word names are deliberately excluded - the generic key-shaped
277
+ * regex of {@link RepairParser.matchKey} already covers them.
278
+ */
279
+ private declaredMultiWordKeys;
280
+ /**
281
+ * Matches a Schema-declared property name that contains whitespace at `startPos`, literally
282
+ * (case as declared, unless `keyMatching` folds case).
283
+ *
284
+ * The generic key scanner cannot help here: its bare-key branch excludes whitespace, so an
285
+ * unquoted `Official language:` in the document is never seen as one key. Declaring the name
286
+ * in the Schema supplies the missing information, and this method turns it into both a
287
+ * breakpoint for greedy capture and a readable key. A candidate glued to a longer word
288
+ * (`de-factoOfficial language:`) is rejected, so the breakpoint stays anchored on real keys.
289
+ *
290
+ * @returns the declared name and the amount of text it covers, or `null`.
291
+ */
292
+ private matchDeclaredKey;
126
293
  /**
127
294
  * Probes whether the current position marks a structural delimiter (end or next property).
128
295
  */
@@ -131,15 +298,45 @@ declare class RepairParser {
131
298
  * Checks if the upcoming text looks like a property key defined in the Schema at the given path.
132
299
  */
133
300
  private isLookingAtKey;
301
+ /**
302
+ * Matches a property key at `startPos`, including quoted keys that contain
303
+ * whitespace/commas/colons (`"Official language":`), and returns the decoded key.
304
+ */
305
+ private matchKey;
306
+ /**
307
+ * Is a property boundary (a key followed by ':') ahead of `startPos`?
308
+ *
309
+ * - 'structural': trust any key-shaped token. Used right after a value was parsed by the
310
+ * strict JSON path, so a successful parse is never thrown away.
311
+ * - 'greedy': when the Schema declares property names at this level, stop only at a
312
+ * declared key; otherwise text that merely looks like `"foo bar":` would cut the value.
313
+ *
314
+ * A whitespace-containing name declared by the Schema is always a breakpoint, quoted or not,
315
+ * because it can only be recognised literally (see {@link RepairParser.matchDeclaredKey});
316
+ * in greedy mode other keys count as breakpoints through `keyMatching`, so a declared key
317
+ * written as `user_name` still breaks a value when the Schema declares `userName`.
318
+ */
319
+ private isBoundaryAhead;
134
320
  /**
135
321
  * Performs type coercion and semantic repair based on the Schema.
136
322
  * Handles fuzzy enum matching, noisy number extraction, and boolean variants.
323
+ *
324
+ * @param raw - The exact text the strict JSON path consumed for `val`, when it came from
325
+ * there. Coercing to `string` uses it so that `{ zip: 01234 }` yields `'01234'`.
137
326
  */
138
327
  private coerceValue;
139
328
  /**
140
329
  * Consumes a standard JSON string.
141
330
  */
142
331
  private consumeString;
332
+ /**
333
+ * Matches a JSON number literal at the current position.
334
+ *
335
+ * Scientific notation (`1e5`, `-2E2`) and a leading `+` are accepted; the match always
336
+ * stops at the end of a well-formed literal so that leftovers such as `1.2.3` remain
337
+ * available for greedy capture instead of being silently truncated.
338
+ */
339
+ private static readonly NUMBER_PATTERN;
143
340
  /**
144
341
  * Consumes a standard JSON number.
145
342
  */
package/dist/index.d.ts CHANGED
@@ -3,31 +3,64 @@
3
3
  */
4
4
  interface RepairOptions {
5
5
  /**
6
- * Fuzzy matching for keys.
6
+ * Fuzzy matching of property keys against the Schema's declared `properties`.
7
7
  *
8
- * - `false` (default): Strict matching against the Schema defined keys.
9
- * - `true`: Allows case-insensitive matching and conversion between snake_case and camelCase.
10
- * - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic to find a matching property name.
8
+ * - `false` (default): Only an exactly declared key counts as a match.
9
+ * - `true`: Case-insensitive and separator-insensitive matching, so `user_name`,
10
+ * `userName`, `USER-NAME` and `user name` all resolve to the declared key.
11
+ * - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic;
12
+ * it receives the incoming key and the declared names, and returns the name to use
13
+ * (or `undefined` to fall back to the incoming key).
14
+ *
15
+ * A match renames the key to the Schema's name in the output and makes nested Schema
16
+ * lookups (and therefore type coercion) work for it.
17
+ * It also decides where greedy capture stops: with `true` a separator or case variant of a
18
+ * declared key (`user_name:` for `userName`) ends the value in front of it.
19
+ * When you reuse a `SchemaWalker`, pass this option to `SchemaWalker.create()`.
11
20
  */
12
21
  keyMatching?: boolean | ((key: string, properties: string[]) => string | undefined);
13
22
  /**
14
- * Strategy for greedy string capture when standard JSON parsing fails.
23
+ * Strategy for greedy string capture when the strict JSON path failed for a value.
24
+ *
25
+ * - `'aggressive'` (default): When the Schema declares property names for the current
26
+ * level, the captured value only ends at one of those declared keys. Text that merely
27
+ * looks like `"some words":` stays inside the value.
28
+ * - `'conservative'`: Any text matching the `"key":` / `key:` pattern ends the value,
29
+ * which keeps the structure of the document at the cost of cutting values short.
15
30
  *
16
- * - `'conservative'`: Stops at any text matching the `"key":` pattern.
17
- * - `'aggressive'` (default): Only stops if the key exists in the Schema and its following value type matches the expectations.
31
+ * A whitespace-containing key the Schema declares is a breakpoint in both strategies even
32
+ * when the document left it unquoted (`{ Capital: Berlin, Official language: Italian }`),
33
+ * because it can only be recognised from the declaration.
34
+ * Neither strategy affects values that were parsed by the strict JSON path; the
35
+ * boundary rules described in the README apply to those unchanged.
18
36
  */
19
37
  stringCaptureStrategy?: 'conservative' | 'aggressive';
20
38
  /**
21
- * Whether to attempt type coercion based on the Schema.
39
+ * Whether to coerce values to the type the Schema declares. Enabled by default.
40
+ *
41
+ * - `true` (default): `"Approx. 1,200.50 USD"` becomes `1200.5`, `"yes"` becomes `true`,
42
+ * `"Processing!"` becomes the enum entry it fuzzy matches, `12` becomes `"12"` when the
43
+ * Schema says `type: 'string'`.
44
+ * - `false`: values are returned exactly as they were parsed.
45
+ *
46
+ * Coercion needs the Schema of the property the value belongs to; a level that declares
47
+ * no types is left alone.
22
48
  *
23
- * If `true`, the parser will try to convert values to the expected type (e.g., "123" to 123 for numbers, "yes" to true for booleans).
49
+ * Coercing to a declared `string` reuses the text the document wrote, not the number it
50
+ * parsed to, so a leading zero survives: `{ id: 01234 }` becomes `"01234"`.
51
+ * `null` and structures (`{}` / `[]`) are never stringified - `"null"` and
52
+ * `"[object Object]"` are not what a `type: 'string'` declaration asks for.
24
53
  */
25
54
  coerceTypes?: boolean;
26
55
  /**
27
56
  * Defines how to handle properties not defined in the Schema.
28
57
  *
29
58
  * - `'keep'` (default): Keeps these extra properties in the output.
30
- * - `'remove'`: Automatically removes properties not found in the Schema.
59
+ * - `'remove'`: Drops them. Only applies at a level whose Schema declares `properties`;
60
+ * a free-form level has no "extra" keys and is left untouched.
61
+ *
62
+ * This option is independent from the JSON Schema keyword `additionalProperties: false`,
63
+ * which is respected on its own when validating incoming keys.
31
64
  */
32
65
  additionalProperties?: 'keep' | 'remove';
33
66
  }
@@ -43,15 +76,20 @@ type JSONPath = (string | number)[];
43
76
  */
44
77
  declare class SchemaWalker {
45
78
  private dereferencedSchema;
79
+ private options;
46
80
  private constructor();
47
81
  /**
48
82
  * Static factory method to create a SchemaWalker instance.
49
83
  * Asynchronously dereferences the provided JSON Schema.
50
84
  *
85
+ * 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.
87
+ *
51
88
  * @param schema - The JSON Schema object to walk.
89
+ * @param options - Repair options that concern the Schema itself (`keyMatching`).
52
90
  * @returns A promise that resolves to a SchemaWalker instance.
53
91
  */
54
- static create(schema: any): Promise<SchemaWalker>;
92
+ static create(schema: any, options?: RepairOptions): Promise<SchemaWalker>;
55
93
  /**
56
94
  * Retrieves the sub-schema for a given JSON path.
57
95
  *
@@ -67,6 +105,46 @@ declare class SchemaWalker {
67
105
  * @returns True if the property is defined in the Schema or allowed by additionalProperties.
68
106
  */
69
107
  isValidProperty(path: JSONPath, key: string): boolean;
108
+ /**
109
+ * Resolves an incoming property name to the name declared by the Schema at `path`.
110
+ *
111
+ * Without `keyMatching` this only accepts an exact declaration. With `keyMatching: true`
112
+ * the comparison ignores case and the separators used by the two common naming styles
113
+ * (`user_name` / `userName` / `USER NAME`). A function matcher decides itself and may
114
+ * return a name the Schema does not declare.
115
+ *
116
+ * Besides renaming, the result is what makes a key a breakpoint for greedy string capture:
117
+ * the parser calls this while deciding whether an upcoming `key:` ends the value in front of it.
118
+ *
119
+ * @param path - The current parent path.
120
+ * @param key - The property key found in the broken document.
121
+ * @returns The canonical Schema property name, or `null` when nothing matches.
122
+ */
123
+ matchProperty(path: JSONPath, key: string): string | null;
124
+ /**
125
+ * The property names the Schema declares at `path` (empty when the level is free-form).
126
+ */
127
+ declaredPropertyNames(path: JSONPath): string[];
128
+ /**
129
+ * Folding used for fuzzy key matching: case-insensitive and separator-insensitive, so
130
+ * snake_case, kebab-case, camelCase and spaced keys collide.
131
+ */
132
+ private static normalizeName;
133
+ /**
134
+ * Whether a property name is explicitly declared in the Schema at the given path.
135
+ *
136
+ * @param path - The current parent path.
137
+ * @param key - The property key to check.
138
+ * @returns True only when `key` appears in the Schema `properties` of that path.
139
+ */
140
+ isDeclaredProperty(path: JSONPath, key: string): boolean;
141
+ /**
142
+ * Whether the Schema at the given path declares any property names at all.
143
+ * Used to decide whether key matching can be strict or has to stay lenient.
144
+ *
145
+ * @param path - The current parent path.
146
+ */
147
+ hasDeclaredProperties(path: JSONPath): boolean;
70
148
  /**
71
149
  * Gets the expected types for a specific property at a given path.
72
150
  *
@@ -106,23 +184,112 @@ declare class RepairParser {
106
184
  * Uses Schema guidance to decide whether to use standard parsing or greedy capture.
107
185
  */
108
186
  private consumeValue;
187
+ /**
188
+ * Attempts a strict JSON scalar parse (string / number / boolean / null) at the current
189
+ * position and rewinds when the token is not followed by a boundary.
190
+ *
191
+ * The boundary test runs in `'structural'` mode: a cleanly parsed value is trusted, so
192
+ * anything that looks like the next key is treated as structure and the successful parse
193
+ * is never discarded in favour of greedy capture. This is what guarantees that valid JSON
194
+ * always parses exactly like `JSON.parse`.
195
+ */
196
+ private tryConsumeStrictValue;
197
+ /**
198
+ * Whether the Schema describes an object at the current path.
199
+ *
200
+ * `SchemaWalker` navigates on `type === 'object' || properties`, so implicit-object
201
+ * detection has to use the same rule: a level that declares `properties` (or a
202
+ * `type: ['object', ...]` union) is an object even when it never spells out `type`.
203
+ */
204
+ private static declaresObject;
109
205
  /**
110
206
  * Parses a JSON object, handling both standard and implicit (no braces) structures.
111
207
  */
112
208
  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
+ /**
218
+ * Assigns an own enumerable property without going through setters.
219
+ *
220
+ * `obj[key] = value` with a key such as `__proto__` rewrites the prototype of the result
221
+ * instead of storing a value (`JSON.parse` keeps it as a plain data property), which both
222
+ * loses the key and leaks inherited properties into the repaired document.
223
+ */
224
+ private static setOwn;
113
225
  /**
114
226
  * Parses a JSON array.
115
227
  */
116
228
  private consumeArray;
117
229
  /**
118
230
  * Consumes a property key, handling both quoted and unquoted keys.
231
+ *
232
+ * A quoted key keeps its exact content, including whitespace and punctuation
233
+ * (`"Official language"`); a bare key stops at quote characters so that a malformed
234
+ * document can never produce keys such as `language"`.
235
+ *
236
+ * A bare key that the Schema declares verbatim at `path` wins over the token scan, so a
237
+ * multi-word declaration (`Official language`) is read as one key even when the document
238
+ * left it unquoted (see {@link RepairParser.matchDeclaredKey}).
239
+ *
240
+ * @param path - The parent path the key belongs to; `pathStack` (the key is pushed later).
241
+ * @returns the key, or `null` when no key is present at all (an empty quoted key `""`
242
+ * is a valid key and returns the empty string).
119
243
  */
120
244
  private consumeKey;
121
245
  /**
122
- * Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
123
- * Implements the "Parity Rule" for smart quote stripping.
246
+ * Captures content greedily until it encounters a delimiter that marks the start of the
247
+ * next property or the end of a structure. This is the fallback used when the strict JSON
248
+ * path failed, so the boundary test runs in `'greedy'` mode: when the Schema declares
249
+ * property names for this level, capture stops only at a declared key (see
250
+ * {@link RepairParser.isBoundaryAhead}).
251
+ *
252
+ * It also tracks balanced delimiters (parentheses, brackets, braces) and quotes, so that
253
+ * structural markers inside DSL-like strings (e.g. `@weather(location="SH, CN")`) stay
254
+ * part of the captured value, and implements the "Parity Rule" for quote stripping.
124
255
  */
125
256
  private consumeGreedyString;
257
+ /**
258
+ * Characters that make the text before a candidate key part of a longer word.
259
+ */
260
+ private static readonly WORD_CHAR;
261
+ /**
262
+ * Compiled "declared key literally here" patterns, shared across instances.
263
+ * Keyed by `fuzzy` + name because the `i` flag depends on `keyMatching`.
264
+ */
265
+ private static readonly declaredKeyPatterns;
266
+ /**
267
+ * Memo of the last path the multi-word declarations were collected for.
268
+ * Greedy capture probes every character of a value while the path stays the same, so this
269
+ * avoids re-walking the Schema (and re-keying a Map) thousands of times per document.
270
+ */
271
+ private cachedPath;
272
+ private cachedDeclaredKeys;
273
+ /**
274
+ * The property names declared at `path` that contain whitespace, with a pattern that matches
275
+ * them literally: the name escaped, internal whitespace runs relaxed to `\s+`, and a `:`
276
+ * required after it. Single-word names are deliberately excluded - the generic key-shaped
277
+ * regex of {@link RepairParser.matchKey} already covers them.
278
+ */
279
+ private declaredMultiWordKeys;
280
+ /**
281
+ * Matches a Schema-declared property name that contains whitespace at `startPos`, literally
282
+ * (case as declared, unless `keyMatching` folds case).
283
+ *
284
+ * The generic key scanner cannot help here: its bare-key branch excludes whitespace, so an
285
+ * unquoted `Official language:` in the document is never seen as one key. Declaring the name
286
+ * in the Schema supplies the missing information, and this method turns it into both a
287
+ * breakpoint for greedy capture and a readable key. A candidate glued to a longer word
288
+ * (`de-factoOfficial language:`) is rejected, so the breakpoint stays anchored on real keys.
289
+ *
290
+ * @returns the declared name and the amount of text it covers, or `null`.
291
+ */
292
+ private matchDeclaredKey;
126
293
  /**
127
294
  * Probes whether the current position marks a structural delimiter (end or next property).
128
295
  */
@@ -131,15 +298,45 @@ declare class RepairParser {
131
298
  * Checks if the upcoming text looks like a property key defined in the Schema at the given path.
132
299
  */
133
300
  private isLookingAtKey;
301
+ /**
302
+ * Matches a property key at `startPos`, including quoted keys that contain
303
+ * whitespace/commas/colons (`"Official language":`), and returns the decoded key.
304
+ */
305
+ private matchKey;
306
+ /**
307
+ * Is a property boundary (a key followed by ':') ahead of `startPos`?
308
+ *
309
+ * - 'structural': trust any key-shaped token. Used right after a value was parsed by the
310
+ * strict JSON path, so a successful parse is never thrown away.
311
+ * - 'greedy': when the Schema declares property names at this level, stop only at a
312
+ * declared key; otherwise text that merely looks like `"foo bar":` would cut the value.
313
+ *
314
+ * A whitespace-containing name declared by the Schema is always a breakpoint, quoted or not,
315
+ * because it can only be recognised literally (see {@link RepairParser.matchDeclaredKey});
316
+ * in greedy mode other keys count as breakpoints through `keyMatching`, so a declared key
317
+ * written as `user_name` still breaks a value when the Schema declares `userName`.
318
+ */
319
+ private isBoundaryAhead;
134
320
  /**
135
321
  * Performs type coercion and semantic repair based on the Schema.
136
322
  * Handles fuzzy enum matching, noisy number extraction, and boolean variants.
323
+ *
324
+ * @param raw - The exact text the strict JSON path consumed for `val`, when it came from
325
+ * there. Coercing to `string` uses it so that `{ zip: 01234 }` yields `'01234'`.
137
326
  */
138
327
  private coerceValue;
139
328
  /**
140
329
  * Consumes a standard JSON string.
141
330
  */
142
331
  private consumeString;
332
+ /**
333
+ * Matches a JSON number literal at the current position.
334
+ *
335
+ * Scientific notation (`1e5`, `-2E2`) and a leading `+` are accepted; the match always
336
+ * stops at the end of a well-formed literal so that leftovers such as `1.2.3` remain
337
+ * available for greedy capture instead of being silently truncated.
338
+ */
339
+ private static readonly NUMBER_PATTERN;
143
340
  /**
144
341
  * Consumes a standard JSON number.
145
342
  */
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,r=await h.dereference(i);return new s(r)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&!!i.properties[s]||!1!==i.additionalProperties))}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),h=i?.properties?.[s];return h?Array.isArray(h.type)?h.type:h.type?[h.type]:[]:[]}},i=class{input="";pos=0;pathStack=[];walker;options;constructor(t,s={}){this.walker=t,this.options={coerceTypes:!0,...s}}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const t=this.peek(),s=this.walker.getSchemaForPath(this.pathStack),i=s?.type;if("{"===t||"object"===i&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===t)return this.consumeArray();const h=this.pos;let r,e=!1;if('"'===t||"'"===t)try{r=this.consumeString();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?e=!0:this.pos=h}catch(t){this.pos=h}else if(this.isDigit(t)||"-"===t)try{r=this.consumeNumber();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?e=!0:this.pos=h}catch(t){this.pos=h}else if("t"===t||"f"===t||"n"===t)try{r="n"===t?this.consumeNull():this.consumeBoolean();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?e=!0:this.pos=h}catch(t){this.pos=h}if(e)return this.options.coerceTypes&&s?this.coerceValue(r,s):r;this.pos=h;const n=this.consumeGreedyString();return this.options.coerceTypes&&s?this.coerceValue(n,s):n}consumeObject(){const t={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const i=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const h=this.consumeKey();if(!h)break;if(!s&&t.hasOwnProperty(h)){this.pos=i;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==i||void 0!==s&&""!==s)&&(t[h]=s)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||s&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!s)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===i)break}return s&&"}"===this.peek()&&this.consumeChar("}"),t}consumeArray(){const t=[];this.consumeChar("["),this.skipWhitespace();let s=0;for(;this.pos<this.input.length&&"]"!==this.peek()&&"}"!==this.peek();){const i=this.pos;this.pathStack.push(s);try{const h=this.consumeValue();this.pos!==i&&(t.push(h),s++)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()&&(this.consumeChar(","),this.skipWhitespace()),this.pos===i)break}return"]"===this.peek()&&this.consumeChar("]"),t}consumeKey(){if(this.skipWhitespace(),this.pos>=this.input.length)return"";if('"'===this.peek()||"'"===this.peek())return this.consumeString();let t="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek();)t+=this.next();return t}consumeGreedyString(){let t="";const s=this.pos;for(;this.pos<this.input.length&&!this.isAtDelimiter();)t+=this.next();this.pos===s&&this.pos<this.input.length&&!this.isAtDelimiter()&&(t+=this.next());let i=t.trim();if(i.length>=2){const t=i[0],s=i[i.length-1];if(('"'===t||"'"===t)&&t===s){const s=i.slice(1,-1);let h=0;for(let i=0;i<s.length;i++)s[i]!==t||0!==i&&"\\"===s[i-1]||h++;if(h%2==1||0===h)return s}}return i}isAtDelimiter(){if(this.pos>=this.input.length)return!0;const t=this.peek();if("}"===t||"]"===t)return!0;const s="number"==typeof this.pathStack[this.pathStack.length-1];if(","===t){if(s)return!0;const t=this.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(t)||this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)}if(this.isLookingAtKey(this.pathStack.slice(0,-1)))return!0;if(this.isWhitespace(t)){const t=this.pos;this.skipWhitespace();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isLookingAtKey(this.pathStack.slice(0,-1));return this.pos=t,i}return!1}isLookingAtKey(t,s=this.pos){const i=this.input.slice(s).match(/^\s*["']?([^"'\s:]+)["']?\s*:/);if(i){const s=i[1];return this.walker.isValidProperty(t,s)}return!1}coerceValue(t,s){const i=Array.isArray(s.type)?s.type:s.type?[s.type]:[],h=String(t).trim();if(s.enum){const t=h.toLowerCase().replace(/[^a-z0-9]/g,"");for(const i of s.enum){if(t===String(i).toLowerCase().replace(/[^a-z0-9]/g,""))return i}}const r=null===t?"null":typeof t;if(i.length>0&&i.includes(r))return t;if(i.includes("number")||i.includes("integer")){let t=h.replace(/([^0-9.\-])/g,t=>","===t||","===t?"":" ").trim().split(/\s+/)[0];const s=parseFloat(t);if(!isNaN(s))return i.includes("integer")?Math.round(s):s}if(i.includes("boolean")){const t=h.toLowerCase(),s=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(s.includes(t))return!1}return i.includes("null")&&"null"===h.toLowerCase()?null:t}consumeString(){const t=this.next();let s="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?(this.next(),this.pos<this.input.length&&(s+=this.next())):s+=this.next();return this.peek()===t&&this.next(),s}consumeNumber(){let t="";for(;this.pos<this.input.length&&/[0-9.\-]/.test(this.peek());)t+=this.next();return parseFloat(t)}consumeBoolean(){const t=this.input.slice(this.pos);return t.startsWith("true")?(this.pos+=4,!0):!!t.startsWith("false")&&(this.pos+=5,!1)}consumeNull(){return this.pos+=4,null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}};async function h(t,h,r={}){const e=h instanceof s?h:await s.create(h);return new i(e,r).parse(t)}export{i as RepairParser,s as SchemaWalker,h as jsonRepair};
1
+ import t from"@apidevtools/json-schema-ref-parser";import{cloneDeep as s}from"lodash-es";var i=class i{dereferencedSchema;options;constructor(t,s={}){this.dereferencedSchema=t,this.options=s}static async create(e,r={}){if(!e)return new i({},r);const h=new t,n=await h.dereference(s(e));return new i(n,r)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&null!==this.matchProperty(t,s)||!1!==i.additionalProperties))}matchProperty(t,s){const e=this.declaredPropertyNames(t);if(e.includes(s))return s;const r=this.options.keyMatching;if(!r||0===e.length)return null;if("function"==typeof r){const t=r(s,e);return"string"==typeof t&&""!==t?t:null}const h=i.normalizeName(s);return e.find(t=>i.normalizeName(t)===h)??null}declaredPropertyNames(t){const s=this.getSchemaForPath(t)?.properties;return s?Object.keys(s):[]}static normalizeName(t){return t.replace(/[\s_\-.]/g,"").toLowerCase()}isDeclaredProperty(t,s){const i=this.getSchemaForPath(t);return!!i?.properties&&Object.prototype.hasOwnProperty.call(i.properties,s)}hasDeclaredProperties(t){const s=this.getSchemaForPath(t);return!!s?.properties&&Object.keys(s.properties).length>0}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),e=i?.properties?.[s];return e?Array.isArray(e.type)?e.type:e.type?[e.type]:[]:[]}},e=class t{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.cachedPath=null,this.cachedDeclaredKeys=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const s=this.peek(),i=this.walker.getSchemaForPath(this.pathStack);if("{"===s||t.declaresObject(i)&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===s)return this.consumeArray();const e=this.pos,r=this.tryConsumeStrictValue(s);if(r.ok)return this.options.coerceTypes&&i?this.coerceValue(r.value,i,r.raw):r.value;this.pos=e;const h=this.consumeGreedyString();return this.options.coerceTypes&&i?this.coerceValue(h,i):h}tryConsumeStrictValue(t){const s=this.pos;let i=null;if('"'===t||"'"===t?i=()=>this.consumeString():this.isDigit(t)||"-"===t||"+"===t?i=()=>this.consumeNumber():"t"!==t&&"f"!==t&&"n"!==t||(i=()=>"n"===t?this.consumeNull():this.consumeBoolean()),!i)return{ok:!1,value:void 0};try{const t=i(),e=this.input.slice(s,this.pos);if(this.skipWhitespace(),this.isAtDelimiter("structural")||this.pos>=this.input.length)return{ok:!0,value:t,raw:e}}catch(t){}return this.pos=s,{ok:!1,value:void 0}}static declaresObject(t){return!!t&&(Array.isArray(t.type)?t.type.includes("object"):"object"===t.type||!!t.properties)}consumeObject(){const s={},i="{"===this.peek();for(i&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const e=this.pos;if(!i&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const r=this.consumeKey(this.pathStack);if(null===r)break;const h=[...this.pathStack],n=this.walker.matchProperty(h,r)??r;if(!i&&Object.prototype.hasOwnProperty.call(s,n)){this.pos=e;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(n);try{const i=this.consumeValue();(this.pos!==e||void 0!==i&&""!==i)&&this.isKeptProperty(h,n)&&t.setOwn(s,n,i)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||i&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!i)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===e)break}return i&&"}"===this.peek()&&this.consumeChar("}"),s}isKeptProperty(t,s){return"remove"!==this.options.additionalProperties||(!this.walker.hasDeclaredProperties(t)||this.walker.isDeclaredProperty(t,s))}static setOwn(t,s,i){Object.defineProperty(t,s,{value:i,enumerable:!0,writable:!0,configurable:!0})}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 e=this.consumeValue();this.pos!==i&&(t.push(e),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(t=this.pathStack){if(this.skipWhitespace(),this.pos>=this.input.length)return null;if('"'===this.peek()||"'"===this.peek())return this.consumeString();const s=this.matchDeclaredKey(this.pos,t);if(s)return this.pos+=s.length,s.key;let i="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek()&&'"'!==this.peek()&&"'"!==this.peek();)i+=this.next();return i}consumeGreedyString(){let t="";const s=[];let i=!1,e="";for(;this.pos<this.input.length;){const r=this.peek();if(0===s.length&&this.isAtDelimiter("greedy"))break;if(i){if(r===e){let t=0,s=this.pos-1;for(;s>=0&&"\\"===this.input[s];)t++,s--;t%2==0&&(i=!1)}}else if('"'===r||"'"===r)i=!0,e=r;else if("("===r||"["===r||"{"===r)s.push(r);else if(")"===r||"]"===r||"}"===r){const t=s[s.length-1];(")"===r&&"("===t||"]"===r&&"["===t||"}"===r&&"{"===t)&&s.pop()}t+=this.next()}let r=t.trim();if(r.length>=2){const t=r[0],s=r[r.length-1];if(('"'===t||"'"===t)&&t===s){const s=r.slice(1,-1);let i=0;for(let e=0;e<s.length;e++)s[e]!==t||0!==e&&"\\"===s[e-1]||i++;if(i%2==1||0===i)return s}}return r}static WORD_CHAR=/[\p{L}\p{N}_]/u;static declaredKeyPatterns=new Map;cachedPath=null;cachedDeclaredKeys=[];declaredMultiWordKeys(s){if(this.cachedPath&&this.cachedPath.length===s.length&&this.cachedPath.every((t,i)=>t===s[i]))return this.cachedDeclaredKeys;const i=!0===this.options.keyMatching,e=this.walker.declaredPropertyNames(s).filter(t=>/\s/.test(t.trim())).map(s=>{const e=`${i?"i":""}:${s}`;let r=t.declaredKeyPatterns.get(e);if(!r){const h=s.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");r=new RegExp(`^${h}(?=\\s*:)`,i?"i":""),t.declaredKeyPatterns.set(e,r)}return{name:s,pattern:r}}).sort((t,s)=>s.name.length-t.name.length);return this.cachedPath=[...s],this.cachedDeclaredKeys=e,e}matchDeclaredKey(s,i=this.pathStack){let e=s;for(;e<this.input.length&&this.isWhitespace(this.input[e]);)e++;if(e>0&&t.WORD_CHAR.test(this.input[e-1]))return null;const r=this.declaredMultiWordKeys(i);if(0===r.length)return null;const h=this.input.slice(e);let n=null;for(const{name:t,pattern:s}of r){const i=h.match(s);i&&(!n||i[0].length>n.length)&&(n={key:t,length:i[0].length})}return n}isAtDelimiter(t="greedy"){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.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(s)||(!!/^\s*$/.test(s)||this.isBoundaryAhead(this.pos+1,t))}if(this.isBoundaryAhead(this.pos,t))return!0;if(this.isWhitespace(s)){const s=this.pos;this.skipWhitespace();const i=this.peek(),e="}"===i||"]"===i||","===i||this.isBoundaryAhead(this.pos,t);return this.pos=s,e}return!1}isLookingAtKey(t,s=this.pos){if(null!==this.matchDeclaredKey(s,t))return!0;const i=this.matchKey(s);return null!==i&&this.walker.isValidProperty(t,i)}matchKey(t=this.pos){const s=this.input.slice(t).match(/^\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([^\s"',:{}\[\]]+))\s*:/);if(!s)return null;const i=void 0!==s[1]||void 0!==s[2];let e=s[1]??s[2]??s[3];return i&&(e=e.replace(/\\(["'\\])/g,"$1")),e}isBoundaryAhead(t,s){const i=this.pathStack.slice(0,-1);if(null!==this.matchDeclaredKey(t,i))return!0;const e=this.matchKey(t);return null!==e&&("structural"===s||("conservative"===this.options.stringCaptureStrategy||(this.walker.hasDeclaredProperties(i)?null!==this.walker.matchProperty(i,e):this.walker.isValidProperty(i,e))))}coerceValue(t,s,i){const e=Array.isArray(s.type)?s.type:s.type?[s.type]:[],r=String(t).trim();if(s.enum){const t=r.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 h=null===t?"null":typeof t;if(e.length>0&&e.includes(h))return t;if(e.includes("string"))return null===t||"object"==typeof t||"string"==typeof t?t:void 0!==i?i.trim():String(t);if(e.includes("number")||e.includes("integer")){const t=r.replace(/(?<=\d)[,,](?=\d)/g,"").match(/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?/),s=t?parseFloat(t[0]):NaN;if(!isNaN(s))return e.includes("integer")?Math.round(s):s}if(e.includes("boolean")){const t=r.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 e.includes("null")&&"null"===r.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}static NUMBER_PATTERN=/^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?/;consumeNumber(){const s=this.input.slice(this.pos).match(t.NUMBER_PATTERN);return s?(this.pos+=s[0].length,parseFloat(s[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++}};async function r(t,s,r={}){const h=s instanceof i?s:await i.create(s,r);return new e(h,r).parse(t)}export{e as RepairParser,i as SchemaWalker,r as jsonRepair};