@orkestrel/contract 0.0.4 → 0.0.6

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.
@@ -27,6 +27,86 @@ var JSON_SCHEMA_TYPES = Object.freeze([
27
27
  "integer",
28
28
  "string"
29
29
  ]);
30
+ /**
31
+ * The maximum number of {@link Fault} entries a single `explain` report ever
32
+ * returns, frozen.
33
+ *
34
+ * @remarks
35
+ * Bounds the report against adversarial input (a giant array, a wide record) —
36
+ * `compileReporter` collects faults in stable pre-order and stops once this cap
37
+ * is reached, so the report size (and the work to build it) stays finite and
38
+ * deterministic regardless of the input's size.
39
+ */
40
+ var FAULT_LIMIT = 64;
41
+ /**
42
+ * The maximum character length of a {@link preview}-rendered string, frozen.
43
+ *
44
+ * @remarks
45
+ * A previewed string longer than this is clipped with a trailing `…` so a
46
+ * {@link Fault}'s `received` field never embeds an unbounded amount of
47
+ * untrusted text.
48
+ */
49
+ var PREVIEW_LIMIT = 64;
50
+ /**
51
+ * The default maximum object/array nesting depth {@link valueToSchema} walks,
52
+ * frozen.
53
+ *
54
+ * @remarks
55
+ * Bounds inference against adversarial or cyclic runtime input — once the
56
+ * remaining depth budget reaches zero, inference stops descending and emits
57
+ * the empty accept-anything schema `{}` for that branch instead of recursing
58
+ * further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.
59
+ */
60
+ var INFER_DEPTH_LIMIT = 32;
61
+ /**
62
+ * The default maximum number of object properties / array elements
63
+ * {@link valueToSchema} samples per container, frozen.
64
+ *
65
+ * @remarks
66
+ * Bounds the work (and the emitted schema's size) against a wide record or a
67
+ * huge array — properties/elements beyond this cap are never inspected.
68
+ * Overridable per call via {@link ValueToSchemaOptions.maxProperties}.
69
+ */
70
+ var INFER_BREADTH_LIMIT = 256;
71
+ /**
72
+ * The default maximum number of distinct values a multi-sample slot may hold
73
+ * before enum inference gives up and falls back to a bare `type`, frozen.
74
+ *
75
+ * @remarks
76
+ * Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples}
77
+ * will emit — a slot with distinct-value count at or above this limit is
78
+ * treated as unbounded (an ID column, not a category) and never gets an
79
+ * `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum}
80
+ * (which gates whether enum inference runs at all).
81
+ */
82
+ var INFER_ENUM_LIMIT = 12;
83
+ /**
84
+ * The maximum string length {@link stringToFormat} attempts to classify,
85
+ * frozen.
86
+ *
87
+ * @remarks
88
+ * Bounds per-string format-detection work: a value longer than this returns
89
+ * `undefined` immediately, before any pattern match runs. 128 sits
90
+ * comfortably above the longest real format token — an RFC 3339 date-time
91
+ * with fractional seconds and a UTC offset — so no legitimate classification
92
+ * changes; only pathologically long strings (a multi-megabyte payload passed
93
+ * as a candidate email/URI) are skipped.
94
+ */
95
+ var FORMAT_MAX_LENGTH = 128;
96
+ /**
97
+ * Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats
98
+ * (`uuid` / `email` / `uri`), frozen as data.
99
+ *
100
+ * @remarks
101
+ * The ISO-8601 date/time formats are NOT listed here — they additionally
102
+ * require an attempt-guarded `Date` validity check, so their pattern lives
103
+ * inline in `stringToFormat` rather than as reusable standalone data.
104
+ */
105
+ var FORMAT_PATTERNS = Object.freeze({
106
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
107
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
108
+ uri: /^[a-z][a-z0-9+.-]*:\/\//i
109
+ });
30
110
  //#endregion
31
111
  //#region src/core/validators.ts
