@ark/fast-check 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2025 ArkType
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,5 @@
1
+ import type { nodeOfKind, SequenceTuple } from "@ark/schema";
2
+ import * as fc from "fast-check";
3
+ import type { Ctx } from "../fastCheckContext.ts";
4
+ export declare const getPossiblyWeightedArray: (arrArbitrary: fc.Arbitrary<unknown[]>, node: nodeOfKind<"sequence">, ctx: Ctx) => fc.Arbitrary<unknown[]>;
5
+ export declare const spreadVariadicElements: (tupleArbitraries: fc.Arbitrary<unknown>[], tupleElements: SequenceTuple) => fc.Arbitrary<unknown[]>;
@@ -0,0 +1,31 @@
1
+ import * as fc from "fast-check";
2
+ export const getPossiblyWeightedArray = (arrArbitrary, node, ctx) => ctx.tieStack.length ?
3
+ fc.oneof({
4
+ maxDepth: 2,
5
+ depthIdentifier: `id:${node.id}`
6
+ }, { arbitrary: fc.constant([]), weight: 1 }, {
7
+ arbitrary: arrArbitrary,
8
+ weight: 2
9
+ })
10
+ : arrArbitrary;
11
+ export const spreadVariadicElements = (tupleArbitraries, tupleElements) => fc.tuple(...tupleArbitraries).chain(arr => {
12
+ const arrayWithoutOptionals = [];
13
+ const arrayWithOptionals = [];
14
+ for (const i in arr) {
15
+ if (tupleElements[i].kind === "variadic") {
16
+ const generatedValuesArray = arr[i].map(val => fc.constant(val));
17
+ arrayWithoutOptionals.push(...generatedValuesArray);
18
+ arrayWithOptionals.push(...generatedValuesArray);
19
+ }
20
+ else if (tupleElements[i].kind === "optionals")
21
+ arrayWithOptionals.push(fc.constant(arr[i]));
22
+ else {
23
+ arrayWithoutOptionals.push(fc.constant(arr[i]));
24
+ arrayWithOptionals.push(fc.constant(arr[i]));
25
+ }
26
+ }
27
+ if (arrayWithOptionals.length !== arrayWithoutOptionals.length) {
28
+ return fc.oneof(fc.tuple(...arrayWithoutOptionals), fc.tuple(...arrayWithOptionals));
29
+ }
30
+ return fc.tuple(...arrayWithOptionals);
31
+ });
@@ -0,0 +1,3 @@
1
+ import * as fc from "fast-check";
2
+ import type { ProtoInputNode } from "./proto.ts";
3
+ export declare const buildDateArbitrary: (node: ProtoInputNode) => fc.Arbitrary<Date>;
@@ -0,0 +1,12 @@
1
+ import * as fc from "fast-check";
2
+ export const buildDateArbitrary = (node) => {
3
+ if (node.hasKind("intersection")) {
4
+ const fastCheckDateConstraints = {};
5
+ if (node.inner.after)
6
+ fastCheckDateConstraints.min = node.inner.after.rule;
7
+ if (node.inner.before)
8
+ fastCheckDateConstraints.max = node.inner.before.rule;
9
+ return fc.date(fastCheckDateConstraints);
10
+ }
11
+ return fc.date();
12
+ };
@@ -0,0 +1,14 @@
1
+ import type { nodeOfKind } from "@ark/schema";
2
+ import * as fc from "fast-check";
3
+ import type { Ctx } from "../fastCheckContext.ts";
4
+ export declare const buildDomainArbitrary: BuildDomainArbitrary;
5
+ export type DomainArbitrary<t = unknown> = (node: DomainInputNode, ctx: Ctx) => fc.Arbitrary<t>;
6
+ type BuildDomainArbitrary = {
7
+ number: DomainArbitrary<number>;
8
+ string: DomainArbitrary<string>;
9
+ symbol: DomainArbitrary<symbol>;
10
+ bigint: DomainArbitrary<bigint>;
11
+ object: DomainArbitrary;
12
+ };
13
+ export type DomainInputNode = nodeOfKind<"intersection"> | nodeOfKind<"domain">;
14
+ export {};
@@ -0,0 +1,11 @@
1
+ import * as fc from "fast-check";
2
+ import { buildStructureArbitrary } from "../arktypeFastCheck.js";
3
+ import { buildNumberArbitrary } from "./number.js";
4
+ import { buildStringArbitrary } from "./string.js";
5
+ export const buildDomainArbitrary = {
6
+ number: node => buildNumberArbitrary(node),
7
+ string: node => buildStringArbitrary(node),
8
+ object: (node, ctx) => node.hasKind("domain") ? fc.object() : buildStructureArbitrary(node, ctx),
9
+ symbol: () => fc.constant(Symbol()),
10
+ bigint: () => fc.bigInt()
11
+ };
@@ -0,0 +1,3 @@
1
+ import * as fc from "fast-check";
2
+ import type { DomainInputNode } from "./domain.ts";
3
+ export declare const buildNumberArbitrary: (node: DomainInputNode) => fc.Arbitrary<number>;
@@ -0,0 +1,67 @@
1
+ import { hasKey, nearestFloat, throwInternalError } from "@ark/util";
2
+ import * as fc from "fast-check";
3
+ export const buildNumberArbitrary = (node) => {
4
+ if (node.hasKind("domain")) {
5
+ return fc.double({
6
+ noNaN: !node.numberAllowsNaN
7
+ });
8
+ }
9
+ const numberConstraints = getFastCheckNumberConstraints(node);
10
+ const hasMax = hasKey(numberConstraints, "max");
11
+ const hasMin = hasKey(numberConstraints, "min");
12
+ if (!hasKey(numberConstraints, "divisor"))
13
+ return fc.double(numberConstraints);
14
+ const divisor = numberConstraints.divisor;
15
+ if (divisor === undefined)
16
+ throwInternalError("Expected a divisor.");
17
+ if (hasMin && hasMax) {
18
+ if (numberConstraints.min === undefined ||
19
+ numberConstraints.max === undefined) {
20
+ throwInternalError(`Expected min and max node refinements to not be undefined. (was min: ${numberConstraints.min} max: ${numberConstraints.max})`);
21
+ }
22
+ if (numberConstraints.min > numberConstraints.max) {
23
+ throw new Error(`No integer value satisfies >${numberConstraints.min} & <${numberConstraints.max}`);
24
+ }
25
+ }
26
+ const min = numberConstraints.min ?? Number.MIN_SAFE_INTEGER;
27
+ const max = numberConstraints.max ?? Number.MAX_SAFE_INTEGER;
28
+ const firstDivisibleInRange = Math.ceil(min / divisor) * divisor;
29
+ if (firstDivisibleInRange > max || firstDivisibleInRange < min) {
30
+ throw new Error(`No values within range ${numberConstraints.min} - ${numberConstraints.max} are divisible by ${numberConstraints.divisor}.`);
31
+ }
32
+ numberConstraints.min = firstDivisibleInRange;
33
+ //fast-check defaults max to 0x7fffffff which prevents larger divisible numbers from being produced
34
+ numberConstraints.max = max;
35
+ const integerArbitrary = fc.integer(numberConstraints);
36
+ const integersDivisibleByDivisor = integerArbitrary.map(value => {
37
+ const remainder = value % divisor;
38
+ if (remainder === 0)
39
+ return value;
40
+ const lowerPossibleValue = value - remainder;
41
+ if (lowerPossibleValue >= firstDivisibleInRange &&
42
+ lowerPossibleValue % divisor === 0)
43
+ return lowerPossibleValue;
44
+ return value + remainder;
45
+ });
46
+ return integersDivisibleByDivisor;
47
+ };
48
+ const getFastCheckNumberConstraints = (node) => {
49
+ const hasDivisor = node.prestructurals.find(refinement => refinement.hasKind("divisor"));
50
+ const numberConstraints = {
51
+ noNaN: !node.inner.domain?.numberAllowsNaN
52
+ };
53
+ for (const refinement of node.prestructurals) {
54
+ if (refinement.hasKindIn("min", "max")) {
55
+ let rule = refinement.rule;
56
+ if ("exclusive" in refinement) {
57
+ rule = nearestFloat(refinement.rule, refinement.hasKind("min") ? "+" : "-");
58
+ }
59
+ if (hasDivisor !== undefined)
60
+ rule = refinement.hasKind("min") ? Math.ceil(rule) : Math.floor(rule);
61
+ numberConstraints[refinement.kind] = rule;
62
+ }
63
+ else if (refinement.hasKind("divisor"))
64
+ numberConstraints["divisor"] = refinement.rule;
65
+ }
66
+ return numberConstraints;
67
+ };
@@ -0,0 +1,4 @@
1
+ import type { nodeOfKind } from "@ark/schema";
2
+ import { type Arbitrary } from "fast-check";
3
+ import type { Ctx } from "../fastCheckContext.ts";
4
+ export declare const buildCyclicArbitrary: (node: nodeOfKind<"structure">, ctx: Ctx) => Arbitrary<Record<string, unknown>>;
@@ -0,0 +1,14 @@
1
+ import { letrec } from "fast-check";
2
+ import { buildObjectArbitrary } from "../arktypeFastCheck.js";
3
+ export const buildCyclicArbitrary = (node, ctx) => {
4
+ const objectArbitrary = letrec(tie => {
5
+ ctx.tieStack.push(tie);
6
+ const arbitraries = {
7
+ root: buildObjectArbitrary(node, ctx),
8
+ ...ctx.arbitrariesByIntersectionId
9
+ };
10
+ ctx.tieStack.pop();
11
+ return arbitraries;
12
+ });
13
+ return objectArbitrary["root"];
14
+ };
@@ -0,0 +1,14 @@
1
+ import type { nodeOfKind } from "@ark/schema";
2
+ import * as fc from "fast-check";
3
+ import type { Ctx } from "../fastCheckContext.ts";
4
+ import type { DomainInputNode } from "./domain.ts";
5
+ export declare const buildProtoArbitrary: BuildProtoArbitrary;
6
+ type BuildProtoArbitrary = {
7
+ Array: ProtoArbitrary;
8
+ Set: ProtoArbitrary<Set<unknown>>;
9
+ Date: ProtoArbitrary<Date>;
10
+ [key: string]: ProtoArbitrary;
11
+ };
12
+ type ProtoArbitrary<t = unknown> = (node: ProtoInputNode | DomainInputNode, ctx: Ctx) => fc.Arbitrary<t>;
13
+ export type ProtoInputNode = nodeOfKind<"intersection"> | nodeOfKind<"domain">;
14
+ export {};
@@ -0,0 +1,10 @@
1
+ import * as fc from "fast-check";
2
+ import { buildStructureArbitrary } from "../arktypeFastCheck.js";
3
+ import { buildDateArbitrary } from "./date.js";
4
+ export const buildProtoArbitrary = {
5
+ Array: (node, ctx) => node.hasKind("proto") ?
6
+ fc.array(fc.anything())
7
+ : buildStructureArbitrary(node, ctx),
8
+ Set: () => fc.uniqueArray(fc.anything()).map(arr => new Set(arr)),
9
+ Date: node => buildDateArbitrary(node)
10
+ };
@@ -0,0 +1,3 @@
1
+ import * as fc from "fast-check";
2
+ import type { DomainInputNode } from "./domain.ts";
3
+ export declare const buildStringArbitrary: (node: DomainInputNode) => fc.Arbitrary<string>;
@@ -0,0 +1,31 @@
1
+ import { throwInternalError } from "@ark/util";
2
+ import * as fc from "fast-check";
3
+ export const buildStringArbitrary = (node) => {
4
+ if (node.hasKind("domain"))
5
+ return fc.string();
6
+ const stringConstraints = getFastCheckStringConstraints(node.prestructurals);
7
+ if ("pattern" in stringConstraints) {
8
+ if (stringConstraints.minLength || stringConstraints.maxLength)
9
+ throwInternalError("Bounded regex is not supported.");
10
+ return fc.stringMatching(new RegExp(stringConstraints.pattern));
11
+ }
12
+ return fc.string(stringConstraints);
13
+ };
14
+ const getFastCheckStringConstraints = (refinements) => {
15
+ const stringConstraints = {};
16
+ for (const refinement of refinements) {
17
+ if (refinement.hasKind("pattern")) {
18
+ if (stringConstraints.pattern !== undefined) {
19
+ throwInternalError("Multiple regexes on a single node is not supported.");
20
+ }
21
+ stringConstraints["pattern"] = refinement.rule;
22
+ }
23
+ else if (refinement.hasKind("exactLength")) {
24
+ stringConstraints["minLength"] = refinement.rule;
25
+ stringConstraints["maxLength"] = refinement.rule;
26
+ }
27
+ else
28
+ stringConstraints[refinement.kind] = refinement.rule;
29
+ }
30
+ return stringConstraints;
31
+ };
@@ -0,0 +1,7 @@
1
+ import type { nodeOfKind } from "@ark/schema";
2
+ import type { type } from "arktype";
3
+ import * as fc from "fast-check";
4
+ import { type Ctx } from "./fastCheckContext.ts";
5
+ export declare const arkToArbitrary: (schema: type.Any) => fc.Arbitrary<unknown>;
6
+ export declare const buildStructureArbitrary: (node: nodeOfKind<"intersection">, ctx: Ctx) => fc.Arbitrary<unknown>;
7
+ export declare const buildObjectArbitrary: (node: nodeOfKind<"structure">, ctx: Ctx) => fc.Arbitrary<Record<string, unknown>>;
@@ -0,0 +1,141 @@
1
+ import { hasKey, stringAndSymbolicEntriesOf, throwInternalError } from "@ark/util";
2
+ import * as fc from "fast-check";
3
+ import { getPossiblyWeightedArray, spreadVariadicElements } from "./arbitraries/array.js";
4
+ import { buildDomainArbitrary } from "./arbitraries/domain.js";
5
+ import { buildCyclicArbitrary } from "./arbitraries/object.js";
6
+ import { buildProtoArbitrary } from "./arbitraries/proto.js";
7
+ import { initializeContext } from "./fastCheckContext.js";
8
+ export const arkToArbitrary = (schema) => {
9
+ const ctx = initializeContext();
10
+ return buildArbitrary(schema, ctx);
11
+ };
12
+ const buildArbitrary = (node, ctx) => {
13
+ switch (node.kind) {
14
+ case "intersection":
15
+ ctx.seenIntersectionIds[node.id] = true;
16
+ ctx.isCyclic = node.isCyclic;
17
+ //specifically in the case of unknown, it is represented as an empty intersection so we just return anything here.
18
+ if (node.basis === null)
19
+ return fc.anything();
20
+ const intersectionArbitrary = node.basis?.kind === "domain" ?
21
+ buildDomainArbitrary[node.basis?.domain](node, ctx)
22
+ : buildProtoArbitrary[node.basis?.proto.name](node, ctx);
23
+ ctx.arbitrariesByIntersectionId[node.id] = intersectionArbitrary;
24
+ return intersectionArbitrary;
25
+ case "domain":
26
+ if (node.domain in buildDomainArbitrary)
27
+ return buildDomainArbitrary[node.domain](node, ctx);
28
+ return throwInternalError(`${node.domain} is not supported`);
29
+ case "union":
30
+ const arbitraries = node.children.map(node => buildArbitrary(node, ctx));
31
+ return fc.oneof(...arbitraries);
32
+ case "unit":
33
+ return fc.constant(node.unit);
34
+ case "proto":
35
+ return buildProtoArbitrary[node.proto.name](node, ctx);
36
+ case "structure":
37
+ return buildStructureArbitrary(node, ctx);
38
+ case "index":
39
+ return buildIndexSignatureArbitrary([node], ctx);
40
+ case "required":
41
+ case "optional":
42
+ if (node.value.hasKind("alias") && node.required)
43
+ throwInternalError("Infinitely deep cycles are not supported.");
44
+ return buildArbitrary(node.value, ctx);
45
+ case "morph":
46
+ if (node.inner.in === undefined)
47
+ throwInternalError(`Expected the morph to have an 'In' value.`);
48
+ return buildArbitrary(node.inner.in, ctx);
49
+ case "alias":
50
+ if (ctx.tieStack.length < 1)
51
+ throwInternalError("Tie has not been initialized");
52
+ const tie = ctx.tieStack[ctx.tieStack.length - 1];
53
+ const id = node.resolutionId;
54
+ /**
55
+ * Synthetic aliases cause the original structure to not contain the resolved alias node when
56
+ * iterating through children so we explicitly build the resolved node
57
+ */
58
+ if (!(id in ctx.seenIntersectionIds)) {
59
+ ctx.seenIntersectionIds[id] = true;
60
+ ctx.arbitrariesByIntersectionId[id] = buildArbitrary(node.resolution, ctx);
61
+ }
62
+ return tie(id);
63
+ }
64
+ throwInternalError(`${node.kind} is not supported`);
65
+ };
66
+ export const buildStructureArbitrary = (node, ctx) => {
67
+ const structure = node.structure;
68
+ if (node.basis?.hasKind("domain")) {
69
+ if (structure === undefined)
70
+ throwInternalError("Expected a structure node.");
71
+ if (hasKey(structure, "index") && structure.index)
72
+ return buildIndexSignatureArbitrary(structure.index, ctx);
73
+ return buildObjectArbitrary(structure, ctx);
74
+ }
75
+ if (node.inner.exactLength?.rule === 0)
76
+ return fc.tuple();
77
+ const fcArrayConstraints = {};
78
+ if (node.inner.minLength)
79
+ fcArrayConstraints.minLength = node.inner.minLength.rule;
80
+ if (node.inner.maxLength)
81
+ fcArrayConstraints.maxLength = node.inner.maxLength.rule;
82
+ const arrArbitrary = structure?.sequence ?
83
+ buildArrayArbitrary(structure.sequence, fcArrayConstraints, ctx)
84
+ : fc.array(fc.anything(), fcArrayConstraints);
85
+ if (structure?.required || structure?.optional) {
86
+ const objectArbitrary = buildObjectArbitrary(structure, ctx);
87
+ return fc
88
+ .tuple(arrArbitrary, objectArbitrary)
89
+ .map(([arr, record]) => Object.assign(arr, record));
90
+ }
91
+ return arrArbitrary;
92
+ };
93
+ export const buildObjectArbitrary = (node, ctx) => {
94
+ if (ctx.isCyclic && !ctx.tieStack.length)
95
+ return buildCyclicArbitrary(node, ctx);
96
+ const entries = stringAndSymbolicEntriesOf(node.propsByKey);
97
+ const requiredKeys = node.requiredKeys;
98
+ const arbitrariesByKey = {};
99
+ for (const [key, value] of entries)
100
+ arbitrariesByKey[key] = buildArbitrary(value, ctx);
101
+ return fc.record(arbitrariesByKey, { requiredKeys });
102
+ };
103
+ const buildIndexSignatureArbitrary = (indexNodes, ctx) => {
104
+ if (indexNodes.length === 1)
105
+ return getDictionaryArbitrary(indexNodes[0], ctx);
106
+ const dictionaryArbitraries = [];
107
+ for (const indexNode of indexNodes)
108
+ dictionaryArbitraries.push(getDictionaryArbitrary(indexNode, ctx));
109
+ return fc.tuple(...dictionaryArbitraries).map(arbs => {
110
+ const recordArb = {};
111
+ for (const arb of arbs)
112
+ Object.assign(recordArb, arb);
113
+ return recordArb;
114
+ });
115
+ };
116
+ const getDictionaryArbitrary = (node, ctx) => {
117
+ const signatureArbitrary = buildArbitrary(node.signature, ctx);
118
+ const valueArbitrary = buildArbitrary(node.value, ctx);
119
+ //signatureArbitrary can be a symbol or string arbitrary
120
+ return fc.dictionary(signatureArbitrary, valueArbitrary);
121
+ };
122
+ const buildArrayArbitrary = (node, refinements, ctx) => {
123
+ //Arrays will always have a single element and the kind will be variadic
124
+ if (node.tuple.length === 1 && node.tuple[0].kind === "variadic") {
125
+ const elementsArbitrary = buildArbitrary(node.tuple[0].node, ctx);
126
+ const arrArbitrary = fc.array(elementsArbitrary, refinements);
127
+ return getPossiblyWeightedArray(arrArbitrary, node, ctx);
128
+ }
129
+ return getSpreadVariadicElementsTuple(node.tuple, ctx);
130
+ };
131
+ const getSpreadVariadicElementsTuple = (tupleElements, ctx) => {
132
+ const tupleArbitraries = [];
133
+ for (const element of tupleElements) {
134
+ const arbitrary = buildArbitrary(element.node, ctx);
135
+ if (element.kind === "variadic")
136
+ tupleArbitraries.push(fc.array(arbitrary));
137
+ else
138
+ tupleArbitraries.push(arbitrary);
139
+ }
140
+ return spreadVariadicElements(tupleArbitraries, tupleElements);
141
+ };
@@ -0,0 +1,8 @@
1
+ import type { Arbitrary, LetrecLooselyTypedTie } from "fast-check";
2
+ export type Ctx = {
3
+ seenIntersectionIds: Record<string, true>;
4
+ arbitrariesByIntersectionId: Record<string, Arbitrary<unknown>>;
5
+ isCyclic: boolean;
6
+ tieStack: LetrecLooselyTypedTie[];
7
+ };
8
+ export declare const initializeContext: () => Ctx;
@@ -0,0 +1,6 @@
1
+ export const initializeContext = () => ({
2
+ seenIntersectionIds: {},
3
+ arbitrariesByIntersectionId: {},
4
+ isCyclic: false,
5
+ tieStack: []
6
+ });
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@ark/fast-check",
3
+ "version": "0.0.12",
4
+ "license": "MIT",
5
+ "author": {
6
+ "name": "David Blass",
7
+ "email": "david@arktype.io",
8
+ "url": "https://arktype.io"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/arktypeio/arktype.git",
13
+ "directory": "ark/fast-check"
14
+ },
15
+ "type": "module",
16
+ "main": "./out/arktypeFastCheck.js",
17
+ "types": "./out/arktypeFastCheck.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "ark-ts": "./arktypeFastCheck.ts",
21
+ "default": "./out/arktypeFastCheck.js"
22
+ },
23
+ "./internal/*.ts": {
24
+ "ark-ts": "./*.ts",
25
+ "default": "./out/*.js"
26
+ },
27
+ "./internal/*.js": {
28
+ "ark-ts": "./*.ts",
29
+ "default": "./out/*.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "out"
34
+ ],
35
+ "dependencies": {
36
+ "arktype": "2.2.1",
37
+ "@ark/schema": "0.56.0",
38
+ "@ark/util": "0.56.0"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "peerDependencies": {
44
+ "fast-check": "3"
45
+ },
46
+ "scripts": {
47
+ "build": "ts ../repo/build.ts",
48
+ "test": "tsx ../repo/testPackage.ts"
49
+ }
50
+ }