@orkestrel/contract 0.0.4 → 0.0.5

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,26 @@ 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;
29
49
  //#endregion
30
50
  //#region src/core/validators.ts
31
51
  /** Determine whether a value is `null`.
@@ -1079,6 +1099,79 @@ function enumerableSymbolCount(value) {
1079
1099
  function schemaToParameters(schema) {
1080
1100
  return isRecord(schema) ? schema : void 0;
1081
1101
  }
1102
+ /**
1103
+ * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s
1104
+ * `received` field.
1105
+ *
1106
+ * @remarks
1107
+ * A primitive renders as its literal: a string is `JSON.stringify`-escaped and
1108
+ * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when
1109
+ * clipped); a number / boolean / bigint / symbol renders via `String`; `null`
1110
+ * and `undefined` render as their own name. Everything else — a plain object,
1111
+ * an array, a function, a class instance, a `Map` — is NEVER traversed or
1112
+ * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),
1113
+ * so a hostile or enormous structure can never blow up the preview.
1114
+ *
1115
+ * @param value - The value to preview
1116
+ * @returns A short descriptive string, always safe to embed in a diagnostic
1117
+ *
1118
+ * @example
1119
+ * ```ts
1120
+ * preview('hi') // '"hi"'
1121
+ * preview(42) // '42'
1122
+ * preview(null) // 'null'
1123
+ * preview({ a: 1 }) // 'object'
1124
+ * preview([1, 2, 3]) // 'object'
1125
+ * ```
1126
+ */
1127
+ function preview(value) {
1128
+ if (value === null) return "null";
1129
+ if (value === void 0) return "undefined";
1130
+ if (isString(value)) {
1131
+ const text = JSON.stringify(value);
1132
+ return text.length > 64 ? `${text.slice(0, 64)}…` : text;
1133
+ }
1134
+ if (isNumber(value) || isBoolean(value)) return String(value);
1135
+ if (isBigInt(value)) return `${value}n`;
1136
+ if (isSymbol(value)) return value.toString();
1137
+ return typeof value;
1138
+ }
1139
+ /**
1140
+ * Project a {@link ContractShape} to the {@link FaultKind} it describes.
1141
+ *
1142
+ * @remarks
1143
+ * A structural mapping used by {@link compileReporter} to fill a `Fault`'s
1144
+ * `expected` field: most shapes map to their own `type` (`numberShape` maps to
1145
+ * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
1146
+ * `nullableShape` project through to their inner shape's kind, and `rawShape`
1147
+ * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
1148
+ *
1149
+ * @param shape - The shape to project
1150
+ * @returns The shape's {@link FaultKind}
1151
+ *
1152
+ * @example
1153
+ * ```ts
1154
+ * shapeToKind(stringShape()) // 'string'
1155
+ * shapeToKind(integerShape()) // 'integer'
1156
+ * shapeToKind(optionalShape(nullShape())) // 'null'
1157
+ * ```
1158
+ */
1159
+ function shapeToKind(shape) {
1160
+ switch (shape.type) {
1161
+ case "string": return "string";
1162
+ case "number": return shape.integer === true ? "integer" : "number";
1163
+ case "boolean": return "boolean";
1164
+ case "null": return "null";
1165
+ case "literal": return "literal";
1166
+ case "array": return "array";
1167
+ case "object": return "object";
1168
+ case "union": return "union";
1169
+ case "json": return "json";
1170
+ case "optional": return shapeToKind(shape.inner);
1171
+ case "nullable": return shapeToKind(shape.inner);
1172
+ case "raw": return "json";
1173
+ }
1174
+ }
1082
1175
  //#endregion
1083
1176
  //#region src/core/combinators.ts
1084
1177
  function arrayOf(elementGuard) {
@@ -2256,6 +2349,260 @@ function compileGenerator(shape, random = seededRandom(Date.now())) {
2256
2349
  case "raw": throw new Error("compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way");
2257
2350
  }
2258
2351
  }