32
112
  /** Determine whether a value is `null`.
@@ -1080,6 +1160,142 @@ function enumerableSymbolCount(value) {
1080
1160
  function schemaToParameters(schema) {
1081
1161
  return isRecord(schema) ? schema : void 0;
1082
1162
  }
1163
+ /**
1164
+ * Wrap a non-object `JSONSchema` root in a single-property object schema, so
1165
+ * an inferred primitive/array/union schema can flow into {@link schemaToParameters}
1166
+ * as an MCP-compatible `inputSchema`.
1167
+ *
1168
+ * @remarks
1169
+ * Total and deterministic. `schema.type === 'object'` passes through
1170
+ * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only
1171
+ * schema with no `type`, or the empty `{}`) is wrapped as a single required
1172
+ * `value` property: `{ type: 'object', properties: { value: schema },
1173
+ * required: ['value'], additionalProperties: false }`. Composition:
1174
+ * `schemaToParameters(schemaToObject(valueToSchema(payload)))`.
1175
+ *
1176
+ * @param schema - The schema to wrap
1177
+ * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema
1178
+ *
1179
+ * @example
1180
+ * ```ts
1181
+ * schemaToObject({ type: 'string' })
1182
+ * // { type: 'object', properties: { value: { type: 'string' } },
1183
+ * // required: ['value'], additionalProperties: false }
1184
+ * schemaToObject({ type: 'object', properties: {} }) // unchanged
1185
+ * ```
1186
+ */
1187
+ function schemaToObject(schema) {
1188
+ if (schema.type === "object") return schema;
1189
+ return {
1190
+ type: "object",
1191
+ properties: { value: schema },
1192
+ required: ["value"],
1193
+ additionalProperties: false
1194
+ };
1195
+ }
1196
+ /**
1197
+ * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to
1198
+ * a finite non-negative integer, falling back to a default for anything else.
1199
+ *
1200
+ * @remarks
1201
+ * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or
1202
+ * malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard
1203
+ * (`NaN <= 0` is `false`, so recursion never halts), and a negative
1204
+ * `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key
1205
+ * instead of capping the list (a fractional value has a similarly undefined
1206
+ * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`
1207
+ * is `false` — since an unbounded budget is exactly the adversarial case the
1208
+ * caps exist to prevent. A valid finite non-negative integer passes through
1209
+ * unchanged.
1210
+ *
1211
+ * @param value - The candidate budget value
1212
+ * @param fallback - The default to use when `value` is not a finite
1213
+ * non-negative integer
1214
+ * @returns A finite non-negative integer budget
1215
+ *
1216
+ * @example
1217
+ * ```ts
1218
+ * sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT
1219
+ * sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT
1220
+ * sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4
1221
+ * ```
1222
+ */
1223
+ function sanitizeBudget(value, fallback) {
1224
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : fallback;
1225
+ }
1226
+ /**
1227
+ * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s
1228
+ * `received` field.
1229
+ *
1230
+ * @remarks
1231
+ * A primitive renders as its literal: a string is `JSON.stringify`-escaped and
1232
+ * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when
1233
+ * clipped); a number / boolean / bigint / symbol renders via `String`; `null`
1234
+ * and `undefined` render as their own name. Everything else — a plain object,
1235
+ * an array, a function, a class instance, a `Map` — is NEVER traversed or
1236
+ * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),
1237
+ * so a hostile or enormous structure can never blow up the preview.
1238
+ *
1239
+ * @param value - The value to preview
1240
+ * @returns A short descriptive string, always safe to embed in a diagnostic
1241
+ *
1242
+ * @example
1243
+ * ```ts
1244
+ * preview('hi') // '"hi"'
1245
+ * preview(42) // '42'
1246
+ * preview(null) // 'null'
1247
+ * preview({ a: 1 }) // 'object'
1248
+ * preview([1, 2, 3]) // 'object'
1249
+ * ```
1250
+ */
1251
+ function preview(value) {
1252
+ if (value === null) return "null";
1253
+ if (value === void 0) return "undefined";
1254
+ if (isString(value)) {
1255
+ const text = JSON.stringify(value);
1256
+ return text.length > 64 ? `${text.slice(0, 64)}…` : text;
1257
+ }
1258
+ if (isNumber(value) || isBoolean(value)) return String(value);
1259
+ if (isBigInt(value)) return `${value}n`;
1260
+ if (isSymbol(value)) return value.toString();
1261
+ return typeof value;
1262
+ }
1263
+ /**
1264
+ * Project a {@link ContractShape} to the {@link FaultKind} it describes.
1265
+ *
1266
+ * @remarks
1267
+ * A structural mapping used by {@link compileReporter} to fill a `Fault`'s
1268
+ * `expected` field: most shapes map to their own `type` (`numberShape` maps to
1269
+ * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
1270
+ * `nullableShape` project through to their inner shape's kind, and `rawShape`
1271
+ * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
1272
+ *
1273
+ * @param shape - The shape to project
1274
+ * @returns The shape's {@link FaultKind}
1275
+ *
1276
+ * @example
1277
+ * ```ts
1278
+ * shapeToKind(stringShape()) // 'string'
1279
+ * shapeToKind(integerShape()) // 'integer'
1280
+ * shapeToKind(optionalShape(nullShape())) // 'null'
1281
+ * ```
1282
+ */
1283
+ function shapeToKind(shape) {
1284
+ switch (shape.type) {
1285
+ case "string": return "string";
1286
+ case "number": return shape.integer === true ? "integer" : "number";
1287
+ case "boolean": return "boolean";
1288
+ case "null": return "null";
1289
+ case "literal": return "literal";
1290
+ case "array": return "array";
1291
+ case "object": return "object";
1292
+ case "union": return "union";
1293
+ case "json": return "json";
1294
+ case "optional": return shapeToKind(shape.inner);
1295
+ case "nullable": return shapeToKind(shape.inner);
1296
+ case "raw": return "json";
1297
+ }
1298
+ }
1083
1299
  //#endregion
1084
1300
  //#region src/core/combinators.ts
1085
1301
  function arrayOf(elementGuard) {
@@ -2257,6 +2473,260 @@ function compileGenerator(shape, random = seededRandom(Date.now())) {
2257
2473
  case "raw": throw new Error("compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way");
2258
2474
  }
2259
2475
  }
