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