@orkestrel/contract 0.0.6 → 0.0.7

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.
@@ -3655,6 +3655,348 @@ function rawShape(schema) {
3655
3655
  schema
3656
3656
  };
3657
3657
  }
3658
+ /**
3659
+ * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON
3660
+ * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).
3661
+ *
3662
+ * @remarks
3663
+ * Total and pure. Either keyword is used only when it is a non-negative
3664
+ * integer (`isInteger` + `>= 0`); a malformed value (a string, a negative
3665
+ * number, `NaN`, `Infinity`, a fraction) is dropped as if absent. When both
3666
+ * bounds are present and `min` exceeds `max`, the PAIR is dropped entirely
3667
+ * (an unbounded shape is always a legal widening of a contradictory schema).
3668
+ *
3669
+ * @param min - The raw `minLength` / `minItems` keyword value
3670
+ * @param max - The raw `maxLength` / `maxItems` keyword value
3671
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
3672
+ *
3673
+ * @example
3674
+ * ```ts
3675
+ * deriveLengthBounds(1, 10) // { min: 1, max: 10 }
3676
+ * deriveLengthBounds(10, 1) // {} — contradictory, dropped
3677
+ * deriveLengthBounds(-1, 10) // { max: 10 } — negative min dropped
3678
+ * ```
3679
+ */
3680
+ function deriveLengthBounds(min, max) {
3681
+ const lo = isInteger(min) && min >= 0 ? min : void 0;
3682
+ const hi = isInteger(max) && max >= 0 ? max : void 0;
3683
+ if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
3684
+ return {
3685
+ min: lo,
3686
+ max: hi
3687
+ };
3688
+ }
3689
+ /**
3690
+ * Derive `min`/`max` shape bounds from a pair of finite-number JSON Schema
3691
+ * range keywords (`minimum`/`maximum`).
3692
+ *
3693
+ * @remarks
3694
+ * Total and pure. Either keyword is used only when it is a finite number
3695
+ * ({@link isFiniteNumber} — rejects `NaN` / `±Infinity` / non-numbers); when
3696
+ * both bounds are present and `min` exceeds `max`, the PAIR is dropped
3697
+ * entirely, the same contradiction rule {@link deriveLengthBounds} applies.
3698
+ *
3699
+ * @param min - The raw `minimum` keyword value
3700
+ * @param max - The raw `maximum` keyword value
3701
+ * @returns The derived `min` / `max` pair, either possibly `undefined`
3702
+ *
3703
+ * @example
3704
+ * ```ts
3705
+ * deriveRangeBounds(0, 120) // { min: 0, max: 120 }
3706
+ * deriveRangeBounds(5, 1) // {} — contradictory, dropped
3707
+ * ```
3708
+ */
3709
+ function deriveRangeBounds(min, max) {
3710
+ const lo = isFiniteNumber(min) ? min : void 0;
3711
+ const hi = isFiniteNumber(max) ? max : void 0;
3712
+ if (lo !== void 0 && hi !== void 0 && lo > hi) return {};
3713
+ return {
3714
+ min: lo,
3715
+ max: hi
3716
+ };
3717
+ }
3718
+ /**
3719
+ * Build an {@link ObjectShape} from a JSON Schema object node's `properties` /
3720
+ * `required` / `additionalProperties` keywords — the object-specialized branch
3721
+ * of {@link buildShapeFromNode}.
3722
+ *
3723
+ * @remarks
3724
+ * `properties` (when a record) contributes one child shape per own key, capped
3725
+ * at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}
3726
+ * unless it appears as a string entry of `required`. A property whose value is
3727
+ * not itself a record widens to {@link jsonShape}. `additionalProperties`:
3728
+ * `false` closes the object; a record value recurses into it (`objectShape`
3729
+ * validates extras against that shape); anything else — `true`, absent, or
3730
+ * malformed — leaves the object OPEN (`true`), matching JSON Schema's own
3731
+ * absent-means-open default and the fact that {@link valueToSchema} /
3732
+ * {@link samplesToSchema} always emit the keyword explicitly, so an absent
3733
+ * value only arises from a hand-written schema. When `properties` has MORE
3734
+ * keys than {@link INFER_BREADTH_LIMIT}, the schema's own
3735
+ * `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —
3736
+ * a dropped key's value could otherwise fail a `false` or record-valued rest
3737
+ * shape it was never checked against — mirroring `inferObject`'s
3738
+ * `truncated ? true : !closed` rule (inferers.ts:485). The accumulator uses a
3739
+ * null-prototype record so a property literally named `__proto__` becomes an
3740
+ * own data key rather than mutating the prototype, mirroring
3741
+ * {@link inferObject} (inferers.ts).
3742
+ *
3743
+ * @param schema - The object schema node
3744
+ * @param depth - Remaining descent budget passed to child properties
3745
+ * @param visited - The ancestor set guarding against cycles — recursion
3746
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3747
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3748
+ * supported usage
3749
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
3750
+ * recursion state owned by the {@link schemaToShape} entry point; passing
3751
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
3752
+ * supported usage
3753
+ * @param description - The node's already-extracted `description`, if any
3754
+ * @returns The built object shape
3755
+ *
3756
+ * @example
3757
+ * ```ts
3758
+ * buildObjectShape(
3759
+ * { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
3760
+ * INFER_DEPTH_LIMIT,
3761
+ * new WeakSet(),
3762
+ * new WeakMap(),
3763
+ * undefined,
3764
+ * )
3765
+ * // objectShape({ id: integerShape() }, { additionalProperties: true })
3766
+ * ```
3767
+ */
3768
+ function buildObjectShape(schema, depth, visited, memo, description) {
3769
+ const propertiesSource = isRecord(schema.properties) ? schema.properties : void 0;
3770
+ const requiredSource = isArray(schema.required) ? schema.required.filter((entry) => isString(entry)) : [];
3771
+ const properties = Object.create(null);
3772
+ let truncated = false;
3773
+ if (propertiesSource) {
3774
+ const allKeys = Object.keys(propertiesSource);
3775
+ truncated = allKeys.length > 256;
3776
+ const keys = allKeys.slice(0, 256);
3777
+ for (const key of keys) {
3778
+ const child = propertiesSource[key];
3779
+ const childShape = isRecord(child) ? schemaNodeToShape(child, depth - 1, visited, memo) : jsonShape();
3780
+ properties[key] = requiredSource.includes(key) ? childShape : optionalShape(childShape);
3781
+ }
3782
+ }
3783
+ const extra = schema.additionalProperties;
3784
+ return objectShape(properties, {
3785
+ additionalProperties: truncated ? true : extra === false ? false : isRecord(extra) ? schemaNodeToShape(extra, depth - 1, visited, memo) : true,
3786
+ description
3787
+ });
3788
+ }
3789
+ /**
3790
+ * Build a {@link ContractShape} for one JSON Schema node — the recursive
3791
+ * spine of {@link schemaToShape}, shared with per-child recursion via
3792
+ * {@link schemaNodeToShape}.
3793
+ *
3794
+ * @remarks
3795
+ * Every keyword is read defensively (the node's static `JSONSchema` type is
3796
+ * NOT trusted at runtime — a caller-supplied node may be adversarial), so a
3797
+ * malformed keyword falls through to the next rule instead of throwing.
3798
+ * Precedence, top-down:
3799
+ *
3800
+ * 1. `enum` — an array with at least one string/number/boolean entry (finite
3801
+ * numbers only) becomes a {@link literalShape} over the filtered entries.
3802
+ * Non-primitive / non-finite entries are dropped; an empty result falls
3803
+ * through.
3804
+ * 2. `oneOf` — an array with at least one record entry becomes an
3805
+ * {@link oneOfShape} over the recursively-built variants, provided the
3806
+ * record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the
3807
+ * limit, building a subset union would be strictly narrower than the
3808
+ * schema's full union (a value matching only a dropped variant would be
3809
+ * wrongly rejected), so the whole node widens to {@link jsonShape} instead
3810
+ * of sampling a subset.
3811
+ * 3. `anyOf` — identically, via {@link unionShape}.
3812
+ * 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —
3813
+ * the matching primitive shape, with length/range bounds derived via
3814
+ * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node
3815
+ * additionally drops its bounds when they describe an EMPTY integer range
3816
+ * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
3817
+ * rejects — so the result is always a valid shape.
3818
+ * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
3819
+ * a record-valued `items` (widening to {@link jsonShape} otherwise), with
3820
+ * bounds from `minItems` / `maxItems`.
3821
+ * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
3822
+ * record-valued `properties` — delegates to {@link buildObjectShape}.
3823
+ * 7. Everything else — an empty schema, an unrecognized/absent `type`,
3824
+ * exhausted depth/breadth, or an attempt failure — widens to
3825
+ * {@link jsonShape} (the exact inverse of `compileSchema(jsonShape())`,
3826
+ * and where the inferers themselves bottom out at their own limits).
3827
+ *
3828
+ * `format` and `pattern` are NEVER read into the compiled shape — `format` is
3829
+ * annotation-only and `pattern` compiling an attacker-supplied string into a
3830
+ * `RegExp` is a ReDoS vector. `description`, when a string, carries through to
3831
+ * the produced shape's `description` option.
3832
+ *
3833
+ * @param schema - The schema node to convert
3834
+ * @param depth - Remaining descent budget (0 halts recursion with `jsonShape()`)
3835
+ * @param visited - The ancestor set guarding against cycles — recursion
3836
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3837
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3838
+ * supported usage
3839
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache
3840
+ * guarding against exponential re-conversion of a
3841
+ * shared-reference schema DAG — recursion state owned by the
3842
+ * {@link schemaToShape} entry point; passing a shared or
3843
+ * pre-populated `WeakMap` changes caching behavior and is not
3844
+ * supported usage
3845
+ * @returns The built shape for `schema`
3846
+ *
3847
+ * @example
3848
+ * ```ts
3849
+ * buildShapeFromNode({ type: 'string', minLength: 1 }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
3850
+ * // stringShape({ min: 1 })
3851
+ * ```
3852
+ */
3853
+ function buildShapeFromNode(schema, depth, visited, memo) {
3854
+ const description = isString(schema.description) ? schema.description : void 0;
3855
+ if (isArray(schema.enum)) {
3856
+ const literals = schema.enum.filter((entry) => isString(entry) || isFiniteNumber(entry) || isBoolean(entry));
3857
+ if (literals.length > 0) return literalShape(literals, { description });
3858
+ }
3859
+ if (isArray(schema.oneOf)) {
3860
+ const records = schema.oneOf.filter((entry) => isRecord(entry));
3861
+ if (records.length > 256) return jsonShape({ description });
3862
+ const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
3863
+ if (variants.length > 0) return oneOfShape(...variants);
3864
+ }
3865
+ if (isArray(schema.anyOf)) {
3866
+ const records = schema.anyOf.filter((entry) => isRecord(entry));
3867
+ if (records.length > 256) return jsonShape({ description });
3868
+ const variants = records.map((entry) => schemaNodeToShape(entry, depth - 1, visited, memo));
3869
+ if (variants.length > 0) return unionShape(...variants);
3870
+ }
3871
+ const type = isString(schema.type) ? schema.type : void 0;
3872
+ if (type === "string") {
3873
+ const bounds = deriveLengthBounds(schema.minLength, schema.maxLength);
3874
+ return stringShape({
3875
+ min: bounds.min,
3876
+ max: bounds.max,
3877
+ description
3878
+ });
3879
+ }
3880
+ if (type === "number") {
3881
+ const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
3882
+ return numberShape({
3883
+ min: bounds.min,
3884
+ max: bounds.max,
3885
+ description
3886
+ });
3887
+ }
3888
+ if (type === "integer") {
3889
+ const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
3890
+ return integerShape(Math.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > Math.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? { description } : {
3891
+ min: bounds.min,
3892
+ max: bounds.max,
3893
+ description
3894
+ });
3895
+ }
3896
+ if (type === "boolean") return booleanShape({ description });
3897
+ if (type === "null") return nullShape({ description });
3898
+ if (type === "array") {
3899
+ const items = isRecord(schema.items) ? schemaNodeToShape(schema.items, depth - 1, visited, memo) : jsonShape();
3900
+ const bounds = deriveLengthBounds(schema.minItems, schema.maxItems);
3901
+ return arrayShape(items, {
3902
+ min: bounds.min,
3903
+ max: bounds.max,
3904
+ description
3905
+ });
3906
+ }
3907
+ if (type === "object" || type === void 0 && isRecord(schema.properties)) return buildObjectShape(schema, depth, visited, memo, description);
3908
+ return jsonShape({ description });
3909
+ }
3910
+ /**
3911
+ * Convert one JSON Schema node into a {@link ContractShape} — the recursion
3912
+ * entry point {@link schemaToShape} and {@link buildShapeFromNode} share for
3913
+ * every child (`items`, `properties` values, `additionalProperties`,
3914
+ * `oneOf` / `anyOf` variants).
3915
+ *
3916
+ * @remarks
3917
+ * Total: never throws. Guards depth exhaustion, a non-record node (the
3918
+ * node's static `JSONSchema` type is not trusted at runtime), and a cyclic
3919
+ * re-encounter of `schema` — all three widen to {@link jsonShape}. The
3920
+ * ancestor set is added to and removed from around the WHOLE subtree
3921
+ * conversion (not permanently), so a DAG-shaped schema reached twice via two
3922
+ * different, non-cyclic paths does not false-positive as a cycle. The
3923
+ * subtree conversion itself runs inside {@link attempt}, so a hostile
3924
+ * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
3925
+ * — it degrades to {@link jsonShape} instead. A same-node re-conversion at
3926
+ * the same remaining `depth` is served from `memo` (guards a
3927
+ * shared-reference schema DAG against exponential blowup), mirroring
3928
+ * {@link inferObject} / {@link inferArray} (inferers.ts).
3929
+ *
3930
+ * @param schema - The schema node to convert
3931
+ * @param depth - Remaining descent budget
3932
+ * @param visited - The ancestor set guarding against cycles — recursion
3933
+ * state owned by the {@link schemaToShape} entry point; passing a shared or
3934
+ * pre-populated `WeakSet` changes cycle-detection behavior and is not
3935
+ * supported usage
3936
+ * @param memo - A per-call `(schema node, remaining depth) → shape` cache —
3937
+ * recursion state owned by the {@link schemaToShape} entry point; passing
3938
+ * a shared or pre-populated `WeakMap` changes caching behavior and is not
3939
+ * supported usage
3940
+ * @returns The built shape for `schema`, or {@link jsonShape} on any failure
3941
+ *
3942
+ * @example
3943
+ * ```ts
3944
+ * schemaNodeToShape({ type: 'boolean' }, INFER_DEPTH_LIMIT, new WeakSet(), new WeakMap())
3945
+ * // booleanShape()
3946
+ * ```
3947
+ */
3948
+ function schemaNodeToShape(schema, depth, visited, memo) {
3949
+ if (!(depth > 0) || !isRecord(schema) || visited.has(schema)) return jsonShape();
3950
+ const cached = memo.get(schema)?.get(depth);
3951
+ if (cached) return cached;
3952
+ visited.add(schema);
3953
+ const outcome = attempt(() => buildShapeFromNode(schema, depth, visited, memo));
3954
+ visited.delete(schema);
3955
+ const shape = outcome.success ? outcome.value : jsonShape();
3956
+ let depths = memo.get(schema);
3957
+ if (!depths) {
3958
+ depths = /* @__PURE__ */ new Map();
3959
+ memo.set(schema, depths);
3960
+ }
3961
+ depths.set(depth, shape);
3962
+ return shape;
3963
+ }
3964
+ /**
3965
+ * Convert a runtime `JSONSchema` value into a validating {@link ContractShape}
3966
+ * — the inverse of {@link compileSchema}, and the validating sibling of
3967
+ * {@link rawShape} (which embeds a schema fragment WITHOUT validating it).
3968
+ *
3969
+ * @remarks
3970
+ * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
3971
+ * outright hostile (throwing-getter Proxy) `schema` value all degrade to
3972
+ * {@link jsonShape} rather than escaping as an error, so
3973
+ * `createContract(schemaToShape(x))` is safe to call for any `x`. See
3974
+ * {@link buildShapeFromNode} for the exact per-keyword precedence.
3975
+ *
3976
+ * `format` and `pattern` are NEVER asserted by the compiled shape — `format`
3977
+ * is annotation-only (per the JSON Schema spec, it never narrows validation
3978
+ * on its own) and compiling an attacker-controlled `pattern` string into a
3979
+ * `RegExp` is a ReDoS vector; both keywords are read only far enough to be
3980
+ * ignored. Any node the walk cannot express — an empty `{}`, an
3981
+ * unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a
3982
+ * cyclic re-encounter — widens to {@link jsonShape} (accept any JSON), never
3983
+ * narrows: the round trip `compileGuard(schemaToShape(valueToSchema(v)))(v)`
3984
+ * holds for every `v`, with widening as the only source of looseness.
3985
+ *
3986
+ * @param schema - The JSON Schema value to convert
3987
+ * @returns The built {@link ContractShape}
3988
+ *
3989
+ * @example
3990
+ * ```ts
3991
+ * const schema = samplesToSchema([{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }])
3992
+ * const contract = createContract(schemaToShape(schema))
3993
+ * contract.parse({ id: 3, name: 'Alan' }) // { id: 3, name: 'Alan' }
3994
+ * contract.parse({ id: 'nope' }) // undefined
3995
+ * ```
3996
+ */
3997
+ function schemaToShape(schema) {
3998
+ return schemaNodeToShape(schema, 32, /* @__PURE__ */ new WeakSet(), /* @__PURE__ */ new WeakMap());
3999
+ }
3658
4000
  //#endregion