2476
+ /**
2477
+ * Compile a {@link ContractShape} into a structured fault report for a value —
2478
+ * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.
2479
+ *
2480
+ * @remarks
2481
+ * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards
2482
+ * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /
2483
+ * `isJSONValue` / …), so the soundness invariant
2484
+ * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`
2485
+ * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a
2486
+ * coercible value like `'42'` against a `numberShape` reports no fault, the
2487
+ * same leniency `parse` grants, even though the strict guard would reject it).
2488
+ *
2489
+ * Faults are collected in stable pre-order (declared key/index order); every
2490
+ * call — object, array, and union alike, including a union's `oneOf` "no
2491
+ * match" / "no consensus" summary fault prepended to its closest variant's
2492
+ * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the
2493
+ * bound holds at every level of nesting, not just the outermost container, on
2494
+ * adversarial input (a huge array, a wide record, a wide union of wide
2495
+ * records). A closed object's extra keys never
2496
+ * fault — `parse` silently drops them, so `explain` mirrors that leniency; an
2497
+ * open object with a constraining `additionalProperties` shape recurses extras
2498
+ * against it instead. A hostile getter or throwing `Proxy` trap is contained
2499
+ * via {@link attempt} and surfaces as a single top-level type fault, never a
2500
+ * throw (AGENTS §14).
2501
+ *
2502
+ * @param shape - The shape to report against
2503
+ * @param value - The value to check
2504
+ * @param path - The path prefix for faults produced at this call (defaults to the root)
2505
+ * @returns The faults found, empty when the value parses successfully
2506
+ *
2507
+ * @example
2508
+ * ```ts
2509
+ * const user = objectShape({ name: stringShape({ min: 1 }) })
2510
+ * compileReporter(user, { name: '' })
2511
+ * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '""' }]
2512
+ * compileReporter(user, { name: 'Ada' }) // []
2513
+ * ```
2514
+ */
2515
+ function compileReporter(shape, value, path = []) {
2516
+ switch (shape.type) {
2517
+ case "string": {
2518
+ const parsed = parseString(value);
2519
+ if (parsed === void 0) return [{
2520
+ reason: "type",
2521
+ path,
2522
+ expected: "string",
2523
+ received: preview(value)
2524
+ }];
2525
+ const faults = [];
2526
+ if (shape.min !== void 0 && parsed.length < shape.min) faults.push({
2527
+ reason: "constraint",
2528
+ path,
2529
+ expected: "string",
2530
+ constraint: "min",
2531
+ limit: shape.min,
2532
+ received: preview(parsed)
2533
+ });
2534
+ if (shape.max !== void 0 && parsed.length > shape.max) faults.push({
2535
+ reason: "constraint",
2536
+ path,
2537
+ expected: "string",
2538
+ constraint: "max",
2539
+ limit: shape.max,
2540
+ received: preview(parsed)
2541
+ });
2542
+ if (shape.pattern !== void 0 && !shape.pattern.test(parsed)) faults.push({
2543
+ reason: "constraint",
2544
+ path,
2545
+ expected: "string",
2546
+ constraint: "pattern",
2547
+ limit: shape.pattern.source,
2548
+ received: preview(parsed)
2549
+ });
2550
+ return faults;
2551
+ }
2552
+ case "number": {
2553
+ const kind = shape.integer === true ? "integer" : "number";
2554
+ const parsed = parseNumber(value);
2555
+ if (parsed === void 0) return [{
2556
+ reason: "type",
2557
+ path,
2558
+ expected: kind,
2559
+ received: preview(value)
2560
+ }];
2561
+ const faults = [];
2562
+ if (shape.integer === true && !Number.isInteger(parsed)) faults.push({
2563
+ reason: "constraint",
2564
+ path,
2565
+ expected: kind,
2566
+ constraint: "integer",
2567
+ received: preview(parsed)
2568
+ });
2569
+ if (shape.min !== void 0 && parsed < shape.min) faults.push({
2570
+ reason: "constraint",
2571
+ path,
2572
+ expected: kind,
2573
+ constraint: "min",
2574
+ limit: shape.min,
2575
+ received: preview(parsed)
2576
+ });
2577
+ if (shape.max !== void 0 && parsed > shape.max) faults.push({
2578
+ reason: "constraint",
2579
+ path,
2580
+ expected: kind,
2581
+ constraint: "max",
2582
+ limit: shape.max,
2583
+ received: preview(parsed)
2584
+ });
2585
+ return faults;
2586
+ }
2587
+ case "boolean": return parseBoolean(value) === void 0 ? [{
2588
+ reason: "type",
2589
+ path,
2590
+ expected: "boolean",
2591
+ received: preview(value)
2592
+ }] : [];
2593
+ case "null": return value === null ? [] : [{
2594
+ reason: "type",
2595
+ path,
2596
+ expected: "null",
2597
+ received: preview(value)
2598
+ }];
2599
+ case "json": return isJSONValue(value) ? [] : [{
2600
+ reason: "type",
2601
+ path,
2602
+ expected: "json",
2603
+ received: preview(value)
2604
+ }];
2605
+ case "literal": {
2606
+ const allowed = new Set(shape.values);
2607
+ return allowed.has(value) || isString(value) && allowed.has(value.trim()) ? [] : [{
2608
+ reason: "type",
2609
+ path,
2610
+ expected: "literal",
2611
+ received: preview(value)
2612
+ }];
2613
+ }
2614
+ case "array": {
2615
+ if (!isArray(value)) return [{
2616
+ reason: "type",
2617
+ path,
2618
+ expected: "array",
2619
+ received: preview(value)
2620
+ }];
2621
+ const faults = [];
2622
+ if (!attempt(() => {
2623
+ for (let index = 0; index < value.length; index += 1) {
2624
+ if (faults.length >= 64) return;
2625
+ faults.push(...compileReporter(shape.items, value[index], [...path, String(index)]));
2626
+ }
2627
+ }).success) return [{
2628
+ reason: "type",
2629
+ path,
2630
+ expected: "array",
2631
+ received: preview(value)
2632
+ }];
2633
+ if (shape.min !== void 0 && value.length < shape.min) faults.push({
2634
+ reason: "constraint",
2635
+ path,
2636
+ expected: "array",
2637
+ constraint: "min",
2638
+ limit: shape.min,
2639
+ received: String(value.length)
2640
+ });
2641
+ if (shape.max !== void 0 && value.length > shape.max) faults.push({
2642
+ reason: "constraint",
2643
+ path,
2644
+ expected: "array",
2645
+ constraint: "max",
2646
+ limit: shape.max,
2647
+ received: String(value.length)
2648
+ });
2649
+ return faults.length > 64 ? faults.slice(0, 64) : faults;
2650
+ }
2651
+ case "object": {
2652
+ if (!isRecord(value)) return [{
2653
+ reason: "type",
2654
+ path,
2655
+ expected: "object",
2656
+ received: preview(value)
2657
+ }];
2658
+ const record = value;
2659
+ const faults = [];
2660
+ const known = /* @__PURE__ */ new Set();
2661
+ if (!attempt(() => {
2662
+ for (const key of Object.keys(shape.properties)) {
2663
+ if (faults.length >= 64) return;
2664
+ const child = shape.properties[key];
2665
+ if (child === void 0) continue;
2666
+ known.add(key);
2667
+ const optional = child.type === "optional";
2668
+ const inner = optional ? child.inner : child;
2669
+ const raw = record[key];
2670
+ if (raw === void 0) {
2671
+ if (!optional) faults.push({
2672
+ reason: "missing",
2673
+ path: [...path, key],
2674
+ expected: shapeToKind(inner)
2675
+ });
2676
+ continue;
2677
+ }
2678
+ faults.push(...compileReporter(inner, raw, [...path, key]));
2679
+ }
2680
+ const extra = shape.additionalProperties;
2681
+ if (extra !== void 0 && extra !== true && extra !== false) for (const key of Object.keys(record)) {
2682
+ if (faults.length >= 64) return;
2683
+ if (known.has(key)) continue;
2684
+ faults.push(...compileReporter(extra, record[key], [...path, key]));
2685
+ }
2686
+ }).success) return [{
2687
+ reason: "type",
2688
+ path,
2689
+ expected: "object",
2690
+ received: preview(value)
2691
+ }];
2692
+ return faults.length > 64 ? faults.slice(0, 64) : faults;
2693
+ }
2694
+ case "union": {
2695
+ const perVariant = shape.variants.map((variant) => compileReporter(variant, value, path));
2696
+ let bestIndex = 0;
2697
+ for (let index = 1; index < perVariant.length; index += 1) {
2698
+ const current = perVariant[index];
2699
+ const best = perVariant[bestIndex];
2700
+ if (current !== void 0 && best !== void 0 && current.length < best.length) bestIndex = index;
2701
+ }
2702
+ const closest = perVariant[bestIndex] ?? [];
2703
+ if (shape.mode === "oneOf") {
2704
+ let matched = 0;
2705
+ for (const variant of shape.variants) if (compileGuard(variant)(value)) matched += 1;
2706
+ if (matched === 1) return [];
2707
+ if (matched === 0) return [{
2708
+ reason: "oneOf",
2709
+ path,
2710
+ matched: 0
2711
+ }, ...closest].slice(0, 64);
2712
+ return [{
2713
+ reason: "oneOf",
2714
+ path,
2715
+ matched
2716
+ }];
2717
+ }
2718
+ if (perVariant.some((variantFaults) => variantFaults.length === 0)) return [];
2719
+ return [{
2720
+ reason: "variant",
2721
+ path,
2722
+ variants: shape.variants.length
2723
+ }, ...closest].slice(0, 64);
2724
+ }
2725
+ case "optional": return value === void 0 ? [] : compileReporter(shape.inner, value, path);
2726
+ case "nullable": return value === null ? [] : compileReporter(shape.inner, value, path);
2727
+ case "raw": return [];
2728
+ }
2729
+ }
2260
2730
  function createContract(shape) {
2261
2731
  validateShape(shape);
2262
2732
  const schema = compileSchema(shape);
@@ -2268,12 +2738,599 @@ function createContract(shape) {
2268
2738
  parse(value) {
2269
2739
  return parser(value);
2270
2740
  },
2741
+ explain(value) {
2742
+ return compileReporter(shape, value);
2743
+ },
2271
2744
  generate(random) {
2272
2745
  return compileGenerator(shape, random);
2273
2746
  }
2274
2747
  };
2275
2748
  }
