schema-brief 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 schema-brief contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,147 @@
1
+ # schema-brief
2
+
3
+ Compact JSON Schema into LLM-ready instructions, extract JSON from model output, and validate the response with the same contract.
4
+
5
+ `schema-brief` is designed for TypeScript AI applications that need structured output without adding a heavy validation or prompt-engineering dependency. It supports the most common JSON Schema subset used for model outputs: objects, arrays, primitives, `required`, `enum`, `const`, string/number bounds, array bounds, and `additionalProperties`.
6
+
7
+ ## Why this exists
8
+
9
+ Recent JavaScript ecosystem signals point toward three strong open-source opportunities:
10
+
11
+ - TypeScript-first libraries keep gaining share across web and AI tooling.
12
+ - AI applications increasingly need reliable structured output contracts.
13
+ - Teams want small, auditable packages at LLM boundaries instead of framework lock-in.
14
+
15
+ This package sits at that boundary: one schema becomes prompt instructions, validation, and retry guidance.
16
+
17
+ ## How It Is Different
18
+
19
+ `schema-brief` is intentionally smaller than an AI framework and more LLM-focused than a general JSON Schema validator.
20
+
21
+ | Alternative | Best for | Difference |
22
+ | --- | --- | --- |
23
+ | LangChain structured output | Agent pipelines and retries inside LangChain | `schema-brief` is framework-neutral and has no provider/runtime dependency. |
24
+ | Vercel AI SDK structured output | Full-stack apps already using AI SDK | `schema-brief` can be used before or after any model call, including local models and custom SDKs. |
25
+ | AJV and JSON Schema validators | Full JSON Schema compliance and high-throughput validation | `schema-brief` optimizes for the common LLM-output subset and also generates prompt/repair text. |
26
+ | JSON extraction utilities | Pulling JSON out of messy model text | `schema-brief` couples extraction with schema prompt generation and validation feedback. |
27
+ | Zod/Valibot-based helpers | TypeScript schema-first apps | `schema-brief` starts from portable JSON Schema, which fits OpenAPI, MCP, and provider-native structured outputs. |
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ npm install schema-brief
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ```js
38
+ import { brief, parseStructured, repairPrompt } from "schema-brief";
39
+
40
+ const schema = {
41
+ title: "IssueTriage",
42
+ type: "object",
43
+ required: ["severity", "summary", "labels"],
44
+ additionalProperties: false,
45
+ properties: {
46
+ severity: { enum: ["low", "medium", "high"] },
47
+ summary: {
48
+ type: "string",
49
+ maxLength: 140,
50
+ description: "A concise human-readable issue summary"
51
+ },
52
+ labels: {
53
+ type: "array",
54
+ minItems: 1,
55
+ maxItems: 5,
56
+ items: { type: "string" }
57
+ }
58
+ }
59
+ };
60
+
61
+ const systemPrompt = brief(schema);
62
+ // Send systemPrompt to your model.
63
+
64
+ const result = parseStructured(modelText, schema);
65
+
66
+ if (!result.ok) {
67
+ const retryPrompt = repairPrompt(schema, result.issues);
68
+ // Send retryPrompt with the invalid JSON.
69
+ }
70
+ ```
71
+
72
+ ## API
73
+
74
+ ### `brief(schema, options?)`
75
+
76
+ Returns compact prompt text for a JSON Schema subset.
77
+
78
+ Options:
79
+
80
+ - `title`: override schema title in the prompt.
81
+ - `includeDescriptions`: include field descriptions. Defaults to `true`.
82
+ - `examples`: include valid JSON examples.
83
+ - `maxDepth`: limit prompt rendering depth. Defaults to `8`.
84
+
85
+ ### `extractJson(text)`
86
+
87
+ Extracts and parses the first complete JSON object or array from raw text or markdown fences.
88
+
89
+ ### `validate(schema, value)`
90
+
91
+ Validates a value against the supported JSON Schema subset.
92
+
93
+ Returns:
94
+
95
+ ```ts
96
+ { ok: true, value }
97
+ // or
98
+ { ok: false, issues: [{ path, code, message }] }
99
+ ```
100
+
101
+ ### `parseStructured(text, schema)`
102
+
103
+ Combines `extractJson` and `validate`.
104
+
105
+ ### `repairPrompt(schema, issues)`
106
+
107
+ Creates a concise prompt asking a model to repair invalid JSON.
108
+
109
+ ## Supported Schema Keywords
110
+
111
+ - `type`
112
+ - `title`
113
+ - `description`
114
+ - `enum`
115
+ - `const`
116
+ - `properties`
117
+ - `required`
118
+ - `additionalProperties`
119
+ - `items`
120
+ - `minItems`
121
+ - `maxItems`
122
+ - `minLength`
123
+ - `maxLength`
124
+ - `pattern`
125
+ - `format` for prompt output only
126
+ - `minimum`
127
+ - `maximum`
128
+
129
+ ## Product Roadmap
130
+
131
+ - Zod adapter: `briefFromZod(schema)`
132
+ - Standard Schema adapter
133
+ - OpenAI, Anthropic, and Vercel AI SDK helpers
134
+ - Token-budgeted schema compression
135
+ - Browser bundle size CI
136
+ - JSON repair suggestions with deterministic patches
137
+
138
+ ## Development
139
+
140
+ ```sh
141
+ npm test
142
+ npm run check
143
+ ```
144
+
145
+ ## License
146
+
147
+ MIT
@@ -0,0 +1,35 @@
1
+ import { brief, parseStructured, repairPrompt } from "schema-brief";
2
+
3
+ const schema = {
4
+ title: "ReleaseNote",
5
+ type: "object",
6
+ required: ["summary", "risk", "actions"],
7
+ additionalProperties: false,
8
+ properties: {
9
+ summary: {
10
+ type: "string",
11
+ maxLength: 160,
12
+ description: "One sentence summary for an engineering changelog"
13
+ },
14
+ risk: {
15
+ enum: ["low", "medium", "high"]
16
+ },
17
+ actions: {
18
+ type: "array",
19
+ minItems: 1,
20
+ items: { type: "string" }
21
+ }
22
+ }
23
+ };
24
+
25
+ const prompt = brief(schema);
26
+ console.log(prompt);
27
+
28
+ const modelOutput = `{"summary":"Adds OAuth callback validation.","risk":"low","actions":["Deploy API","Watch auth errors"]}`;
29
+ const parsed = parseStructured(modelOutput, schema);
30
+
31
+ if (!parsed.ok) {
32
+ console.log(repairPrompt(schema, parsed.issues));
33
+ } else {
34
+ console.log(parsed.value);
35
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "schema-brief",
3
+ "version": "0.1.0",
4
+ "description": "Compact JSON Schema prompts and validate structured LLM outputs with zero dependencies.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "import": "./src/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "src",
16
+ "examples",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test",
22
+ "check": "node --check src/index.js",
23
+ "prepublishOnly": "npm test && npm run check"
24
+ },
25
+ "keywords": [
26
+ "ai",
27
+ "llm",
28
+ "json-schema",
29
+ "structured-output",
30
+ "typescript",
31
+ "validation",
32
+ "prompt"
33
+ ],
34
+ "author": "",
35
+ "license": "MIT",
36
+ "sideEffects": false,
37
+ "engines": {
38
+ "node": ">=18"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/kwakhyun/schema-brief.git"
46
+ },
47
+ "bugs": {
48
+ "url": "https://github.com/kwakhyun/schema-brief/issues"
49
+ },
50
+ "homepage": "https://github.com/kwakhyun/schema-brief#readme"
51
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ export type JsonTypeName =
2
+ | "string"
3
+ | "number"
4
+ | "integer"
5
+ | "boolean"
6
+ | "null"
7
+ | "array"
8
+ | "object";
9
+
10
+ export type JsonPrimitive = string | number | boolean | null;
11
+ export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
12
+
13
+ export interface JsonSchema {
14
+ type?: JsonTypeName | JsonTypeName[];
15
+ title?: string;
16
+ description?: string;
17
+ enum?: readonly JsonValue[];
18
+ const?: JsonValue;
19
+ properties?: Record<string, JsonSchema>;
20
+ required?: readonly string[];
21
+ additionalProperties?: boolean | JsonSchema;
22
+ items?: JsonSchema | readonly JsonSchema[];
23
+ minItems?: number;
24
+ maxItems?: number;
25
+ minLength?: number;
26
+ maxLength?: number;
27
+ pattern?: string;
28
+ format?: string;
29
+ minimum?: number;
30
+ maximum?: number;
31
+ }
32
+
33
+ export interface BriefOptions {
34
+ title?: string;
35
+ includeDescriptions?: boolean;
36
+ examples?: readonly JsonValue[];
37
+ maxDepth?: number;
38
+ }
39
+
40
+ export interface ValidationIssue {
41
+ path: string;
42
+ code: string;
43
+ message: string;
44
+ }
45
+
46
+ export type ValidationResult<T = unknown> =
47
+ | { ok: true; value: T }
48
+ | { ok: false; issues: ValidationIssue[] };
49
+
50
+ export type ParseResult<T = unknown> = ValidationResult<T>;
51
+
52
+ export function brief(schema: JsonSchema, options?: BriefOptions): string;
53
+ export function extractJson(text: string): unknown;
54
+ export function validate<T = unknown>(schema: JsonSchema, value: unknown): ValidationResult<T>;
55
+ export function parseStructured<T = unknown>(text: string, schema: JsonSchema): ParseResult<T>;
56
+ export function repairPrompt(schema: JsonSchema, issues: readonly ValidationIssue[]): string;
package/src/index.js ADDED
@@ -0,0 +1,419 @@
1
+ const DEFAULT_MAX_DEPTH = 8;
2
+
3
+ /**
4
+ * Compile a JSON Schema subset into a compact, model-readable contract.
5
+ *
6
+ * @param {import("./index.d.ts").JsonSchema} schema
7
+ * @param {import("./index.d.ts").BriefOptions} [options]
8
+ * @returns {string}
9
+ */
10
+ export function brief(schema, options = {}) {
11
+ const lines = [];
12
+ const title = typeof options.title === "string" ? options.title : schema.title;
13
+ const lead = title ? `Return JSON for ${title}.` : "Return JSON that matches this schema.";
14
+
15
+ lines.push(lead);
16
+ lines.push("No markdown, comments, or extra text.");
17
+ lines.push(`Shape: ${describeSchema(schema, { depth: 0, maxDepth: options.maxDepth ?? DEFAULT_MAX_DEPTH })}`);
18
+
19
+ if (options.includeDescriptions !== false) {
20
+ const descriptions = collectDescriptions(schema);
21
+ if (descriptions.length > 0) {
22
+ lines.push("Field notes:");
23
+ for (const note of descriptions) {
24
+ lines.push(`- ${note.path}: ${note.description}`);
25
+ }
26
+ }
27
+ }
28
+
29
+ if (Array.isArray(options.examples) && options.examples.length > 0) {
30
+ lines.push("Examples:");
31
+ for (const example of options.examples) {
32
+ lines.push(stableStringify(example));
33
+ }
34
+ }
35
+
36
+ return lines.join("\n");
37
+ }
38
+
39
+ /**
40
+ * Extract the first complete JSON value from text, including fenced markdown.
41
+ *
42
+ * @param {string} text
43
+ * @returns {unknown}
44
+ */
45
+ export function extractJson(text) {
46
+ if (typeof text !== "string") {
47
+ throw new TypeError("extractJson expected a string");
48
+ }
49
+
50
+ const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
51
+ const source = fenced ? fenced[1].trim() : text.trim();
52
+
53
+ try {
54
+ return JSON.parse(source);
55
+ } catch {
56
+ const slice = firstJsonSlice(source);
57
+ if (!slice) {
58
+ throw new SyntaxError("No JSON object or array found in text");
59
+ }
60
+ return JSON.parse(slice);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Validate a value against the supported JSON Schema subset.
66
+ *
67
+ * @param {import("./index.d.ts").JsonSchema} schema
68
+ * @param {unknown} value
69
+ * @returns {import("./index.d.ts").ValidationResult}
70
+ */
71
+ export function validate(schema, value) {
72
+ const issues = [];
73
+ visit(schema, value, "$", issues, 0);
74
+ return issues.length === 0 ? { ok: true, value } : { ok: false, issues };
75
+ }
76
+
77
+ /**
78
+ * Extract and validate structured model output in one call.
79
+ *
80
+ * @param {string} text
81
+ * @param {import("./index.d.ts").JsonSchema} schema
82
+ * @returns {import("./index.d.ts").ParseResult}
83
+ */
84
+ export function parseStructured(text, schema) {
85
+ try {
86
+ const value = extractJson(text);
87
+ const result = validate(schema, value);
88
+ return result.ok ? { ok: true, value } : result;
89
+ } catch (error) {
90
+ return {
91
+ ok: false,
92
+ issues: [
93
+ {
94
+ path: "$",
95
+ code: "invalid_json",
96
+ message: error instanceof Error ? error.message : "Invalid JSON"
97
+ }
98
+ ]
99
+ };
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Create a concise repair prompt from validation issues.
105
+ *
106
+ * @param {import("./index.d.ts").JsonSchema} schema
107
+ * @param {readonly import("./index.d.ts").ValidationIssue[]} issues
108
+ * @returns {string}
109
+ */
110
+ export function repairPrompt(schema, issues) {
111
+ const bulletList = issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n");
112
+ return [
113
+ "Fix the JSON so it matches the schema.",
114
+ "Return only the corrected JSON.",
115
+ brief(schema, { includeDescriptions: true }),
116
+ "Validation errors:",
117
+ bulletList
118
+ ].join("\n");
119
+ }
120
+
121
+ function describeSchema(schema, context) {
122
+ if (context.depth > context.maxDepth) {
123
+ return "...";
124
+ }
125
+
126
+ if ("const" in schema) {
127
+ return JSON.stringify(schema.const);
128
+ }
129
+
130
+ if (Array.isArray(schema.enum)) {
131
+ return schema.enum.map((item) => JSON.stringify(item)).join(" | ");
132
+ }
133
+
134
+ const type = normalizeType(schema);
135
+
136
+ if (Array.isArray(type)) {
137
+ return type.join(" | ");
138
+ }
139
+
140
+ if (type === "object" || schema.properties) {
141
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
142
+ const props = Object.entries(schema.properties ?? {}).map(([key, child]) => {
143
+ const suffix = required.has(key) ? "" : "?";
144
+ return `${key}${suffix}: ${describeSchema(child, nextContext(context))}`;
145
+ });
146
+
147
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
148
+ props.push(`[key: string]: ${describeSchema(schema.additionalProperties, nextContext(context))}`);
149
+ } else if (schema.additionalProperties === true) {
150
+ props.push("[key: string]: unknown");
151
+ }
152
+
153
+ return `{ ${props.join("; ")} }`;
154
+ }
155
+
156
+ if (type === "array" || schema.items) {
157
+ const item = schema.items && !Array.isArray(schema.items)
158
+ ? describeSchema(schema.items, nextContext(context))
159
+ : "unknown";
160
+ const range = formatRange(schema.minItems, schema.maxItems, "items");
161
+ return `Array<${item}>${range}`;
162
+ }
163
+
164
+ if (type === "string") {
165
+ const parts = ["string"];
166
+ if (schema.format) parts.push(`format:${schema.format}`);
167
+ if (schema.pattern) parts.push(`/${schema.pattern}/`);
168
+ const range = formatRange(schema.minLength, schema.maxLength, "chars");
169
+ return `${parts.join(" ")}${range}`;
170
+ }
171
+
172
+ if (type === "number" || type === "integer") {
173
+ const range = formatRange(schema.minimum, schema.maximum, "");
174
+ return `${type}${range}`;
175
+ }
176
+
177
+ return type ?? "unknown";
178
+ }
179
+
180
+ function collectDescriptions(schema, path = "$", notes = []) {
181
+ if (typeof schema.description === "string" && schema.description.trim()) {
182
+ notes.push({ path, description: schema.description.trim() });
183
+ }
184
+
185
+ if (schema.properties) {
186
+ for (const [key, child] of Object.entries(schema.properties)) {
187
+ collectDescriptions(child, `${path}.${key}`, notes);
188
+ }
189
+ }
190
+
191
+ if (schema.items && !Array.isArray(schema.items)) {
192
+ collectDescriptions(schema.items, `${path}[]`, notes);
193
+ }
194
+
195
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
196
+ collectDescriptions(schema.additionalProperties, `${path}.*`, notes);
197
+ }
198
+
199
+ return notes;
200
+ }
201
+
202
+ function visit(schema, value, path, issues, depth) {
203
+ if (depth > DEFAULT_MAX_DEPTH * 4) {
204
+ issues.push(issue(path, "max_depth", "Value is too deeply nested"));
205
+ return;
206
+ }
207
+
208
+ if ("const" in schema && !sameJson(schema.const, value)) {
209
+ issues.push(issue(path, "const", `Expected ${stableStringify(schema.const)}`));
210
+ return;
211
+ }
212
+
213
+ if (Array.isArray(schema.enum) && !schema.enum.some((item) => sameJson(item, value))) {
214
+ issues.push(issue(path, "enum", `Expected one of ${schema.enum.map(stableStringify).join(", ")}`));
215
+ return;
216
+ }
217
+
218
+ const expected = normalizeType(schema);
219
+ if (expected && !matchesType(expected, value)) {
220
+ issues.push(issue(path, "type", `Expected ${Array.isArray(expected) ? expected.join(" or ") : expected}`));
221
+ return;
222
+ }
223
+
224
+ const type = Array.isArray(expected) ? inferType(value) : expected ?? inferType(value);
225
+
226
+ if (type === "object" && value !== null && !Array.isArray(value) && typeof value === "object") {
227
+ validateObject(schema, value, path, issues, depth);
228
+ }
229
+
230
+ if (type === "array" && Array.isArray(value)) {
231
+ validateArray(schema, value, path, issues, depth);
232
+ }
233
+
234
+ if (type === "string" && typeof value === "string") {
235
+ validateString(schema, value, path, issues);
236
+ }
237
+
238
+ if ((type === "number" || type === "integer") && typeof value === "number") {
239
+ validateNumber(schema, value, path, issues);
240
+ }
241
+ }
242
+
243
+ function validateObject(schema, value, path, issues, depth) {
244
+ const props = schema.properties ?? {};
245
+ const required = Array.isArray(schema.required) ? schema.required : [];
246
+
247
+ for (const key of required) {
248
+ if (!Object.prototype.hasOwnProperty.call(value, key)) {
249
+ issues.push(issue(`${path}.${key}`, "required", "Required property is missing"));
250
+ }
251
+ }
252
+
253
+ for (const [key, childValue] of Object.entries(value)) {
254
+ if (props[key]) {
255
+ visit(props[key], childValue, `${path}.${key}`, issues, depth + 1);
256
+ continue;
257
+ }
258
+
259
+ if (schema.additionalProperties === false) {
260
+ issues.push(issue(`${path}.${key}`, "additional_property", "Additional property is not allowed"));
261
+ } else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
262
+ visit(schema.additionalProperties, childValue, `${path}.${key}`, issues, depth + 1);
263
+ }
264
+ }
265
+ }
266
+
267
+ function validateArray(schema, value, path, issues, depth) {
268
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) {
269
+ issues.push(issue(path, "min_items", `Expected at least ${schema.minItems} items`));
270
+ }
271
+
272
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
273
+ issues.push(issue(path, "max_items", `Expected at most ${schema.maxItems} items`));
274
+ }
275
+
276
+ if (schema.items && !Array.isArray(schema.items)) {
277
+ value.forEach((itemValue, index) => {
278
+ visit(schema.items, itemValue, `${path}[${index}]`, issues, depth + 1);
279
+ });
280
+ }
281
+ }
282
+
283
+ function validateString(schema, value, path, issues) {
284
+ if (typeof schema.minLength === "number" && value.length < schema.minLength) {
285
+ issues.push(issue(path, "min_length", `Expected at least ${schema.minLength} characters`));
286
+ }
287
+
288
+ if (typeof schema.maxLength === "number" && value.length > schema.maxLength) {
289
+ issues.push(issue(path, "max_length", `Expected at most ${schema.maxLength} characters`));
290
+ }
291
+
292
+ if (typeof schema.pattern === "string") {
293
+ const pattern = new RegExp(schema.pattern);
294
+ if (!pattern.test(value)) {
295
+ issues.push(issue(path, "pattern", `Expected string to match /${schema.pattern}/`));
296
+ }
297
+ }
298
+ }
299
+
300
+ function validateNumber(schema, value, path, issues) {
301
+ if (!Number.isFinite(value)) {
302
+ issues.push(issue(path, "finite", "Expected a finite number"));
303
+ }
304
+
305
+ if (schema.type === "integer" && !Number.isInteger(value)) {
306
+ issues.push(issue(path, "integer", "Expected an integer"));
307
+ }
308
+
309
+ if (typeof schema.minimum === "number" && value < schema.minimum) {
310
+ issues.push(issue(path, "minimum", `Expected value >= ${schema.minimum}`));
311
+ }
312
+
313
+ if (typeof schema.maximum === "number" && value > schema.maximum) {
314
+ issues.push(issue(path, "maximum", `Expected value <= ${schema.maximum}`));
315
+ }
316
+ }
317
+
318
+ function normalizeType(schema) {
319
+ if (schema.type) return schema.type;
320
+ if (schema.properties) return "object";
321
+ if (schema.items) return "array";
322
+ if (typeof schema.const === "string") return "string";
323
+ if (typeof schema.const === "number") return Number.isInteger(schema.const) ? "integer" : "number";
324
+ if (typeof schema.const === "boolean") return "boolean";
325
+ if (schema.const === null) return "null";
326
+ return undefined;
327
+ }
328
+
329
+ function matchesType(expected, value) {
330
+ const actual = inferType(value);
331
+ if (Array.isArray(expected)) {
332
+ return expected.some((item) => matchesType(item, value));
333
+ }
334
+ return actual === expected || (expected === "number" && actual === "integer");
335
+ }
336
+
337
+ function inferType(value) {
338
+ if (value === null) return "null";
339
+ if (Array.isArray(value)) return "array";
340
+ if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
341
+ return typeof value;
342
+ }
343
+
344
+ function issue(path, code, message) {
345
+ return { path, code, message };
346
+ }
347
+
348
+ function nextContext(context) {
349
+ return { depth: context.depth + 1, maxDepth: context.maxDepth };
350
+ }
351
+
352
+ function formatRange(min, max, unit) {
353
+ const label = unit ? ` ${unit}` : "";
354
+ if (typeof min === "number" && typeof max === "number") return ` (${min}-${max}${label})`;
355
+ if (typeof min === "number") return ` (>=${min}${label})`;
356
+ if (typeof max === "number") return ` (<=${max}${label})`;
357
+ return "";
358
+ }
359
+
360
+ function sameJson(a, b) {
361
+ return stableStringify(a) === stableStringify(b);
362
+ }
363
+
364
+ function stableStringify(value) {
365
+ if (value === null || typeof value !== "object") {
366
+ return JSON.stringify(value);
367
+ }
368
+
369
+ if (Array.isArray(value)) {
370
+ return `[${value.map(stableStringify).join(",")}]`;
371
+ }
372
+
373
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
374
+ return `{${entries.map(([key, child]) => `${JSON.stringify(key)}:${stableStringify(child)}`).join(",")}}`;
375
+ }
376
+
377
+ function firstJsonSlice(source) {
378
+ for (let index = 0; index < source.length; index += 1) {
379
+ const char = source[index];
380
+ if (char !== "{" && char !== "[") continue;
381
+
382
+ const close = char === "{" ? "}" : "]";
383
+ const stack = [close];
384
+ let inString = false;
385
+ let escaped = false;
386
+
387
+ for (let cursor = index + 1; cursor < source.length; cursor += 1) {
388
+ const current = source[cursor];
389
+
390
+ if (escaped) {
391
+ escaped = false;
392
+ continue;
393
+ }
394
+
395
+ if (current === "\\") {
396
+ escaped = inString;
397
+ continue;
398
+ }
399
+
400
+ if (current === "\"") {
401
+ inString = !inString;
402
+ continue;
403
+ }
404
+
405
+ if (inString) continue;
406
+
407
+ if (current === "{" || current === "[") {
408
+ stack.push(current === "{" ? "}" : "]");
409
+ } else if (current === "}" || current === "]") {
410
+ if (current !== stack.pop()) break;
411
+ if (stack.length === 0) {
412
+ return source.slice(index, cursor + 1);
413
+ }
414
+ }
415
+ }
416
+ }
417
+
418
+ return "";
419
+ }