2352
+ /**
2353
+ * Compile a {@link ContractShape} into a structured fault report for a value —
2354
+ * the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.
2355
+ *
2356
+ * @remarks
2357
+ * MIRROR-PARSE semantics: reuses the exact leaf parsers/guards
2358
+ * {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /
2359
+ * `isJSONValue` / …), so the soundness invariant
2360
+ * `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`
2361
+ * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a
2362
+ * coercible value like `'42'` against a `numberShape` reports no fault, the
2363
+ * same leniency `parse` grants, even though the strict guard would reject it).
2364
+ *
2365
+ * Faults are collected in stable pre-order (declared key/index order); every
2366
+ * call — object, array, and union alike, including a union's `oneOf` "no
2367
+ * match" / "no consensus" summary fault prepended to its closest variant's
2368
+ * faults — slices its return to at most {@link FAULT_LIMIT} entries, so the
2369
+ * bound holds at every level of nesting, not just the outermost container, on
2370
+ * adversarial input (a huge array, a wide record, a wide union of wide
2371
+ * records). A closed object's extra keys never
2372
+ * fault — `parse` silently drops them, so `explain` mirrors that leniency; an
2373
+ * open object with a constraining `additionalProperties` shape recurses extras
2374
+ * against it instead. A hostile getter or throwing `Proxy` trap is contained
2375
+ * via {@link attempt} and surfaces as a single top-level type fault, never a
2376
+ * throw (AGENTS §14).
2377
+ *
2378
+ * @param shape - The shape to report against
2379
+ * @param value - The value to check
2380
+ * @param path - The path prefix for faults produced at this call (defaults to the root)
2381
+ * @returns The faults found, empty when the value parses successfully
2382
+ *
2383
+ * @example
2384
+ * ```ts
2385
+ * const user = objectShape({ name: stringShape({ min: 1 }) })
2386
+ * compileReporter(user, { name: '' })
2387
+ * // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '""' }]
2388
+ * compileReporter(user, { name: 'Ada' }) // []
2389
+ * ```
2390
+ */
2391
+ function compileReporter(shape, value, path = []) {
2392
+ switch (shape.type) {
2393
+ case "string": {
2394
+ const parsed = parseString(value);
2395
+ if (parsed === void 0) return [{
2396
+ reason: "type",
2397
+ path,
2398
+ expected: "string",
2399
+ received: preview(value)
2400
+ }];
2401
+ const faults = [];
2402
+ if (shape.min !== void 0 && parsed.length < shape.min) faults.push({
2403
+ reason: "constraint",
2404
+ path,
2405
+ expected: "string",
2406
+ constraint: "min",
2407
+ limit: shape.min,
2408
+ received: preview(parsed)
2409
+ });
2410
+ if (shape.max !== void 0 && parsed.length > shape.max) faults.push({
2411
+ reason: "constraint",
2412
+ path,
2413
+ expected: "string",
2414
+ constraint: "max",
2415
+ limit: shape.max,
2416
+ received: preview(parsed)
2417
+ });
2418
+ if (shape.pattern !== void 0 && !shape.pattern.test(parsed)) faults.push({
2419
+ reason: "constraint",
2420
+ path,
2421
+ expected: "string",
2422
+ constraint: "pattern",
2423
+ limit: shape.pattern.source,
2424
+ received: preview(parsed)
2425
+ });
2426
+ return faults;
2427
+ }
2428
+ case "number": {
2429
+ const kind = shape.integer === true ? "integer" : "number";
2430
+ const parsed = parseNumber(value);
2431
+ if (parsed === void 0) return [{
2432
+ reason: "type",
2433
+ path,
2434
+ expected: kind,
2435
+ received: preview(value)
2436
+ }];
2437
+ const faults = [];
2438
+ if (shape.integer === true && !Number.isInteger(parsed)) faults.push({
2439
+ reason: "constraint",
2440
+ path,
2441
+ expected: kind,
2442
+ constraint: "integer",
2443
+ received: preview(parsed)
2444
+ });
2445
+ if (shape.min !== void 0 && parsed < shape.min) faults.push({
2446
+ reason: "constraint",
2447
+ path,
2448
+ expected: kind,
2449
+ constraint: "min",
2450
+ limit: shape.min,
2451
+ received: preview(parsed)
2452
+ });
2453
+ if (shape.max !== void 0 && parsed > shape.max) faults.push({
2454
+ reason: "constraint",
2455
+ path,
2456
+ expected: kind,
2457
+ constraint: "max",
2458
+ limit: shape.max,
2459
+ received: preview(parsed)
2460
+ });
2461
+ return faults;
2462
+ }
2463
+ case "boolean": return parseBoolean(value) === void 0 ? [{
2464
+ reason: "type",
2465
+ path,
2466
+ expected: "boolean",
2467
+ received: preview(value)
2468
+ }] : [];
2469
+ case "null": return value === null ? [] : [{
2470
+ reason: "type",
2471
+ path,
2472
+ expected: "null",
2473
+ received: preview(value)
2474
+ }];
2475
+ case "json": return isJSONValue(value) ? [] : [{
2476
+ reason: "type",
2477
+ path,
2478
+ expected: "json",
2479
+ received: preview(value)
2480
+ }];
2481
+ case "literal": {
2482
+ const allowed = new Set(shape.values);
2483
+ return allowed.has(value) || isString(value) && allowed.has(value.trim()) ? [] : [{
2484
+ reason: "type",
2485
+ path,
2486
+ expected: "literal",
2487
+ received: preview(value)
2488
+ }];
2489
+ }
2490
+ case "array": {
2491
+ if (!isArray(value)) return [{
2492
+ reason: "type",
2493
+ path,
2494
+ expected: "array",
2495
+ received: preview(value)
2496
+ }];
2497
+ const faults = [];
2498
+ if (!attempt(() => {
2499
+ for (let index = 0; index < value.length; index += 1) {
2500
+ if (faults.length >= 64) return;
2501
+ faults.push(...compileReporter(shape.items, value[index], [...path, String(index)]));
2502
+ }
2503
+ }).success) return [{
2504
+ reason: "type",
2505
+ path,
2506
+ expected: "array",
2507
+ received: preview(value)
2508
+ }];
2509
+ if (shape.min !== void 0 && value.length < shape.min) faults.push({
2510
+ reason: "constraint",
2511
+ path,
2512
+ expected: "array",
2513
+ constraint: "min",
2514
+ limit: shape.min,
2515
+ received: String(value.length)
2516
+ });
2517
+ if (shape.max !== void 0 && value.length > shape.max) faults.push({
2518
+ reason: "constraint",
2519
+ path,
2520
+ expected: "array",
2521
+ constraint: "max",
2522
+ limit: shape.max,
2523
+ received: String(value.length)
2524
+ });
2525
+ return faults.length > 64 ? faults.slice(0, 64) : faults;
2526
+ }
2527
+ case "object": {
2528
+ if (!isRecord(value)) return [{
2529
+ reason: "type",
2530
+ path,
2531
+ expected: "object",
2532
+ received: preview(value)
2533
+ }];
2534
+ const record = value;
2535
+ const faults = [];
2536
+ const known = /* @__PURE__ */ new Set();
2537
+ if (!attempt(() => {
2538
+ for (const key of Object.keys(shape.properties)) {
2539
+ if (faults.length >= 64) return;
2540
+ const child = shape.properties[key];
2541
+ if (child === void 0) continue;
2542
+ known.add(key);
2543
+ const optional = child.type === "optional";
2544
+ const inner = optional ? child.inner : child;
2545
+ const raw = record[key];
2546
+ if (raw === void 0) {
2547
+ if (!optional) faults.push({
2548
+ reason: "missing",
2549
+ path: [...path, key],
2550
+ expected: shapeToKind(inner)
2551
+ });
2552
+ continue;
2553
+ }
2554
+ faults.push(...compileReporter(inner, raw, [...path, key]));
2555
+ }
2556
+ const extra = shape.additionalProperties;
2557
+ if (extra !== void 0 && extra !== true && extra !== false) for (const key of Object.keys(record)) {
2558
+ if (faults.length >= 64) return;
2559
+ if (known.has(key)) continue;
2560
+ faults.push(...compileReporter(extra, record[key], [...path, key]));
2561
+ }
2562
+ }).success) return [{
2563
+ reason: "type",
2564
+ path,
2565
+ expected: "object",
2566
+ received: preview(value)
2567
+ }];
2568
+ return faults.length > 64 ? faults.slice(0, 64) : faults;
2569
+ }
2570
+ case "union": {
2571
+ const perVariant = shape.variants.map((variant) => compileReporter(variant, value, path));
2572
+ let bestIndex = 0;
2573
+ for (let index = 1; index < perVariant.length; index += 1) {
2574
+ const current = perVariant[index];
2575
+ const best = perVariant[bestIndex];
2576
+ if (current !== void 0 && best !== void 0 && current.length < best.length) bestIndex = index;
2577
+ }
2578
+ const closest = perVariant[bestIndex] ?? [];
2579
+ if (shape.mode === "oneOf") {
2580
+ let matched = 0;
2581
+ for (const variant of shape.variants) if (compileGuard(variant)(value)) matched += 1;
2582
+ if (matched === 1) return [];
2583
+ if (matched === 0) return [{
2584
+ reason: "oneOf",
2585
+ path,
2586
+ matched: 0
2587
+ }, ...closest].slice(0, 64);
2588
+ return [{
2589
+ reason: "oneOf",
2590
+ path,
2591
+ matched
2592
+ }];
2593
+ }
2594
+ if (perVariant.some((variantFaults) => variantFaults.length === 0)) return [];
2595
+ return [{
2596
+ reason: "variant",
2597
+ path,
2598
+ variants: shape.variants.length
2599
+ }, ...closest].slice(0, 64);
2600
+ }
2601
+ case "optional": return value === void 0 ? [] : compileReporter(shape.inner, value, path);
2602
+ case "nullable": return value === null ? [] : compileReporter(shape.inner, value, path);
2603
+ case "raw": return [];
2604
+ }
2605
+ }
2259
2606
  function createContract(shape) {
2260
2607
  validateShape(shape);
2261
2608
  const schema = compileSchema(shape);
@@ -2267,6 +2614,9 @@ function createContract(shape) {
2267
2614
  parse(value) {
2268
2615
  return parser(value);
2269
2616
  },
2617
+ explain(value) {
2618
+ return compileReporter(shape, value);
2619
+ },
2270
2620
  generate(random) {
2271
2621
  return compileGenerator(shape, random);
2272
2622
  }
@@ -2598,6 +2948,6 @@ function rawShape(schema) {
2598
2948
  };
2599
2949
  }
2600
2950
  //#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 };
2951
+ export { FAULT_LIMIT, JSON_SCHEMA_TYPES, PREVIEW_LIMIT, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, compileGenerator, compileGuard, compileParser, compileReporter, 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, preview, rawShape, recordOf, recordShape, resolveField, schemaToParameters, seededRandom, setOf, shapeToKind, stringOf, stringShape, transformOf, tupleOf, unionOf, unionShape, validateShape, whereOf };
2602
2952
 
2603
2953
  //# sourceMappingURL=index.js.map