2276
2749
  //#endregion
2750
+ //#region src/core/inferers.ts
2751
+ /**
2752
+ * Render a value as a deterministic, key-sorted JSON string.
2753
+ *
2754
+ * @remarks
2755
+ * The stable-stringify backing {@link unifySchemas}'s de-duplication and
2756
+ * ordering: unlike `JSON.stringify`, object keys are sorted before encoding
2757
+ * (recursively, at every nesting level), so two structurally-equal
2758
+ * `JSONSchema` fragments built independently always canonicalize to the same
2759
+ * string. Pure ECMAScript — no `structuredClone`, no `node:*` import.
2760
+ *
2761
+ * @param value - The value to canonicalize (a `JSONSchema` fragment, or any
2762
+ * nested piece of one)
2763
+ * @returns A deterministic string encoding of `value`
2764
+ *
2765
+ * @example
2766
+ * ```ts
2767
+ * canonicalStringify({ type: 'object', properties: {} }) ===
2768
+ * canonicalStringify({ properties: {}, type: 'object' }) // true
2769
+ * ```
2770
+ */
2771
+ function canonicalStringify(value) {
2772
+ if (isArray(value)) return `[${value.map((entry) => canonicalStringify(entry)).join(",")}]`;
2773
+ if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(value[key])}`).join(",")}}`;
2774
+ return JSON.stringify(value);
2775
+ }
2776
+ /**
2777
+ * Unify a list of inferred `JSONSchema` fragments into one schema.
2778
+ *
2779
+ * @remarks
2780
+ * De-duplicates by {@link canonicalStringify}, then applies the one
2781
+ * special-case subsumption inference performs: a bare `{ type: 'integer' }`
2782
+ * alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }`
2783
+ * (an integer sample is also a valid `number` sample). A single surviving
2784
+ * distinct schema is returned directly; two or more are wrapped as
2785
+ * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
2786
+ * An empty input list returns the empty accept-anything schema `{}`.
2787
+ *
2788
+ * @param schemas - The schemas to unify
2789
+ * @returns The unified schema
2790
+ *
2791
+ * @example
2792
+ * ```ts
2793
+ * unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' }
2794
+ * unifySchemas([{ type: 'string' }, { type: 'boolean' }])
2795
+ * // { anyOf: [{ type: 'boolean' }, { type: 'string' }] }
2796
+ * ```
2797
+ */
2798
+ function unifySchemas(schemas) {
2799
+ if (schemas.length === 0) return {};
2800
+ const seen = /* @__PURE__ */ new Map();
2801
+ for (const schema of schemas) {
2802
+ const key = canonicalStringify(schema);
2803
+ if (!seen.has(key)) seen.set(key, schema);
2804
+ }
2805
+ const integerKey = canonicalStringify({ type: "integer" });
2806
+ const numberKey = canonicalStringify({ type: "number" });
2807
+ if (seen.has(integerKey) && seen.has(numberKey)) seen.delete(integerKey);
2808
+ const distinct = [...seen.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, schema]) => schema);
2809
+ if (distinct.length <= 1) {
2810
+ const [only] = distinct;
2811
+ return only ?? {};
2812
+ }
2813
+ return { anyOf: distinct };
2814
+ }
2815
+ /**
2816
+ * Determine whether an ISO-8601-shaped string parses to a valid instant.
2817
+ *
2818
+ * @remarks
2819
+ * A pure, attempt-guarded `Date` validity probe: `new Date(value)` never
2820
+ * throws on a string input, but a value like `2020-13-45` parses to an
2821
+ * `Invalid Date` whose `getTime()` is `NaN` — this is the real validation
2822
+ * step behind {@link stringToFormat}'s `date` / `date-time` / `time`
2823
+ * branches, which pattern-match the shape first and confirm validity here.
2824
+ *
2825
+ * @param value - The candidate ISO-8601 string
2826
+ * @returns `true` when `value` parses to a real instant
2827
+ *
2828
+ * @example
2829
+ * ```ts
2830
+ * isValidISOInstant('2020-01-01') // true
2831
+ * isValidISOInstant('2020-13-45') // false
2832
+ * ```
2833
+ */
2834
+ function isValidISOInstant(value) {
2835
+ const outcome = attempt(() => {
2836
+ const date = new Date(value);
2837
+ return !Number.isNaN(date.getTime());
2838
+ });
2839
+ return outcome.success && outcome.value;
2840
+ }
2841
+ /**
2842
+ * Classify a string against the {@link SchemaFormat} vocabulary.
2843
+ *
2844
+ * @remarks
2845
+ * Total, pure, and deterministic. Fixed precedence, most specific first:
2846
+ * `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first
2847
+ * match wins. The `date-time` / `date` / `time` branches require BOTH a
2848
+ * strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity
2849
+ * check, so a shape-plausible but impossible date (`2020-13-45`) is rejected.
2850
+ * Returns `undefined` when no format matches (including the empty string).
2851
+ *
2852
+ * @param value - The string to classify
2853
+ * @returns The matched {@link SchemaFormat}, or `undefined`
2854
+ *
2855
+ * @example
2856
+ * ```ts
2857
+ * stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid'
2858
+ * stringToFormat('2024-01-15') // 'date'
2859
+ * stringToFormat('2020-13-45') // undefined — invalid date
2860
+ * stringToFormat('ada@example.com') // 'email'
2861
+ * stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset
2862
+ * stringToFormat('10:30:00+02:00') // 'time'
2863
+ * ```
2864
+ */
2865
+ function stringToFormat(value) {
2866
+ if (value.length > 128) return void 0;
2867
+ if (FORMAT_PATTERNS.uuid.test(value)) return "uuid";
2868
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(value) && isValidISOInstant(value)) return "date-time";
2869
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value) && isValidISOInstant(value)) return "date";
2870
+ if (/^\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(value) && isValidISOInstant(`1970-01-01T${value}`)) return "time";
2871
+ if (FORMAT_PATTERNS.email.test(value)) return "email";
2872
+ if (FORMAT_PATTERNS.uri.test(value)) return "uri";
2873
+ }
2874
+ /**
2875
+ * Classify a list of sample values against the {@link SchemaFormat}
2876
+ * vocabulary, requiring unanimity.
2877
+ *
2878
+ * @remarks
2879
+ * A format is returned ONLY IF every value is a string AND every one maps to
2880
+ * the SAME {@link stringToFormat} result (including all mapping to
2881
+ * `undefined`, which itself returns `undefined` here). A single disagreeing
2882
+ * value, a non-string value, or an empty list all yield `undefined` — the
2883
+ * multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples})
2884
+ * relies on this unanimity so a slot with mixed string shapes emits a bare
2885
+ * `{ type: 'string' }` rather than an `anyOf` of formats.
2886
+ *
2887
+ * @param values - The sample values to classify
2888
+ * @returns The unanimous {@link SchemaFormat}, or `undefined`
2889
+ *
2890
+ * @example
2891
+ * ```ts
2892
+ * samplesToFormat(['2024-01-01', '2024-02-02']) // 'date'
2893
+ * samplesToFormat(['2024-01-01', 'not a date']) // undefined
2894
+ * samplesToFormat([]) // undefined
2895
+ * ```
2896
+ */
2897
+ function samplesToFormat(values) {
2898
+ if (values.length === 0 || !values.every((value) => isString(value))) return void 0;
2899
+ const [first, ...rest] = values.map((value) => stringToFormat(value));
2900
+ if (first === void 0) return void 0;
2901
+ return rest.every((format) => format === first) ? first : void 0;
2902
+ }
2903
+ /**
2904
+ * Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated
2905
+ * primitive slot — the multi-sample-only counterpart to
2906
+ * {@link stringToFormat} ({@link valueToSchema} never emits `enum`).
2907
+ *
2908
+ * @remarks
2909
+ * Fires only when ALL of: every value is the same primitive kind (all string
2910
+ * or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed
2911
+ * slot never qualifies, and a slot containing `NaN` / `±Infinity` never
2912
+ * qualifies either, since {@link canonicalStringify} collapses `NaN` to
2913
+ * `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2
2914
+ * values are given; the distinct-by-{@link canonicalStringify} count is LESS
2915
+ * than the value count (repetition required — separates a categorical column
2916
+ * from an ID column); and the distinct count is at most `limit`. The emitted
2917
+ * schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s
2918
+ * `literalShape` emission. Members are sorted by canonical key for
2919
+ * deterministic output.
2920
+ *
2921
+ * @param values - The collected slot values
2922
+ * @param limit - The maximum distinct-value count before giving up
2923
+ * @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
2924
+ *
2925
+ * @example
2926
+ * ```ts
2927
+ * inferPrimitiveEnum(['active', 'inactive', 'active'], 12)
2928
+ * // { enum: ['active', 'inactive'] }
2929
+ * inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition
2930
+ * ```
2931
+ */
2932
+ function inferPrimitiveEnum(values, limit) {
2933
+ if (values.length < 2) return void 0;
2934
+ const allString = values.every((value) => isString(value));
2935
+ const allNumber = !allString && values.every((value) => isFiniteNumber(value));
2936
+ if (!allString && !allNumber) return void 0;
2937
+ const distinct = /* @__PURE__ */ new Map();
2938
+ for (const value of values) if (isString(value) || isFiniteNumber(value)) distinct.set(canonicalStringify(value), value);
2939
+ if (distinct.size >= values.length || distinct.size > limit) return void 0;
2940
+ return { enum: [...distinct.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([, value]) => value) };
2941
+ }
2942
+ /**
2943
+ * Infer a `JSONSchema` fragment for one runtime value — the recursive spine
2944
+ * shared by {@link valueToSchema} and, per collected property/element, by
2945
+ * {@link inferArray} / {@link inferObject}.
2946
+ *
2947
+ * @remarks
2948
+ * Total: never throws, and terminates on cyclic input via `visited`. Leaf
2949
+ * classification order: `null`, boolean, integer (`Number.isInteger`
2950
+ * semantics — `-0` counts), finite non-integer number, non-finite number
2951
+ * (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
2952
+ * `format` keyword when `format` is on and {@link stringToFormat} matches),
2953
+ * array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
2954
+ * plus `format: 'date-time'` when `format` is on); everything else
2955
+ * (function, symbol, bigint, `undefined`, and other non-plain objects such as
2956
+ * `Map` / `Set`) is the empty accept-anything schema `{}`.
2957
+ *
2958
+ * @param value - The value to classify
2959
+ * @param depth - Remaining descent budget (0 halts recursion with `{}`)
2960
+ * @param breadth - The per-container sampling cap passed through to children
2961
+ * @param closed - Whether descended objects emit `additionalProperties: false`
2962
+ * @param format - Whether a string/`Date` leaf gains a `format` keyword
2963
+ * @param visited - The ancestor set guarding against cycles
2964
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
2965
+ * against exponential re-inference of a shared-reference DAG
2966
+ * @returns The inferred schema fragment for `value`
2967
+ *
2968
+ * @example
2969
+ * ```ts
2970
+ * inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' }
2971
+ * ```
2972
+ */
2973
+ function inferValue(value, depth, breadth, closed, format, visited, memo) {
2974
+ if (isNull(value)) return { type: "null" };
2975
+ if (isBoolean(value)) return { type: "boolean" };
2976
+ if (isInteger(value)) return { type: "integer" };
2977
+ if (isFiniteNumber(value)) return { type: "number" };
2978
+ if (isNumber(value)) return { type: "number" };
2979
+ if (isString(value)) {
2980
+ if (format) {
2981
+ const detected = stringToFormat(value);
2982
+ if (detected) return {
2983
+ type: "string",
2984
+ format: detected
2985
+ };
2986
+ }
2987
+ return { type: "string" };
2988
+ }
2989
+ if (isArray(value)) return inferArray(value, depth, breadth, closed, format, visited, memo);
2990
+ if (isRecord(value)) return inferObject(value, depth, breadth, closed, format, visited, memo);
2991
+ if (isDate(value)) return format ? {
2992
+ type: "string",
2993
+ format: "date-time"
2994
+ } : { type: "string" };
2995
+ return {};
2996
+ }
2997
+ /**
2998
+ * Infer a `JSONSchema` array fragment from an array's sampled elements.
2999
+ *
3000
+ * @remarks
3001
+ * An empty array infers `{ type: 'array' }` with no `items`. Otherwise the
3002
+ * first `breadth` elements are classified via {@link inferValue} (one less
3003
+ * depth) and unified with {@link unifySchemas}: a single distinct element
3004
+ * schema becomes `items` directly; multiple distinct schemas become
3005
+ * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of
3006
+ * `value` both yield the empty schema `{}` instead of descending. A sparse
3007
+ * array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before
3008
+ * sampling so every slot — including a hole — is visited as an explicit
3009
+ * `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left
3010
+ * as a hole that would otherwise reach {@link unifySchemas} as `undefined`.
3011
+ *
3012
+ * ALL reads of `value` — including its `length` — happen inside
3013
+ * {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose
3014
+ * `get` trap throws) is exactly as contained as a throwing own-getter element
3015
+ * or a Proxy-over-array element access, and cannot escape as a thrown error.
3016
+ * On failure — or when the sampled/classified list ends up empty — this
3017
+ * returns `{ type: 'array' }` (no `items`), since `value` is still known to
3018
+ * be an array, mirroring the empty-array emission. A same-object
3019
+ * re-inference at the same remaining `depth` is served from `memo` instead
3020
+ * of recomputing (guards a shared-reference DAG against exponential blowup).
3021
+ *
3022
+ * @param value - The array to infer from
3023
+ * @param depth - Remaining descent budget
3024
+ * @param breadth - The maximum number of elements sampled
3025
+ * @param closed - Threaded through to nested object elements
3026
+ * @param format - Threaded through to nested string/`Date` elements
3027
+ * @param visited - The ancestor set guarding against cycles
3028
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
3029
+ * against exponential re-inference of a shared-reference DAG
3030
+ * @returns The inferred array schema
3031
+ *
3032
+ * @example
3033
+ * ```ts
3034
+ * inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap())
3035
+ * // { type: 'array', items: { type: 'number' } }
3036
+ * ```
3037
+ */
3038
+ function inferArray(value, depth, breadth, closed, format, visited, memo) {
3039
+ if (!(depth > 0) || visited.has(value)) return {};
3040
+ const cached = memo.get(value)?.get(depth);
3041
+ if (cached) return cached;
3042
+ visited.add(value);
3043
+ const outcome = attempt(() => {
3044
+ return Array.from(value.slice(0, breadth)).map((entry) => inferValue(entry, depth - 1, breadth, closed, format, visited, memo));
3045
+ });
3046
+ visited.delete(value);
3047
+ const schema = outcome.success && outcome.value.length > 0 ? {
3048
+ type: "array",
3049
+ items: unifySchemas(outcome.value)
3050
+ } : { type: "array" };
3051
+ let depths = memo.get(value);
3052
+ if (!depths) {
3053
+ depths = /* @__PURE__ */ new Map();
3054
+ memo.set(value, depths);
3055
+ }
3056
+ depths.set(depth, schema);
3057
+ return schema;
3058
+ }
3059
+ /**
3060
+ * Infer a `JSONSchema` object fragment from a plain record's sampled
3061
+ * properties.
3062
+ *
3063
+ * @remarks
3064
+ * Own enumerable string keys via `Object.keys`, sorted lexicographically for
3065
+ * deterministic output, capped at `breadth`. Each property value is read
3066
+ * through {@link attempt} so a hostile getter cannot escape as a thrown
3067
+ * error; a property whose value is `undefined` (hostile-getter failure
3068
+ * included) is treated as ABSENT — it contributes neither a `properties`
3069
+ * entry nor a `required` entry. Every other present key is required (single-
3070
+ * value mode). Emits `additionalProperties: false` when `closed`, `true`
3071
+ * otherwise — mirroring {@link compileSchema}'s object-emission convention —
3072
+ * EXCEPT when the own-key list exceeds `breadth`: a truncated key list means
3073
+ * the sampled schema no longer describes every property `value` actually
3074
+ * carries, so `additionalProperties` is forced to `true` regardless of
3075
+ * `closed` (a closed schema built from a truncated sample would otherwise
3076
+ * reject the very object it was inferred from). Depth exhaustion or a cyclic
3077
+ * re-encounter of `value` both yield `{}`. A same-object re-inference at the
3078
+ * same remaining `depth` is served from `memo` instead of recomputing
3079
+ * (guards a shared-reference DAG against exponential blowup).
3080
+ *
3081
+ * @param value - The record to infer from
3082
+ * @param depth - Remaining descent budget
3083
+ * @param breadth - The maximum number of properties sampled
3084
+ * @param closed - Whether the emitted schema closes to unknown keys
3085
+ * @param format - Threaded through to nested string/`Date` properties
3086
+ * @param visited - The ancestor set guarding against cycles
3087
+ * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
3088
+ * against exponential re-inference of a shared-reference DAG
3089
+ * @returns The inferred object schema
3090
+ *
3091
+ * @example
3092
+ * ```ts
3093
+ * inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap())
3094
+ * // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'],
3095
+ * // additionalProperties: false }
3096
+ * ```
3097
+ */
3098
+ function inferObject(value, depth, breadth, closed, format, visited, memo) {
3099
+ if (!(depth > 0) || visited.has(value)) return {};
3100
+ const cached = memo.get(value)?.get(depth);
3101
+ if (cached) return cached;
3102
+ visited.add(value);
3103
+ const outcome = attempt(() => {
3104
+ const allKeys = Object.keys(value).sort();
3105
+ const keys = allKeys.slice(0, breadth);
3106
+ const truncated = allKeys.length > breadth;
3107
+ const properties = Object.create(null);
3108
+ const required = [];
3109
+ for (const key of keys) {
3110
+ const propertyValue = value[key];
3111
+ if (propertyValue === void 0) continue;
3112
+ properties[key] = inferValue(propertyValue, depth - 1, breadth, closed, format, visited, memo);
3113
+ required.push(key);
3114
+ }
3115
+ return {
3116
+ properties,
3117
+ required,
3118
+ truncated
3119
+ };
3120
+ });
3121
+ visited.delete(value);
3122
+ if (!outcome.success) return {};
3123
+ const { properties, required, truncated } = outcome.value;
3124
+ const schema = {
3125
+ type: "object",
3126
+ ...Object.keys(properties).length > 0 ? { properties } : {},
3127
+ ...required.length > 0 ? { required } : {},
3128
+ additionalProperties: truncated ? true : !closed
3129
+ };
3130
+ let depths = memo.get(value);
3131
+ if (!depths) {
3132
+ depths = /* @__PURE__ */ new Map();
3133
+ memo.set(value, depths);
3134
+ }
3135
+ depths.set(depth, schema);
3136
+ return schema;
3137
+ }
3138
+ /**
3139
+ * Infer a `JSONSchema` for one unknown value — the reverse direction of
3140
+ * {@link compileSchema}.
3141
+ *
3142
+ * @remarks
3143
+ * Total: never throws, and is cycle/depth/breadth-bounded (see
3144
+ * {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested
3145
+ * objects close to unknown keys (`additionalProperties: false`) by default;
3146
+ * pass `closed: false` to open them. `format` (default `false`) opts a
3147
+ * string/`Date` leaf into the `format` keyword. Structurally-equal inputs
3148
+ * infer byte-identical schemas (object keys and `anyOf` members are sorted).
3149
+ *
3150
+ * A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string'
3151
+ * }` — is structurally accepted by `schemaToParameters`, but MCP clients
3152
+ * expect an object-shaped `inputSchema`; wrap a non-object payload with
3153
+ * {@link schemaToObject} before advertising it as a tool's parameters.
3154
+ *
3155
+ * `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a
3156
+ * finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /
3157
+ * {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,
3158
+ * fractional) — a hostile or malformed budget can never defeat the depth
3159
+ * guard or corrupt the sampled key/element list.
3160
+ *
3161
+ * @param value - The value to infer a schema from
3162
+ * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds
3163
+ * @returns The inferred `JSONSchema`
3164
+ *
3165
+ * @example
3166
+ * ```ts
3167
+ * valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] })
3168
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' },
3169
+ * // tags: { type: 'array', items: { type: 'string' } } },
3170
+ * // required: ['id', 'name', 'tags'], additionalProperties: false }
3171
+ * ```
3172
+ */
3173
+ function valueToSchema(value, options) {
3174
+ return inferValue(value, sanitizeBudget(options?.maxDepth, 32), sanitizeBudget(options?.maxProperties, 256), options?.closed ?? true, options?.format ?? false, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap());
3175
+ }
3176
+ /**
3177
+ * Infer a `JSONSchema` for a collected slot of sample values — the shared
3178
+ * non-record recursion step behind {@link samplesToSchema} (top level) and
3179
+ * {@link inferRecordSamples} (per collected property).
3180
+ *
3181
+ * @remarks
3182
+ * When every value is itself a plain record, delegates to
3183
+ * {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when
3184
+ * `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality,
3185
+ * repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins
3186
+ * outright (ENUM > FORMAT > bare string). Failing that, each value is
3187
+ * classified independently via {@link inferValue} with `format` FORCED OFF
3188
+ * (the multi-sample seam: nested formats never compound into an `anyOf`) and
3189
+ * unified with {@link unifySchemas}; only when that unified result is exactly
3190
+ * `{ type: 'string' }` and the outer `format` flag is on does
3191
+ * {@link samplesToFormat} run to (maybe) reattach a unanimous `format`.
3192
+ *
3193
+ * @param samples - The collected slot values
3194
+ * @param depth - Remaining descent budget
3195
+ * @param breadth - The maximum number of properties/elements sampled per nested container
3196
+ * @param closed - Whether nested objects close to unknown keys
3197
+ * @param format - Whether a unanimous string slot gains a `format` keyword
3198
+ * @param enumOn - Whether low-cardinality primitive slots may emit `enum`
3199
+ * @returns The inferred schema for the slot
3200
+ *
3201
+ * @example
3202
+ * ```ts
3203
+ * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)
3204
+ * // { type: 'string', format: 'date' }
3205
+ * ```
3206
+ */
3207
+ function inferSamples(samples, depth, breadth, closed, format, enumOn) {
3208
+ if (samples.length === 0) return {};
3209
+ if (samples.every((sample) => isRecord(sample))) return inferRecordSamples(samples, depth, breadth, closed, format, enumOn);
3210
+ if (enumOn) {
3211
+ const enumSchema = inferPrimitiveEnum(samples, 12);
3212
+ if (enumSchema) return enumSchema;
3213
+ }
3214
+ const unified = unifySchemas(samples.map((sample) => inferValue(sample, depth, breadth, closed, false, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap())));
3215
+ if (format && unified.type === "string" && Object.keys(unified).length === 1) {
3216
+ const detected = samplesToFormat(samples);
3217
+ if (detected) return {
3218
+ type: "string",
3219
+ format: detected
3220
+ };
3221
+ }
3222
+ return unified;
3223
+ }
3224
+ /**
3225
+ * Infer a `JSONSchema` object fragment from a set of plain-record samples
3226
+ * (e.g. database rows) — the record-specialized branch of
3227
+ * {@link samplesToSchema}.
3228
+ *
3229
+ * @remarks
3230
+ * `properties` is the union of every sample's own keys (sorted, capped at
3231
+ * `breadth`); a key is `required` only when present (and non-`undefined`) in
3232
+ * EVERY sample. Each key's schema is inferred over the collected values for
3233
+ * that key via {@link inferSamples} itself (one less depth), so a
3234
+ * property that is itself an array/object of varying shape across rows is
3235
+ * unified the same way the top level is, and the same `format` / `enum`
3236
+ * gating applies per key. Unlike {@link inferObject}/
3237
+ * {@link inferArray}, this path carries no `visited` `WeakSet` — a value
3238
+ * shared by reference across multiple sample rows is legitimate (not a
3239
+ * cycle back to an ancestor), so termination on cyclic row data relies on
3240
+ * the decrementing `depth` budget alone. When the union of sample keys
3241
+ * exceeds `breadth`, the key list is truncated and `additionalProperties` is
3242
+ * forced to `true` regardless of `closed` — the same truncation-opens-the-
3243
+ * schema rule {@link inferObject} applies, so a closed schema built from a
3244
+ * truncated key union never rejects the very rows it was inferred from. A
3245
+ * hostile getter on ONE sample row drops that key for ALL rows (the whole
3246
+ * per-key value collection is a single {@link attempt}-contained walk) —
3247
+ * this is a deliberate all-or-nothing scope, not a per-row partial failure.
3248
+ *
3249
+ * @param samples - The plain-record samples
3250
+ * @param depth - Remaining descent budget
3251
+ * @param breadth - The maximum number of properties sampled
3252
+ * @param closed - Whether the emitted schema closes to unknown keys
3253
+ * @param format - Whether a unanimous string column gains a `format` keyword
3254
+ * @param enumOn - Whether a low-cardinality column may emit `enum`
3255
+ * @returns The inferred object schema
3256
+ *
3257
+ * @example
3258
+ * ```ts
3259
+ * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)
3260
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
3261
+ * // required: ['id'], additionalProperties: false }
3262
+ * ```
3263
+ */
3264
+ function inferRecordSamples(samples, depth, breadth, closed, format, enumOn) {
3265
+ if (!(depth > 0)) return {};
3266
+ const keysOutcome = attempt(() => {
3267
+ const keySet = /* @__PURE__ */ new Set();
3268
+ for (const sample of samples) for (const key of Object.keys(sample)) keySet.add(key);
3269
+ const allKeys = [...keySet].sort();
3270
+ return {
3271
+ keys: allKeys.slice(0, breadth),
3272
+ truncated: allKeys.length > breadth
3273
+ };
3274
+ });
3275
+ const keys = keysOutcome.success ? keysOutcome.value.keys : [];
3276
+ const truncated = keysOutcome.success && keysOutcome.value.truncated;
3277
+ const properties = Object.create(null);
3278
+ const required = [];
3279
+ for (const key of keys) {
3280
+ const valuesOutcome = attempt(() => {
3281
+ const values = [];
3282
+ for (const sample of samples) {
3283
+ const propertyValue = sample[key];
3284
+ if (propertyValue !== void 0) values.push(propertyValue);
3285
+ }
3286
+ return values;
3287
+ });
3288
+ const values = valuesOutcome.success ? valuesOutcome.value : [];
3289
+ if (values.length > 0) properties[key] = inferSamples(values, depth - 1, breadth, closed, format, enumOn);
3290
+ if (values.length === samples.length) required.push(key);
3291
+ }
3292
+ return {
3293
+ type: "object",
3294
+ ...Object.keys(properties).length > 0 ? { properties } : {},
3295
+ ...required.length > 0 ? { required } : {},
3296
+ additionalProperties: truncated ? true : !closed
3297
+ };
3298
+ }
3299
+ /**
3300
+ * Infer a `JSONSchema` from a set of example values — the multi-example
3301
+ * counterpart of {@link valueToSchema} (e.g. inferring one schema from
3302
+ * several database rows).
3303
+ *
3304
+ * @remarks
3305
+ * An empty `samples` array infers the empty accept-anything schema `{}`.
3306
+ * When every sample is a plain record, properties/required are unified
3307
+ * per-key across all samples (see {@link inferRecordSamples}) — a key
3308
+ * required iff present and non-`undefined` in every sample. Otherwise the
3309
+ * slot is inferred via {@link inferSamples} (independent {@link valueToSchema}
3310
+ * per sample, unified with {@link unifySchemas} — the same de-duplication and
3311
+ * `anyOf` ordering {@link inferArray} applies to element schemas). `format`
3312
+ * and `enum` (both default `false`) opt a low-cardinality/unanimous-format
3313
+ * slot into the corresponding keyword — see {@link inferSamples} for the
3314
+ * precedence and the multi-sample format-disabling seam. `maxDepth` /
3315
+ * `maxProperties` are sanitized via {@link sanitizeBudget} the same way
3316
+ * {@link valueToSchema} sanitizes them — see there for why.
3317
+ *
3318
+ * @param samples - The example values to infer a schema from
3319
+ * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds
3320
+ * @returns The inferred `JSONSchema`
3321
+ *
3322
+ * @example
3323
+ * ```ts
3324
+ * samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }])
3325
+ * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
3326
+ * // required: ['id'], additionalProperties: false }
3327
+ * samplesToSchema([]) // {}
3328
+ * ```
3329
+ */
3330
+ function samplesToSchema(samples, options) {
3331
+ return inferSamples(samples, sanitizeBudget(options?.maxDepth, 32), sanitizeBudget(options?.maxProperties, 256), options?.closed ?? true, options?.format ?? false, options?.enum ?? false);
3332
+ }
3333
+ //#endregion
2277
3334
  //#region src/core/shapers.ts