3659
4001
  exports.FAULT_LIMIT = FAULT_LIMIT;
3660
4002
  exports.FORMAT_MAX_LENGTH = FORMAT_MAX_LENGTH;
@@ -3670,6 +4012,8 @@ exports.arrayShape = arrayShape;
3670
4012
  exports.attempt = attempt;
3671
4013
  exports.booleanShape = booleanShape;
3672
4014
  exports.boundsOf = boundsOf;
4015
+ exports.buildObjectShape = buildObjectShape;
4016
+ exports.buildShapeFromNode = buildShapeFromNode;
3673
4017
  exports.canonicalStringify = canonicalStringify;
3674
4018
  exports.compileGenerator = compileGenerator;
3675
4019
  exports.compileGuard = compileGuard;
@@ -3678,6 +4022,8 @@ exports.compileReporter = compileReporter;
3678
4022
  exports.compileSchema = compileSchema;
3679
4023
  exports.complementOf = complementOf;
3680
4024
  exports.createContract = createContract;
4025
+ exports.deriveLengthBounds = deriveLengthBounds;
4026
+ exports.deriveRangeBounds = deriveRangeBounds;
3681
4027
  exports.enumOf = enumOf;
3682
4028
  exports.enumerableSymbolCount = enumerableSymbolCount;
3683
4029
  exports.inferArray = inferArray;
@@ -3804,8 +4150,10 @@ exports.resolveField = resolveField;
3804
4150
  exports.samplesToFormat = samplesToFormat;
3805
4151
  exports.samplesToSchema = samplesToSchema;
3806
4152
  exports.sanitizeBudget = sanitizeBudget;
4153
+ exports.schemaNodeToShape = schemaNodeToShape;
3807
4154
  exports.schemaToObject = schemaToObject;
3808
4155
  exports.schemaToParameters = schemaToParameters;
4156
+ exports.schemaToShape = schemaToShape;
3809
4157
  exports.seededRandom = seededRandom;
3810
4158
  exports.setOf = setOf;
3811
4159
  exports.shapeToKind = shapeToKind;