zodzilla 0.0.0-stage → 0.1.0
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 +21 -0
- package/README.md +325 -2
- package/dist/api.d.ts +8 -0
- package/dist/api.js +8 -0
- package/dist/check.d.ts +53 -0
- package/dist/check.js +103 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/internal.d.ts +58 -0
- package/dist/internal.js +130 -0
- package/dist/invalid.d.ts +15 -0
- package/dist/invalid.js +250 -0
- package/dist/numbers.d.ts +25 -0
- package/dist/numbers.js +188 -0
- package/dist/options.d.ts +16 -0
- package/dist/options.js +5 -0
- package/dist/route.d.ts +40 -0
- package/dist/route.js +175 -0
- package/dist/runner.d.ts +58 -0
- package/dist/runner.js +97 -0
- package/dist/strings.d.ts +5 -0
- package/dist/strings.js +198 -0
- package/dist/valid.d.ts +12 -0
- package/dist/valid.js +258 -0
- package/package.json +72 -4
package/dist/internal.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { safeParse } from 'zod/v4/core';
|
|
3
|
+
export class ZodzillaError extends Error {
|
|
4
|
+
name = 'ZodzillaError';
|
|
5
|
+
}
|
|
6
|
+
export const defOf = (schema) => schema._zod.def;
|
|
7
|
+
export const checksOf = (schema) => (schema._zod.def.checks ?? []).map((check) => check._zod.def);
|
|
8
|
+
export const accepts = (schema, value) => safeParse(schema, value).success;
|
|
9
|
+
export function formatPath(path, root = '(root)') {
|
|
10
|
+
let out = '';
|
|
11
|
+
for (const key of path) {
|
|
12
|
+
if (key === '[]')
|
|
13
|
+
out += '[]';
|
|
14
|
+
else if (typeof key === 'number')
|
|
15
|
+
out += `[${key}]`;
|
|
16
|
+
else if (typeof key === 'string' && /^[A-Za-z_$][\w$]*$/.test(key))
|
|
17
|
+
out += out ? `.${key}` : key;
|
|
18
|
+
else
|
|
19
|
+
out += `[${JSON.stringify(String(key))}]`;
|
|
20
|
+
}
|
|
21
|
+
return out || root;
|
|
22
|
+
}
|
|
23
|
+
export const issueList = (issues, root) => issues.map((issue) => `${formatPath(issue.path, root)}: ${issue.message}`).join('; ');
|
|
24
|
+
export const unsatisfiable = (path, reason) => new ZodzillaError(`No value fits ${formatPath(path)}: ${reason}`);
|
|
25
|
+
export const unsupported = (schema, path) => new ZodzillaError(`Can't generate values for ${formatPath(path)} (${defOf(schema).type}). ` +
|
|
26
|
+
'Pass an override for that schema in the options: overrides: [zz.override(thatSchema, arbitrary)]');
|
|
27
|
+
/** Length or size bounds from a schema's checks */
|
|
28
|
+
export function sizeBounds(schema) {
|
|
29
|
+
let min = 0;
|
|
30
|
+
let max;
|
|
31
|
+
let other = false;
|
|
32
|
+
for (const check of checksOf(schema)) {
|
|
33
|
+
switch (check.check) {
|
|
34
|
+
case 'min_length':
|
|
35
|
+
case 'min_size':
|
|
36
|
+
min = Math.max(min, check.minimum);
|
|
37
|
+
break;
|
|
38
|
+
case 'max_length':
|
|
39
|
+
case 'max_size':
|
|
40
|
+
max = Math.min(max ?? Infinity, check.maximum);
|
|
41
|
+
break;
|
|
42
|
+
case 'length_equals':
|
|
43
|
+
min = max = check.length;
|
|
44
|
+
break;
|
|
45
|
+
case 'size_equals':
|
|
46
|
+
min = max = check.size;
|
|
47
|
+
break;
|
|
48
|
+
default:
|
|
49
|
+
other = true;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { min, max, other };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Like arbitrary.filter(), but gives up with a useful error after `budget` rejections in a row
|
|
56
|
+
* instead of spinning forever. The budget only applies to generation: shrinking a failure can
|
|
57
|
+
* legitimately reject many candidates.
|
|
58
|
+
*/
|
|
59
|
+
class BudgetedFilter extends fc.Arbitrary {
|
|
60
|
+
arb;
|
|
61
|
+
keep;
|
|
62
|
+
budget;
|
|
63
|
+
exhausted;
|
|
64
|
+
constructor(arb, keep, budget, exhausted) {
|
|
65
|
+
super();
|
|
66
|
+
this.arb = arb;
|
|
67
|
+
this.keep = keep;
|
|
68
|
+
this.budget = budget;
|
|
69
|
+
this.exhausted = exhausted;
|
|
70
|
+
}
|
|
71
|
+
generate(mrng, biasFactor) {
|
|
72
|
+
for (let attempt = 0; attempt < this.budget; attempt++) {
|
|
73
|
+
const candidate = this.arb.generate(mrng, biasFactor);
|
|
74
|
+
if (this.keep(candidate.value))
|
|
75
|
+
return candidate;
|
|
76
|
+
}
|
|
77
|
+
throw this.exhausted();
|
|
78
|
+
}
|
|
79
|
+
canShrinkWithoutContext(value) {
|
|
80
|
+
return this.arb.canShrinkWithoutContext(value) && this.keep(value);
|
|
81
|
+
}
|
|
82
|
+
shrink(value, context) {
|
|
83
|
+
return this.arb.shrink(value, context).filter((candidate) => this.keep(candidate.value));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export const budgetedFilter = (arb, keep, budget, describe) => new BudgetedFilter(arb, keep, budget, () => new ZodzillaError(describe()));
|
|
87
|
+
/** Keep only the values schema accepts: for refinements, pipes, and anything else not modelled exactly */
|
|
88
|
+
export const validated = (arb, schema, path, ctx) => budgetedFilter(arb, (value) => accepts(schema, value), ctx.maxRejections, () => `Couldn't generate a valid value for ${formatPath(path)}: ${ctx.maxRejections} attempts in a row ` +
|
|
89
|
+
'failed its schema (usually a strict .refine() or a pipe). Pass an override for that schema in the ' +
|
|
90
|
+
'options: overrides: [zz.override(thatSchema, arbitrary)]');
|
|
91
|
+
/** Runs a build inside fc.letrec so z.lazy() schemas can refer back to themselves */
|
|
92
|
+
export function withContext(options, build) {
|
|
93
|
+
const members = fc.letrec((tie) => {
|
|
94
|
+
const ctx = {
|
|
95
|
+
overrides: new Map(options.overrides),
|
|
96
|
+
extraKeys: options.extraKeys ?? true,
|
|
97
|
+
maxRejections: options.maxRejections ?? 1000,
|
|
98
|
+
maxDepth: options.maxDepth ?? 5,
|
|
99
|
+
recursive: false,
|
|
100
|
+
depth: fc.createDepthIdentifier(),
|
|
101
|
+
tie,
|
|
102
|
+
members: {},
|
|
103
|
+
lazyKeys: { valid: new Map(), invalid: new Map() },
|
|
104
|
+
};
|
|
105
|
+
ctx.members.root = build(ctx);
|
|
106
|
+
return ctx.members;
|
|
107
|
+
});
|
|
108
|
+
return members.root;
|
|
109
|
+
}
|
|
110
|
+
/** Builds a z.lazy() schema once per kind, handing out a letrec reference on every later visit */
|
|
111
|
+
export function recurse(kind, schema, ctx, build) {
|
|
112
|
+
const keys = ctx.lazyKeys[kind];
|
|
113
|
+
let key = keys.get(schema);
|
|
114
|
+
if (key === undefined) {
|
|
115
|
+
key = `${kind}${keys.size}`;
|
|
116
|
+
keys.set(schema, key);
|
|
117
|
+
const outer = ctx.recursive;
|
|
118
|
+
ctx.recursive = true;
|
|
119
|
+
ctx.members[key] = build();
|
|
120
|
+
ctx.recursive = outer;
|
|
121
|
+
}
|
|
122
|
+
return ctx.tie(key);
|
|
123
|
+
}
|
|
124
|
+
/** fast-check depth settings inside recursive schemas: deeper levels favour the first (smallest) choice */
|
|
125
|
+
export const depthOptions = (ctx) => ctx.recursive ? { depthIdentifier: ctx.depth, depthSize: 'small', maxDepth: ctx.maxDepth } : {};
|
|
126
|
+
/** A collection arbitrary that, inside recursive schemas, tends to empty as it nests so trees stay finite */
|
|
127
|
+
export function collection(ctx, minLength, maxLength, make) {
|
|
128
|
+
const arb = make(minLength, maxLength);
|
|
129
|
+
return ctx.recursive && minLength === 0 ? fc.oneof(depthOptions(ctx), make(0, 0), arb) : arb;
|
|
130
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import type * as core from 'zod/v4/core';
|
|
3
|
+
import { type Schema } from './internal.js';
|
|
4
|
+
import type { Options } from './options.js';
|
|
5
|
+
export interface InvalidInput {
|
|
6
|
+
/** The value to pass to the code under test */
|
|
7
|
+
value: unknown;
|
|
8
|
+
/** Where the broken rule lives, as a Zod issue path */
|
|
9
|
+
path: PropertyKey[];
|
|
10
|
+
/** What Zod reports when parsing value */
|
|
11
|
+
issues: core.$ZodIssue[];
|
|
12
|
+
}
|
|
13
|
+
/** Values the schema rejects, each breaking a single rule, so code can be checked for clean rejection */
|
|
14
|
+
export declare function invalid<S extends Schema>(schema: S, options?: Options): fc.Arbitrary<InvalidInput>;
|
|
15
|
+
export declare function describeInvalid(schema: Schema, value: unknown, path: PropertyKey[]): InvalidInput;
|
package/dist/invalid.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { safeParse } from 'zod/v4/core';
|
|
3
|
+
import { accepts, budgetedFilter, checksOf, defOf, depthOptions, formatPath, issueList, recurse, sizeBounds, withContext, ZodzillaError, } from './internal.js';
|
|
4
|
+
import { bigintBounds, dateBounds, numberBounds } from './numbers.js';
|
|
5
|
+
import { text } from './strings.js';
|
|
6
|
+
import { arbitrary, finiteKeys, trailingOptional } from './valid.js';
|
|
7
|
+
/** Values the schema rejects, each breaking a single rule, so code can be checked for clean rejection */
|
|
8
|
+
export function invalid(schema, options = {}) {
|
|
9
|
+
return withContext(options, (ctx) => {
|
|
10
|
+
const arb = broken(schema, [], ctx);
|
|
11
|
+
if (!arb)
|
|
12
|
+
throw new ZodzillaError('The schema accepts any value, so there is no invalid input to generate');
|
|
13
|
+
return arb.map(({ value, path }) => describeInvalid(schema, value, path));
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export function describeInvalid(schema, value, path) {
|
|
17
|
+
let issues;
|
|
18
|
+
const bad = {
|
|
19
|
+
value,
|
|
20
|
+
path,
|
|
21
|
+
// Parsed on first look: check() only looks when it reports a failure
|
|
22
|
+
get issues() {
|
|
23
|
+
return (issues ??= safeParse(schema, value).error?.issues ?? []);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
// fast-check prints counterexamples with this: the bad value and Zod's verdict, not the whole object
|
|
27
|
+
return Object.defineProperty(bad, fc.toStringMethod, {
|
|
28
|
+
value: () => `${fc.stringify(value)} /* ${issueList(bad.issues)} */`,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
// One value of each kind. A schema that accepts all of them is treated as accepting anything
|
|
32
|
+
const probes = [undefined, null, true, 0, Number.NaN, '', 'x', 0n, [], {}, new Date(0), Symbol('probe')];
|
|
33
|
+
// Values of every type, for "wrong type" inputs. Whatever the schema accepts is filtered out
|
|
34
|
+
const anyType = fc.oneof(fc.constant(undefined), fc.constant(null), fc.boolean(), fc.integer(), fc.double(), fc.string({ maxLength: 8 }), fc.bigInt(), fc.date(), fc.array(fc.anything({ maxDepth: 1 }), { maxLength: 3 }), fc.object({ maxDepth: 1 }));
|
|
35
|
+
const here = (value) => ({ value, path: [] });
|
|
36
|
+
function broken(schema, at, ctx) {
|
|
37
|
+
const def = defOf(schema);
|
|
38
|
+
if (def.type === 'lazy') {
|
|
39
|
+
return recurse('invalid', schema, ctx, () => {
|
|
40
|
+
const inner = broken(def.getter(), at, ctx);
|
|
41
|
+
if (!inner)
|
|
42
|
+
throw new ZodzillaError(`${formatPath(at)} accepts any value, so it can't be made invalid`);
|
|
43
|
+
return inner;
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
const strategies = [];
|
|
47
|
+
// First, because inside recursive schemas fast-check falls back to the first option as it nests, and this one doesn't recurse
|
|
48
|
+
if (probes.some((probe) => !accepts(schema, probe)))
|
|
49
|
+
strategies.push(anyType.map(here));
|
|
50
|
+
strategies.push(...specific(schema, at, ctx));
|
|
51
|
+
if (!strategies.length)
|
|
52
|
+
return undefined;
|
|
53
|
+
return budgetedFilter(fc.oneof(depthOptions(ctx), ...strategies), (b) => !accepts(schema, b.value), ctx.maxRejections, () => `Couldn't generate an invalid value for ${formatPath(at)}: ${ctx.maxRejections} attempts in a row were accepted`);
|
|
54
|
+
}
|
|
55
|
+
/** Ways to break a schema that are specific to its kind, on top of passing the wrong type */
|
|
56
|
+
function specific(schema, at, ctx) {
|
|
57
|
+
const def = defOf(schema);
|
|
58
|
+
const out = [];
|
|
59
|
+
switch (def.type) {
|
|
60
|
+
case 'string': {
|
|
61
|
+
const { min, max } = sizeBounds(schema);
|
|
62
|
+
if (min > 0)
|
|
63
|
+
out.push(text(0, min - 1).map(here));
|
|
64
|
+
if (max !== undefined)
|
|
65
|
+
out.push(text(max + 1, max + 8).map(here));
|
|
66
|
+
// Random text breaks most formats, regexes and refinements
|
|
67
|
+
if (checksOf(schema).length || 'format' in def)
|
|
68
|
+
out.push(text().map(here));
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
case 'number': {
|
|
72
|
+
const b = numberBounds(schema);
|
|
73
|
+
const finite = { noNaN: true, noDefaultInfinity: true };
|
|
74
|
+
out.push(fc.constantFrom(Number.NaN, Infinity, -Infinity).map(here));
|
|
75
|
+
if (Number.isFinite(b.min))
|
|
76
|
+
out.push(fc.double({ ...finite, max: b.min, maxExcluded: !b.minExcluded }).map(here));
|
|
77
|
+
if (Number.isFinite(b.max))
|
|
78
|
+
out.push(fc.double({ ...finite, min: b.max, minExcluded: !b.maxExcluded }).map(here));
|
|
79
|
+
if (b.int)
|
|
80
|
+
out.push(fc.double({ ...finite, noInteger: true }).map(here), fc.constantFrom(2 ** 53, -(2 ** 53)).map(here));
|
|
81
|
+
if (b.step)
|
|
82
|
+
out.push(fc.integer({ min: -1000, max: 1000 }).map((k) => here((k + 0.5) * b.step)));
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
case 'bigint': {
|
|
86
|
+
const { min, max, step } = bigintBounds(schema);
|
|
87
|
+
if (min !== undefined)
|
|
88
|
+
out.push(fc.bigInt({ max: min - 1n }).map(here));
|
|
89
|
+
if (max !== undefined)
|
|
90
|
+
out.push(fc.bigInt({ min: max + 1n }).map(here));
|
|
91
|
+
if (step && step > 1n)
|
|
92
|
+
out.push(fc.bigInt().map((k) => here(k * step + 1n)));
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
case 'date': {
|
|
96
|
+
const { min, max } = dateBounds(schema);
|
|
97
|
+
out.push(fc.constant(null).map(() => here(new Date(Number.NaN))));
|
|
98
|
+
if (min !== undefined)
|
|
99
|
+
out.push(fc.date({ max: new Date(min - 1), noInvalidDate: true }).map(here));
|
|
100
|
+
if (max !== undefined)
|
|
101
|
+
out.push(fc.date({ min: new Date(max + 1), noInvalidDate: true }).map(here));
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
case 'literal':
|
|
105
|
+
case 'enum': {
|
|
106
|
+
const values = [...(schema._zod.values ?? [])];
|
|
107
|
+
if (values.length)
|
|
108
|
+
out.push(fc.constantFrom(...values).map((v) => here(nearMiss(v))));
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
case 'template_literal':
|
|
112
|
+
return [text().map(here)];
|
|
113
|
+
case 'array': {
|
|
114
|
+
const { min, max } = sizeBounds(schema);
|
|
115
|
+
const element = arbitrary(def.element, [...at, '[]'], ctx);
|
|
116
|
+
if (min > 0)
|
|
117
|
+
out.push(fc.array(element, { maxLength: min - 1 }).map(here));
|
|
118
|
+
if (max !== undefined)
|
|
119
|
+
out.push(fc.array(element, { minLength: max + 1, maxLength: max + 3 }).map(here));
|
|
120
|
+
const bad = broken(def.element, [...at, '[]'], ctx);
|
|
121
|
+
if (bad && max !== 0) {
|
|
122
|
+
out.push(fc.tuple(arbitrary(schema, at, ctx), bad, fc.nat()).map(([items, b, i]) => {
|
|
123
|
+
const copy = [...items];
|
|
124
|
+
const index = copy.length ? i % copy.length : 0;
|
|
125
|
+
copy[index] = b.value;
|
|
126
|
+
return { value: copy, path: [index, ...b.path] };
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
case 'set': {
|
|
132
|
+
const { min, max } = sizeBounds(schema);
|
|
133
|
+
const element = arbitrary(def.valueType, [...at, '[]'], ctx);
|
|
134
|
+
const sets = (minLength, maxLength) => fc
|
|
135
|
+
.uniqueArray(element, { minLength, maxLength, comparator: 'SameValueZero' })
|
|
136
|
+
.map((items) => here(new Set(items)));
|
|
137
|
+
if (min > 0)
|
|
138
|
+
out.push(sets(0, min - 1));
|
|
139
|
+
if (max !== undefined)
|
|
140
|
+
out.push(sets(max + 1, max + 3));
|
|
141
|
+
const bad = broken(def.valueType, [...at, '[]'], ctx);
|
|
142
|
+
if (bad && max !== 0)
|
|
143
|
+
out.push(bad.map((b) => here(new Set([b.value]))));
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
case 'tuple': {
|
|
147
|
+
const whole = arbitrary(schema, at, ctx);
|
|
148
|
+
const required = def.items.length - trailingOptional(def.items);
|
|
149
|
+
if (required > 0)
|
|
150
|
+
out.push(whole.map((items) => here(items.slice(0, required - 1))));
|
|
151
|
+
if (!def.rest) {
|
|
152
|
+
// Pad skipped optional items so the extra element really lands past the end
|
|
153
|
+
const pad = (items) => [
|
|
154
|
+
...items,
|
|
155
|
+
...Array(def.items.length - items.length).fill(undefined),
|
|
156
|
+
];
|
|
157
|
+
out.push(fc.tuple(whole, fc.anything()).map(([items, extra]) => here([...pad(items), extra])));
|
|
158
|
+
}
|
|
159
|
+
def.items.forEach((item, i) => {
|
|
160
|
+
const bad = broken(item, [...at, i], ctx);
|
|
161
|
+
if (!bad)
|
|
162
|
+
return;
|
|
163
|
+
out.push(fc.tuple(whole, bad).map(([items, b]) => {
|
|
164
|
+
const copy = [...items];
|
|
165
|
+
while (copy.length < i)
|
|
166
|
+
copy.push(undefined);
|
|
167
|
+
copy[i] = b.value;
|
|
168
|
+
return { value: copy, path: [i, ...b.path] };
|
|
169
|
+
}));
|
|
170
|
+
});
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
case 'object': {
|
|
174
|
+
const whole = arbitrary(schema, at, ctx);
|
|
175
|
+
for (const [key, value] of Object.entries(def.shape)) {
|
|
176
|
+
if (!value._zod.optin)
|
|
177
|
+
out.push(whole.map((o) => ({ value: omit(o, key), path: [key] })));
|
|
178
|
+
const bad = broken(value, [...at, key], ctx);
|
|
179
|
+
if (bad)
|
|
180
|
+
out.push(fc.tuple(whole, bad).map(([o, b]) => ({ value: { ...o, [key]: b.value }, path: [key, ...b.path] })));
|
|
181
|
+
}
|
|
182
|
+
if (def.catchall && defOf(def.catchall).type === 'never') {
|
|
183
|
+
const extraKey = fc.string({ minLength: 1, maxLength: 10 }).filter((key) => !Object.hasOwn(def.shape, key));
|
|
184
|
+
out.push(fc.tuple(whole, extraKey, fc.anything()).map(([o, key, v]) => here({ ...o, [key]: v })));
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
case 'record': {
|
|
189
|
+
const whole = arbitrary(schema, at, ctx);
|
|
190
|
+
const bad = broken(def.valueType, [...at, '*'], ctx);
|
|
191
|
+
const keys = finiteKeys(def.keyType);
|
|
192
|
+
if (keys) {
|
|
193
|
+
for (const key of keys) {
|
|
194
|
+
if (!def.partial)
|
|
195
|
+
out.push(whole.map((o) => ({ value: omit(o, key), path: [key] })));
|
|
196
|
+
if (bad)
|
|
197
|
+
out.push(fc.tuple(whole, bad).map(([o, b]) => ({ value: { ...o, [key]: b.value }, path: [key, ...b.path] })));
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
else if (bad) {
|
|
201
|
+
const key = arbitrary(def.keyType, [...at, '<key>'], ctx).map(String);
|
|
202
|
+
out.push(fc.tuple(whole, key, bad).map(([o, k, b]) => ({ value: { ...o, [k]: b.value }, path: [k, ...b.path] })));
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
case 'union':
|
|
207
|
+
case 'intersection': {
|
|
208
|
+
// Breaking one side might leave another option satisfied; the caller's filter drops those.
|
|
209
|
+
// The problem is reported at the union itself, since Zod can't say which option was meant
|
|
210
|
+
const sides = def.type === 'union' ? def.options : [def.left, def.right];
|
|
211
|
+
for (const side of sides) {
|
|
212
|
+
const bad = broken(side, at, ctx);
|
|
213
|
+
if (bad)
|
|
214
|
+
out.push(bad.map((b) => here(b.value)));
|
|
215
|
+
}
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
case 'optional':
|
|
219
|
+
case 'nullable':
|
|
220
|
+
case 'default':
|
|
221
|
+
case 'prefault':
|
|
222
|
+
case 'nonoptional':
|
|
223
|
+
case 'readonly': {
|
|
224
|
+
const bad = broken(def.innerType, at, ctx);
|
|
225
|
+
return bad ? [bad] : [];
|
|
226
|
+
}
|
|
227
|
+
case 'pipe': {
|
|
228
|
+
const bad = broken(def.in, at, ctx);
|
|
229
|
+
if (bad)
|
|
230
|
+
out.push(bad);
|
|
231
|
+
// Input the first stage accepts but a later stage or transform rejects, like "maybe" for z.stringbool()
|
|
232
|
+
out.push(arbitrary(def.in, at, ctx).map(here));
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
default:
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/** The right value in the wrong form: a different case, a trailing space, or a different type */
|
|
240
|
+
function nearMiss(value) {
|
|
241
|
+
if (typeof value === 'string') {
|
|
242
|
+
const swapped = value.toUpperCase() === value ? value.toLowerCase() : value.toUpperCase();
|
|
243
|
+
return swapped === value ? `${value} ` : swapped;
|
|
244
|
+
}
|
|
245
|
+
return typeof value === 'bigint' ? Number(value) : String(value);
|
|
246
|
+
}
|
|
247
|
+
function omit(o, key) {
|
|
248
|
+
const { [key]: _, ...rest } = o;
|
|
249
|
+
return rest;
|
|
250
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { type Context, type Path, type Schema } from './internal.js';
|
|
3
|
+
export declare function numberBounds(schema: Schema): {
|
|
4
|
+
min: number;
|
|
5
|
+
max: number;
|
|
6
|
+
minExcluded: boolean;
|
|
7
|
+
maxExcluded: boolean;
|
|
8
|
+
int: boolean;
|
|
9
|
+
step: number;
|
|
10
|
+
exact: boolean;
|
|
11
|
+
};
|
|
12
|
+
export declare function numberArb(schema: Schema, path: Path, ctx: Context): fc.Arbitrary<number>;
|
|
13
|
+
export declare function bigintBounds(schema: Schema): {
|
|
14
|
+
min?: bigint;
|
|
15
|
+
max?: bigint;
|
|
16
|
+
step?: bigint;
|
|
17
|
+
exact: boolean;
|
|
18
|
+
};
|
|
19
|
+
export declare function bigintArb(schema: Schema, path: Path, ctx: Context): fc.Arbitrary<bigint>;
|
|
20
|
+
export declare function dateBounds(schema: Schema): {
|
|
21
|
+
min?: number;
|
|
22
|
+
max?: number;
|
|
23
|
+
exact: boolean;
|
|
24
|
+
};
|
|
25
|
+
export declare function dateArb(schema: Schema, path: Path, ctx: Context): fc.Arbitrary<Date>;
|
package/dist/numbers.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { checksOf, unsatisfiable, validated } from './internal.js';
|
|
3
|
+
const NUMBER_FORMATS = {
|
|
4
|
+
safeint: { int: true, min: Number.MIN_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER },
|
|
5
|
+
int32: { int: true, min: -(2 ** 31), max: 2 ** 31 - 1 },
|
|
6
|
+
uint32: { int: true, min: 0, max: 2 ** 32 - 1 },
|
|
7
|
+
float32: { int: false, min: -3.4028234663852886e38, max: 3.4028234663852886e38 },
|
|
8
|
+
float64: { int: false, min: -Number.MAX_VALUE, max: Number.MAX_VALUE },
|
|
9
|
+
};
|
|
10
|
+
const BIGINT_FORMATS = {
|
|
11
|
+
int64: [-(2n ** 63n), 2n ** 63n - 1n],
|
|
12
|
+
uint64: [0n, 2n ** 64n - 1n],
|
|
13
|
+
};
|
|
14
|
+
const safe = (n) => Math.min(Number.MAX_SAFE_INTEGER, Math.max(Number.MIN_SAFE_INTEGER, n));
|
|
15
|
+
export function numberBounds(schema) {
|
|
16
|
+
const own = schema._zod.def;
|
|
17
|
+
const b = { min: -Infinity, max: Infinity, minExcluded: false, maxExcluded: false, int: false, step: 0, exact: true };
|
|
18
|
+
const raise = (value, excluded) => {
|
|
19
|
+
if (value > b.min || (value === b.min && excluded))
|
|
20
|
+
Object.assign(b, { min: value, minExcluded: excluded });
|
|
21
|
+
};
|
|
22
|
+
const lower = (value, excluded) => {
|
|
23
|
+
if (value < b.max || (value === b.max && excluded))
|
|
24
|
+
Object.assign(b, { max: value, maxExcluded: excluded });
|
|
25
|
+
};
|
|
26
|
+
const applyFormat = (name) => {
|
|
27
|
+
const format = name === undefined ? undefined : NUMBER_FORMATS[name];
|
|
28
|
+
if (!format)
|
|
29
|
+
return void (b.exact = false);
|
|
30
|
+
b.int ||= format.int;
|
|
31
|
+
raise(format.min, false);
|
|
32
|
+
lower(format.max, false);
|
|
33
|
+
};
|
|
34
|
+
// z.int() and friends carry their format on the schema's own def
|
|
35
|
+
if (own.check === 'number_format')
|
|
36
|
+
applyFormat(own.format);
|
|
37
|
+
for (const check of checksOf(schema)) {
|
|
38
|
+
switch (check.check) {
|
|
39
|
+
case 'greater_than':
|
|
40
|
+
raise(Number(check.value), !check.inclusive);
|
|
41
|
+
break;
|
|
42
|
+
case 'less_than':
|
|
43
|
+
lower(Number(check.value), !check.inclusive);
|
|
44
|
+
break;
|
|
45
|
+
case 'multiple_of':
|
|
46
|
+
if (b.step)
|
|
47
|
+
b.exact = false;
|
|
48
|
+
else
|
|
49
|
+
b.step = Math.abs(Number(check.value));
|
|
50
|
+
break;
|
|
51
|
+
case 'number_format':
|
|
52
|
+
applyFormat(check.format);
|
|
53
|
+
break;
|
|
54
|
+
default:
|
|
55
|
+
b.exact = false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return b;
|
|
59
|
+
}
|
|
60
|
+
export function numberArb(schema, path, ctx) {
|
|
61
|
+
const { min, max, minExcluded, maxExcluded, int, step, exact } = numberBounds(schema);
|
|
62
|
+
const lo = safe(minExcluded && Number.isInteger(min) ? min + 1 : Math.ceil(min));
|
|
63
|
+
const hi = safe(maxExcluded && Number.isInteger(max) ? max - 1 : Math.floor(max));
|
|
64
|
+
let arb;
|
|
65
|
+
let modelled = exact;
|
|
66
|
+
if (step) {
|
|
67
|
+
const kLo = safe(Math.ceil((Number.isFinite(min) ? min : Number.MIN_SAFE_INTEGER) / step));
|
|
68
|
+
const kHi = safe(Math.floor((Number.isFinite(max) ? max : Number.MAX_SAFE_INTEGER) / step));
|
|
69
|
+
if (kLo > kHi)
|
|
70
|
+
throw unsatisfiable(path, `no multiple of ${step} lies between ${min} and ${max}`);
|
|
71
|
+
arb = fc.integer({ min: kLo, max: kHi }).map((k) => k * step);
|
|
72
|
+
// Float steps (0.1 * 3 !== 0.3) and exclusive bounds are left to validation
|
|
73
|
+
modelled &&= Number.isInteger(step) && !minExcluded && !maxExcluded;
|
|
74
|
+
}
|
|
75
|
+
else if (int) {
|
|
76
|
+
if (lo > hi)
|
|
77
|
+
throw unsatisfiable(path, `no integer lies between ${min} and ${max}`);
|
|
78
|
+
arb = fc.integer({ min: lo, max: hi });
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
if (min > max || (min === max && (minExcluded || maxExcluded))) {
|
|
82
|
+
throw unsatisfiable(path, `no number lies between ${min} and ${max}`);
|
|
83
|
+
}
|
|
84
|
+
const double = fc.double({
|
|
85
|
+
noNaN: true,
|
|
86
|
+
noDefaultInfinity: true,
|
|
87
|
+
...(Number.isFinite(min) ? { min, minExcluded } : {}),
|
|
88
|
+
...(Number.isFinite(max) ? { max, maxExcluded } : {}),
|
|
89
|
+
});
|
|
90
|
+
// Mix in integers: they're what most code expects, and where off-by-one bugs live
|
|
91
|
+
arb = lo <= hi ? fc.oneof(fc.integer({ min: lo, max: hi }), double) : double;
|
|
92
|
+
}
|
|
93
|
+
return modelled ? arb : validated(arb, schema, path, ctx);
|
|
94
|
+
}
|
|
95
|
+
export function bigintBounds(schema) {
|
|
96
|
+
const own = schema._zod.def;
|
|
97
|
+
const b = { exact: true };
|
|
98
|
+
const raise = (value) => void (b.min = b.min === undefined || value > b.min ? value : b.min);
|
|
99
|
+
const lower = (value) => void (b.max = b.max === undefined || value < b.max ? value : b.max);
|
|
100
|
+
const applyFormat = (name) => {
|
|
101
|
+
const range = name === undefined ? undefined : BIGINT_FORMATS[name];
|
|
102
|
+
if (!range)
|
|
103
|
+
return void (b.exact = false);
|
|
104
|
+
raise(range[0]);
|
|
105
|
+
lower(range[1]);
|
|
106
|
+
};
|
|
107
|
+
if (own.check === 'bigint_format')
|
|
108
|
+
applyFormat(own.format);
|
|
109
|
+
for (const check of checksOf(schema)) {
|
|
110
|
+
switch (check.check) {
|
|
111
|
+
case 'greater_than': {
|
|
112
|
+
const value = BigInt(check.value);
|
|
113
|
+
raise(check.inclusive ? value : value + 1n);
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
case 'less_than': {
|
|
117
|
+
const value = BigInt(check.value);
|
|
118
|
+
lower(check.inclusive ? value : value - 1n);
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
case 'multiple_of': {
|
|
122
|
+
const value = BigInt(check.value);
|
|
123
|
+
if (b.step)
|
|
124
|
+
b.exact = false;
|
|
125
|
+
else
|
|
126
|
+
b.step = value < 0n ? -value : value;
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
case 'bigint_format':
|
|
130
|
+
applyFormat(check.format);
|
|
131
|
+
break;
|
|
132
|
+
default:
|
|
133
|
+
b.exact = false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return b;
|
|
137
|
+
}
|
|
138
|
+
const ceilDiv = (a, d) => (a >= 0n ? (a + d - 1n) / d : -(-a / d));
|
|
139
|
+
const floorDiv = (a, d) => (a >= 0n ? a / d : -((-a + d - 1n) / d));
|
|
140
|
+
export function bigintArb(schema, path, ctx) {
|
|
141
|
+
const { min, max, step, exact } = bigintBounds(schema);
|
|
142
|
+
if (min !== undefined && max !== undefined && min > max) {
|
|
143
|
+
throw unsatisfiable(path, `no bigint lies between ${min} and ${max}`);
|
|
144
|
+
}
|
|
145
|
+
const bounds = (lo, hi) => ({
|
|
146
|
+
...(lo === undefined ? {} : { min: lo }),
|
|
147
|
+
...(hi === undefined ? {} : { max: hi }),
|
|
148
|
+
});
|
|
149
|
+
const arb = step
|
|
150
|
+
? fc
|
|
151
|
+
.bigInt(bounds(min === undefined ? undefined : ceilDiv(min, step), max === undefined ? undefined : floorDiv(max, step)))
|
|
152
|
+
.map((k) => k * step)
|
|
153
|
+
: fc.bigInt(bounds(min, max));
|
|
154
|
+
return exact ? arb : validated(arb, schema, path, ctx);
|
|
155
|
+
}
|
|
156
|
+
const toTime = (value) => (value instanceof Date ? value.getTime() : Number(value));
|
|
157
|
+
export function dateBounds(schema) {
|
|
158
|
+
const b = { exact: true };
|
|
159
|
+
for (const check of checksOf(schema)) {
|
|
160
|
+
switch (check.check) {
|
|
161
|
+
case 'greater_than': {
|
|
162
|
+
const t = toTime(check.value) + (check.inclusive ? 0 : 1);
|
|
163
|
+
b.min = b.min === undefined ? t : Math.max(b.min, t);
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
case 'less_than': {
|
|
167
|
+
const t = toTime(check.value) - (check.inclusive ? 0 : 1);
|
|
168
|
+
b.max = b.max === undefined ? t : Math.min(b.max, t);
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
default:
|
|
172
|
+
b.exact = false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return b;
|
|
176
|
+
}
|
|
177
|
+
export function dateArb(schema, path, ctx) {
|
|
178
|
+
const { min, max, exact } = dateBounds(schema);
|
|
179
|
+
if (min !== undefined && max !== undefined && min > max) {
|
|
180
|
+
throw unsatisfiable(path, `no date lies between ${new Date(min).toISOString()} and ${new Date(max).toISOString()}`);
|
|
181
|
+
}
|
|
182
|
+
const arb = fc.date({
|
|
183
|
+
noInvalidDate: true,
|
|
184
|
+
...(min === undefined ? {} : { min: new Date(min) }),
|
|
185
|
+
...(max === undefined ? {} : { max: new Date(max) }),
|
|
186
|
+
});
|
|
187
|
+
return exact ? arb : validated(arb, schema, path, ctx);
|
|
188
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Arbitrary } from 'fast-check';
|
|
2
|
+
import type * as core from 'zod/v4/core';
|
|
3
|
+
import type { Schema } from './internal.js';
|
|
4
|
+
export interface Options {
|
|
5
|
+
/** Arbitraries to use instead of generating from a schema, keyed by the exact schema instance. Build entries with override() */
|
|
6
|
+
overrides?: Iterable<Override>;
|
|
7
|
+
/** Add unknown keys to some objects that allow them, to catch code that trusts raw input after parsing. Default true */
|
|
8
|
+
extraKeys?: boolean;
|
|
9
|
+
/** How many generated values in a row a refinement or pipe may reject before giving up. Default 1000 */
|
|
10
|
+
maxRejections?: number;
|
|
11
|
+
/** How deep recursive (z.lazy) schemas nest. Default 5 */
|
|
12
|
+
maxDepth?: number;
|
|
13
|
+
}
|
|
14
|
+
export type Override = readonly [schema: Schema, arbitrary: Arbitrary<unknown>];
|
|
15
|
+
/** Use `arbitrary` wherever `schema` (this exact instance) appears */
|
|
16
|
+
export declare const override: <S extends Schema>(schema: S, arbitrary: Arbitrary<core.input<S>>) => Override;
|
package/dist/options.js
ADDED
package/dist/route.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type Schema } from './internal.js';
|
|
2
|
+
import type { Options } from './options.js';
|
|
3
|
+
type FetchHandler = {
|
|
4
|
+
handle(request: Request): Response | Promise<Response>;
|
|
5
|
+
}['handle'];
|
|
6
|
+
export interface RouteOptions<S extends Schema> extends Options {
|
|
7
|
+
/** The HTTP method. checkRoute sends a JSON body, so GET and HEAD aren't supported yet */
|
|
8
|
+
method: 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
9
|
+
/** The path the requests go to, like '/orders' */
|
|
10
|
+
path: string;
|
|
11
|
+
/** Schema for the JSON body the endpoint takes */
|
|
12
|
+
body: S;
|
|
13
|
+
/** If given, the JSON a valid body gets back (with a 2xx status) must match it */
|
|
14
|
+
response?: Schema;
|
|
15
|
+
/** Statuses a valid body may get besides 2xx and 3xx, like [404, 409]. Anything else is a failure */
|
|
16
|
+
allowStatus?: number[];
|
|
17
|
+
/** Statuses an invalid body must get. Default [400, 422] */
|
|
18
|
+
rejectStatus?: number[];
|
|
19
|
+
/** Headers to send with every request, like an auth token. content-type is already application/json */
|
|
20
|
+
headers?: Record<string, string>;
|
|
21
|
+
/** Bodies to always try first, like the `always test it` line from an earlier failure */
|
|
22
|
+
examples?: unknown[];
|
|
23
|
+
/** Rerun just one earlier failure, using the `rerun just this` line from its report */
|
|
24
|
+
replay?: string;
|
|
25
|
+
numRuns?: number;
|
|
26
|
+
seed?: number;
|
|
27
|
+
}
|
|
28
|
+
/** A request body sent exactly as written, for pinning bodies that aren't valid JSON */
|
|
29
|
+
export declare class RawBody {
|
|
30
|
+
readonly text: string;
|
|
31
|
+
constructor(text: string);
|
|
32
|
+
}
|
|
33
|
+
export declare const rawBody: (text: string) => RawBody;
|
|
34
|
+
/**
|
|
35
|
+
* Fuzzes an HTTP endpoint through a fetch-style handler (Request in, Response out). Valid bodies must
|
|
36
|
+
* not get a 4xx or 5xx (beyond `allowStatus`); invalid bodies, including broken JSON, must get a 400 or
|
|
37
|
+
* 422 (or `rejectStatus`).
|
|
38
|
+
*/
|
|
39
|
+
export declare function checkRoute<S extends Schema>(handler: FetchHandler, options: RouteOptions<S>): Promise<void>;
|
|
40
|
+
export {};
|