2278
3335
  /**
2279
3336
  * Build a string {@link StringShape}.
@@ -2599,21 +3656,36 @@ function rawShape(schema) {
2599
3656
  };
2600
3657
  }
2601
3658
  //#endregion
3659
+ exports.FAULT_LIMIT = FAULT_LIMIT;
3660
+ exports.FORMAT_MAX_LENGTH = FORMAT_MAX_LENGTH;
3661
+ exports.FORMAT_PATTERNS = FORMAT_PATTERNS;
3662
+ exports.INFER_BREADTH_LIMIT = INFER_BREADTH_LIMIT;
3663
+ exports.INFER_DEPTH_LIMIT = INFER_DEPTH_LIMIT;
3664
+ exports.INFER_ENUM_LIMIT = INFER_ENUM_LIMIT;
2602
3665
  exports.JSON_SCHEMA_TYPES = JSON_SCHEMA_TYPES;
3666
+ exports.PREVIEW_LIMIT = PREVIEW_LIMIT;
2603
3667
  exports.andOf = andOf;
2604
3668
  exports.arrayOf = arrayOf;
2605
3669
  exports.arrayShape = arrayShape;
2606
3670
  exports.attempt = attempt;
2607
3671
  exports.booleanShape = booleanShape;
2608
3672
  exports.boundsOf = boundsOf;
3673
+ exports.canonicalStringify = canonicalStringify;
2609
3674
  exports.compileGenerator = compileGenerator;
2610
3675
  exports.compileGuard = compileGuard;
2611
3676
  exports.compileParser = compileParser;
3677
+ exports.compileReporter = compileReporter;
2612
3678
  exports.compileSchema = compileSchema;
2613
3679
  exports.complementOf = complementOf;
2614
3680
  exports.createContract = createContract;
2615
3681
  exports.enumOf = enumOf;
2616
3682
  exports.enumerableSymbolCount = enumerableSymbolCount;
3683
+ exports.inferArray = inferArray;
3684
+ exports.inferObject = inferObject;
3685
+ exports.inferPrimitiveEnum = inferPrimitiveEnum;
3686
+ exports.inferRecordSamples = inferRecordSamples;
3687
+ exports.inferSamples = inferSamples;
3688
+ exports.inferValue = inferValue;
2617
3689
  exports.instanceOf = instanceOf;
2618
3690
  exports.integerShape = integerShape;
2619
3691
  exports.intersectionOf = intersectionOf;
@@ -2677,6 +3749,7 @@ exports.isUint32Array = isUint32Array;
2677
3749
  exports.isUint8Array = isUint8Array;
2678
3750
  exports.isUint8ClampedArray = isUint8ClampedArray;
2679
3751
  exports.isUndefined = isUndefined;
3752
+ exports.isValidISOInstant = isValidISOInstant;
2680
3753
  exports.isWeakMap = isWeakMap;
2681
3754
  exports.isWeakSet = isWeakSet;
2682
3755
  exports.isZeroArg = isZeroArg;
@@ -2723,20 +3796,29 @@ exports.parseRecordField = parseRecordField;
2723
3796
  exports.parseString = parseString;
2724
3797
  exports.parseStringField = parseStringField;
2725
3798
  exports.pickOf = pickOf;
3799
+ exports.preview = preview;
2726
3800
  exports.rawShape = rawShape;
2727
3801
  exports.recordOf = recordOf;
2728
3802
  exports.recordShape = recordShape;
2729
3803
  exports.resolveField = resolveField;
3804
+ exports.samplesToFormat = samplesToFormat;
3805
+ exports.samplesToSchema = samplesToSchema;
3806
+ exports.sanitizeBudget = sanitizeBudget;
3807
+ exports.schemaToObject = schemaToObject;
2730
3808
  exports.schemaToParameters = schemaToParameters;
2731
3809
  exports.seededRandom = seededRandom;
2732
3810
  exports.setOf = setOf;
3811
+ exports.shapeToKind = shapeToKind;
2733
3812
  exports.stringOf = stringOf;
2734
3813
  exports.stringShape = stringShape;
3814
+ exports.stringToFormat = stringToFormat;
2735
3815
  exports.transformOf = transformOf;
2736
3816
  exports.tupleOf = tupleOf;
3817
+ exports.unifySchemas = unifySchemas;
2737
3818
  exports.unionOf = unionOf;
2738
3819
  exports.unionShape = unionShape;
2739
3820
  exports.validateShape = validateShape;
3821
+ exports.valueToSchema = valueToSchema;
2740
3822
  exports.whereOf = whereOf;
2741
3823
 
2742
3824
  //# sourceMappingURL=index.cjs.map