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/route.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { safeParse } from 'zod/v4/core';
|
|
3
|
+
import { accepts, budgetedFilter, issueList, ZodzillaError } from './internal.js';
|
|
4
|
+
import { invalid } from './invalid.js';
|
|
5
|
+
import { frames, parseReplay, runPass, Verdict } from './runner.js';
|
|
6
|
+
import { valid } from './valid.js';
|
|
7
|
+
/** A request body sent exactly as written, for pinning bodies that aren't valid JSON */
|
|
8
|
+
export class RawBody {
|
|
9
|
+
text;
|
|
10
|
+
constructor(text) {
|
|
11
|
+
this.text = text;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export const rawBody = (text) => new RawBody(text);
|
|
15
|
+
/**
|
|
16
|
+
* Fuzzes an HTTP endpoint through a fetch-style handler (Request in, Response out). Valid bodies must
|
|
17
|
+
* not get a 4xx or 5xx (beyond `allowStatus`); invalid bodies, including broken JSON, must get a 400 or
|
|
18
|
+
* 422 (or `rejectStatus`).
|
|
19
|
+
*/
|
|
20
|
+
export async function checkRoute(handler, options) {
|
|
21
|
+
const { method, path, body: schema } = options;
|
|
22
|
+
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
|
|
23
|
+
throw new ZodzillaError(`checkRoute sends a JSON body, so it needs POST, PUT, PATCH or DELETE, not ${method}`);
|
|
24
|
+
}
|
|
25
|
+
const settings = {
|
|
26
|
+
subject: `${method} ${path}`,
|
|
27
|
+
callSite: frames(new Error()),
|
|
28
|
+
replay: parseReplay(options.replay),
|
|
29
|
+
numRuns: options.numRuns,
|
|
30
|
+
seed: options.seed,
|
|
31
|
+
};
|
|
32
|
+
const { subject } = settings;
|
|
33
|
+
const allowStatus = options.allowStatus ?? [];
|
|
34
|
+
const rejectStatus = options.rejectStatus ?? [400, 422];
|
|
35
|
+
const budget = options.maxRejections ?? 1000;
|
|
36
|
+
const send = async (text) => {
|
|
37
|
+
const request = new Request(new URL(path, 'http://localhost'), {
|
|
38
|
+
method,
|
|
39
|
+
headers: { 'content-type': 'application/json', ...options.headers },
|
|
40
|
+
body: text,
|
|
41
|
+
});
|
|
42
|
+
// Frameworks turn a crash into a 500 and log it. Catch the log, both to keep test output quiet and
|
|
43
|
+
// so the report can show what crashed and where
|
|
44
|
+
const logged = [];
|
|
45
|
+
const consoleError = console.error;
|
|
46
|
+
console.error = (...args) => void logged.push(...args);
|
|
47
|
+
try {
|
|
48
|
+
const response = await handler(request);
|
|
49
|
+
return {
|
|
50
|
+
status: response.status,
|
|
51
|
+
text: await response.text(),
|
|
52
|
+
logged: logged.find((l) => l instanceof Error) ?? logged[0],
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
return { error };
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
console.error = consoleError;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const replyNotes = (reply) => [
|
|
63
|
+
['status', String(reply.status)],
|
|
64
|
+
['response', clip(reply.text) || '(empty)'],
|
|
65
|
+
];
|
|
66
|
+
const examples = (options.examples ?? []).map((example) => exampleBody(example, schema));
|
|
67
|
+
const goodBodies = jsonBodies(schema, options, subject, budget);
|
|
68
|
+
await runPass('valid', goodBodies, examples.filter((e) => e.valid).map((e) => e.text), async (text) => {
|
|
69
|
+
const reply = await send(text);
|
|
70
|
+
if ('error' in reply)
|
|
71
|
+
throw new Verdict(`${subject} threw on a valid body`, { thrown: reply.error });
|
|
72
|
+
const logged = { thrown: reply.logged, thrownBy: 'Logged while handling it' };
|
|
73
|
+
if (reply.status >= 400 && !allowStatus.includes(reply.status)) {
|
|
74
|
+
throw new Verdict(`${subject} returned ${reply.status} for a valid body`, {
|
|
75
|
+
notes: replyNotes(reply),
|
|
76
|
+
...logged,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (options.response && reply.status < 300) {
|
|
80
|
+
const json = parseJson(reply.text);
|
|
81
|
+
const result = json.ok ? safeParse(options.response, json.value) : undefined;
|
|
82
|
+
if (!result?.success) {
|
|
83
|
+
const mismatch = result ? issueList(result.error.issues, 'response') : "the response isn't JSON";
|
|
84
|
+
throw new Verdict(`${subject} returned a response that doesn't match the response schema`, {
|
|
85
|
+
notes: [...replyNotes(reply), ['mismatch', mismatch]],
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}, (text) => presentBody({ text, value: JSON.parse(text) }), settings);
|
|
90
|
+
await runPass('invalid', badBodies(schema, options, goodBodies, budget), examples.filter((e) => !e.valid), async (bad) => {
|
|
91
|
+
const reply = await send(bad.text);
|
|
92
|
+
const why = [
|
|
93
|
+
'why bad',
|
|
94
|
+
'value' in bad ? issueList(safeParse(schema, bad.value).error?.issues ?? [], 'body') : "it isn't valid JSON",
|
|
95
|
+
];
|
|
96
|
+
if ('error' in reply)
|
|
97
|
+
throw new Verdict(`${subject} threw on an invalid body`, { thrown: reply.error, notes: [why] });
|
|
98
|
+
if (rejectStatus.includes(reply.status))
|
|
99
|
+
return;
|
|
100
|
+
const expected = rejectStatus.join(' or ');
|
|
101
|
+
const headline = reply.status >= 500
|
|
102
|
+
? `${subject} returned ${reply.status} for an invalid body, instead of rejecting it with ${expected}`
|
|
103
|
+
: reply.status < 400
|
|
104
|
+
? `${subject} accepted an invalid body`
|
|
105
|
+
: `${subject} rejected an invalid body with ${reply.status}, not ${expected}. If that's on purpose, set rejectStatus`;
|
|
106
|
+
throw new Verdict(headline, {
|
|
107
|
+
notes: [why, ...replyNotes(reply)],
|
|
108
|
+
thrown: reply.logged,
|
|
109
|
+
thrownBy: 'Logged while handling it',
|
|
110
|
+
});
|
|
111
|
+
}, presentBody, settings);
|
|
112
|
+
}
|
|
113
|
+
/** Bodies the schema accepts, as JSON text. Each one is checked after a JSON round trip, since that's what the endpoint gets */
|
|
114
|
+
function jsonBodies(schema, options, subject, budget) {
|
|
115
|
+
return budgetedFilter(valid(schema, options).map(toJson), (text) => text !== undefined && accepts(schema, JSON.parse(text)), budget, () => `Couldn't build a valid JSON body for ${subject}: ${budget} bodies in a row stopped matching the schema ` +
|
|
116
|
+
"after going through JSON. That usually means it uses something JSON can't carry, like z.date(), " +
|
|
117
|
+
'z.bigint() or z.map(). For a JSON body use z.coerce.date() or z.iso.datetime() instead');
|
|
118
|
+
}
|
|
119
|
+
/** Bodies the schema rejects (after a JSON round trip), plus some that aren't JSON at all */
|
|
120
|
+
function badBodies(schema, options, goodBodies, budget) {
|
|
121
|
+
const broken = fc.oneof(fc.constantFrom('', '{', '[', 'undefined', 'NaN', "{'single': 'quotes'}", '{"trailing": "comma",}'),
|
|
122
|
+
// A real body cut off part way, like a dropped connection
|
|
123
|
+
fc.tuple(goodBodies, fc.nat()).map(([text, at]) => text.slice(0, at % Math.max(text.length, 1))));
|
|
124
|
+
const notJson = budgetedFilter(broken, (text) => !parseJson(text).ok, budget, () => "Couldn't generate broken JSON").map((text) => ({ text }));
|
|
125
|
+
let rejected;
|
|
126
|
+
try {
|
|
127
|
+
rejected = budgetedFilter(invalid(schema, options).map((bad) => toJson(bad.value)), (text) => text !== undefined && !accepts(schema, JSON.parse(text)), budget, () => `Couldn't generate an invalid JSON body: ${budget} in a row became valid after going through JSON`).map((text) => ({ text: text, value: JSON.parse(text) }));
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
// A schema that accepts any value only has broken JSON to reject
|
|
131
|
+
if (error instanceof ZodzillaError)
|
|
132
|
+
return notJson;
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
return fc.oneof({ weight: 9, arbitrary: rejected }, { weight: 1, arbitrary: notJson });
|
|
136
|
+
}
|
|
137
|
+
function exampleBody(example, schema) {
|
|
138
|
+
if (example instanceof RawBody) {
|
|
139
|
+
const json = parseJson(example.text);
|
|
140
|
+
return json.ok
|
|
141
|
+
? { text: example.text, value: json.value, valid: accepts(schema, json.value) }
|
|
142
|
+
: { text: example.text, valid: false };
|
|
143
|
+
}
|
|
144
|
+
const text = toJson(example);
|
|
145
|
+
if (text === undefined)
|
|
146
|
+
throw new ZodzillaError(`Can't send this example as a JSON body: ${fc.stringify(example)}`);
|
|
147
|
+
const value = JSON.parse(text);
|
|
148
|
+
return { text, value, valid: accepts(schema, value) };
|
|
149
|
+
}
|
|
150
|
+
function presentBody(body) {
|
|
151
|
+
const isJson = 'value' in body;
|
|
152
|
+
return {
|
|
153
|
+
input: isJson ? body.value : body.text,
|
|
154
|
+
rows: [['body', clip(body.text) || '(empty)']],
|
|
155
|
+
pin: isJson ? fc.stringify(body.value) : `zz.rawBody(${JSON.stringify(body.text)})`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function toJson(value) {
|
|
159
|
+
try {
|
|
160
|
+
return JSON.stringify(value);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
// BigInts and circular structures can't be sent as JSON
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function parseJson(text) {
|
|
168
|
+
try {
|
|
169
|
+
return { ok: true, value: JSON.parse(text) };
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return { ok: false };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const clip = (text) => (text.length > 200 ? `${text.slice(0, 200)}β¦` : text);
|
package/dist/runner.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
export type Pass = 'valid' | 'invalid';
|
|
3
|
+
/** Thrown when a check finds an input the code mishandles. The message is the report; the fields are for tooling */
|
|
4
|
+
export declare class CheckFailure extends Error {
|
|
5
|
+
/** Which pass failed: valid or invalid input */
|
|
6
|
+
readonly pass: Pass;
|
|
7
|
+
/** The simplest input zodzilla found that still fails */
|
|
8
|
+
readonly input: unknown;
|
|
9
|
+
/** Pass as the `replay` option to rerun just this case */
|
|
10
|
+
readonly replay: string;
|
|
11
|
+
/** What the code threw (or logged), if anything. Not `cause`, which test runners print again in full */
|
|
12
|
+
readonly thrown?: unknown;
|
|
13
|
+
name: string;
|
|
14
|
+
constructor(message: string,
|
|
15
|
+
/** Which pass failed: valid or invalid input */
|
|
16
|
+
pass: Pass,
|
|
17
|
+
/** The simplest input zodzilla found that still fails */
|
|
18
|
+
input: unknown,
|
|
19
|
+
/** Pass as the `replay` option to rerun just this case */
|
|
20
|
+
replay: string,
|
|
21
|
+
/** What the code threw (or logged), if anything. Not `cause`, which test runners print again in full */
|
|
22
|
+
thrown?: unknown);
|
|
23
|
+
}
|
|
24
|
+
export type Note = [label: string, text: string];
|
|
25
|
+
/** Why a single run failed, before it's turned into a report */
|
|
26
|
+
export declare class Verdict extends Error {
|
|
27
|
+
readonly thrown: unknown;
|
|
28
|
+
readonly thrownBy: string | undefined;
|
|
29
|
+
readonly notes: Note[];
|
|
30
|
+
constructor(headline: string, { thrown, thrownBy, notes }: {
|
|
31
|
+
thrown?: unknown;
|
|
32
|
+
thrownBy?: string;
|
|
33
|
+
notes?: Note[];
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
export interface Settings {
|
|
37
|
+
/** What's under test, for reports: a function name, or a method and path */
|
|
38
|
+
subject: string;
|
|
39
|
+
callSite: string[];
|
|
40
|
+
replay: Replay | undefined;
|
|
41
|
+
numRuns: number | undefined;
|
|
42
|
+
seed: number | undefined;
|
|
43
|
+
}
|
|
44
|
+
/** How a generated value appears in a report */
|
|
45
|
+
export interface Presentation {
|
|
46
|
+
input: unknown;
|
|
47
|
+
rows: Note[];
|
|
48
|
+
/** Source for the `examples` line that keeps this input as a regression test */
|
|
49
|
+
pin: string;
|
|
50
|
+
}
|
|
51
|
+
export declare function runPass<T>(pass: Pass, arb: fc.Arbitrary<T>, examples: T[], property: (value: T) => Promise<void>, present: (value: T) => Presentation, { subject, callSite, replay, numRuns, seed }: Settings): Promise<void>;
|
|
52
|
+
export interface Replay {
|
|
53
|
+
pass: Pass;
|
|
54
|
+
seed: number;
|
|
55
|
+
path: string;
|
|
56
|
+
}
|
|
57
|
+
export declare function parseReplay(token: string | undefined): Replay | undefined;
|
|
58
|
+
export declare const frames: (error: unknown) => string[];
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { ZodzillaError } from './internal.js';
|
|
3
|
+
/** Thrown when a check finds an input the code mishandles. The message is the report; the fields are for tooling */
|
|
4
|
+
export class CheckFailure extends Error {
|
|
5
|
+
pass;
|
|
6
|
+
input;
|
|
7
|
+
replay;
|
|
8
|
+
thrown;
|
|
9
|
+
name = 'CheckFailure';
|
|
10
|
+
constructor(message,
|
|
11
|
+
/** Which pass failed: valid or invalid input */
|
|
12
|
+
pass,
|
|
13
|
+
/** The simplest input zodzilla found that still fails */
|
|
14
|
+
input,
|
|
15
|
+
/** Pass as the `replay` option to rerun just this case */
|
|
16
|
+
replay,
|
|
17
|
+
/** What the code threw (or logged), if anything. Not `cause`, which test runners print again in full */
|
|
18
|
+
thrown) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.pass = pass;
|
|
21
|
+
this.input = input;
|
|
22
|
+
this.replay = replay;
|
|
23
|
+
this.thrown = thrown;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Why a single run failed, before it's turned into a report */
|
|
27
|
+
export class Verdict extends Error {
|
|
28
|
+
thrown;
|
|
29
|
+
thrownBy;
|
|
30
|
+
notes;
|
|
31
|
+
constructor(headline, { thrown, thrownBy, notes = [] }) {
|
|
32
|
+
super(headline);
|
|
33
|
+
this.thrown = thrown;
|
|
34
|
+
this.thrownBy = thrownBy;
|
|
35
|
+
this.notes = notes;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export async function runPass(pass, arb, examples, property, present, { subject, callSite, replay, numRuns, seed }) {
|
|
39
|
+
if (replay && replay.pass !== pass)
|
|
40
|
+
return;
|
|
41
|
+
const details = await fc.check(fc.asyncProperty(arb, property), {
|
|
42
|
+
// Examples stay in when replaying: they're part of what the path counts
|
|
43
|
+
examples: examples.map((example) => [example]),
|
|
44
|
+
...(replay
|
|
45
|
+
? { seed: replay.seed, path: replay.path, endOnFailure: true }
|
|
46
|
+
: { ...(numRuns === undefined ? {} : { numRuns }), ...(seed === undefined ? {} : { seed }) }),
|
|
47
|
+
});
|
|
48
|
+
if (!details.failed)
|
|
49
|
+
return;
|
|
50
|
+
const verdict = details.errorInstance;
|
|
51
|
+
// Anything else escaped from zodzilla or fast-check itself, so surface it untouched
|
|
52
|
+
if (!(verdict instanceof Verdict) || !details.counterexample)
|
|
53
|
+
throw verdict;
|
|
54
|
+
const { input, rows, pin } = present(details.counterexample[0]);
|
|
55
|
+
const token = `${pass}:${details.seed}:${details.counterexamplePath}`;
|
|
56
|
+
const simplified = details.numShrinks ? `, then simplified ${plural(details.numShrinks, 'time')}` : '';
|
|
57
|
+
const lines = [
|
|
58
|
+
verdict.message,
|
|
59
|
+
'',
|
|
60
|
+
...[...rows, ...verdict.notes].map(row),
|
|
61
|
+
row(['found', `on run ${details.numRuns}${simplified}`]),
|
|
62
|
+
row(['rerun just this', `replay: '${token}'`]),
|
|
63
|
+
row(['always test it', `examples: [${pin}]`]),
|
|
64
|
+
];
|
|
65
|
+
const { thrown } = verdict;
|
|
66
|
+
if (thrown !== undefined) {
|
|
67
|
+
const what = thrown instanceof Error
|
|
68
|
+
? `${thrown.name}: ${thrown.message}`
|
|
69
|
+
: typeof thrown === 'string'
|
|
70
|
+
? thrown
|
|
71
|
+
: fc.stringify(thrown);
|
|
72
|
+
lines.push('', `${verdict.thrownBy ?? `Thrown by ${subject}`}: ${what}`);
|
|
73
|
+
}
|
|
74
|
+
const failure = new CheckFailure(lines.join('\n'), pass, input, token, thrown);
|
|
75
|
+
// Point the stack (and test runners' code frames) at where the code threw, or else at the check call
|
|
76
|
+
const location = frames(thrown);
|
|
77
|
+
failure.stack = [`${failure.name}: ${failure.message}`, ...(location.length ? location : callSite)].join('\n');
|
|
78
|
+
throw failure;
|
|
79
|
+
}
|
|
80
|
+
const row = ([label, text]) => ` ${label.padEnd(16)} ${text}`;
|
|
81
|
+
const plural = (n, noun) => `${n} ${noun}${n === 1 ? '' : 's'}`;
|
|
82
|
+
export function parseReplay(token) {
|
|
83
|
+
if (token === undefined)
|
|
84
|
+
return undefined;
|
|
85
|
+
const [pass, seed, ...path] = token.split(':');
|
|
86
|
+
if ((pass !== 'valid' && pass !== 'invalid') || !seed || !/^-?\d+$/.test(seed) || !path.length) {
|
|
87
|
+
throw new ZodzillaError(`replay should be copied from a failure report, like 'valid:1234:0:0'; got '${token}'`);
|
|
88
|
+
}
|
|
89
|
+
return { pass, seed: Number(seed), path: path.join(':') };
|
|
90
|
+
}
|
|
91
|
+
// zodzilla's own frames and fast-check's are noise in a report about the caller's code
|
|
92
|
+
const ownDir = new URL('.', import.meta.url).pathname;
|
|
93
|
+
export const frames = (error) => error instanceof Error && error.stack
|
|
94
|
+
? error.stack
|
|
95
|
+
.split('\n')
|
|
96
|
+
.filter((line) => /^\s+at /.test(line) && !line.includes(ownDir) && !line.includes('/fast-check/'))
|
|
97
|
+
: [];
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { type Context, type Path, type Schema } from './internal.js';
|
|
3
|
+
/** Strings made of single UTF-16 code units, so fast-check's length bounds match Zod's .length checks */
|
|
4
|
+
export declare const text: (minLength?: number, maxLength?: number) => fc.Arbitrary<string>;
|
|
5
|
+
export declare function stringArb(schema: Schema, path: Path, ctx: Context): fc.Arbitrary<string>;
|
package/dist/strings.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import { regexes } from 'zod/v4/core';
|
|
3
|
+
import { checksOf, unsatisfiable, validated } from './internal.js';
|
|
4
|
+
// Mostly printable ASCII, with control characters and non-ASCII mixed in (8:1:1) to shake out encoding
|
|
5
|
+
// bugs. One random draw per character: draws are most of fast-check's generation cost
|
|
6
|
+
const BMP = 0xd7ff - 0xa0 + 1;
|
|
7
|
+
const char = fc
|
|
8
|
+
.integer({ min: 0, max: 10 * BMP - 1 })
|
|
9
|
+
.map((i) => String.fromCharCode(i < 8 * BMP ? 0x20 + (i % 95) : i < 9 * BMP ? i % 0x20 : 0xa0 + (i - 9 * BMP)));
|
|
10
|
+
/** One character from `chars`, in a single draw */
|
|
11
|
+
const pick = (chars) => fc.integer({ min: 0, max: chars.length - 1 }).map((i) => chars[i]);
|
|
12
|
+
const word = (chars, minLength, maxLength) => fc.string({ unit: pick(chars), minLength, maxLength });
|
|
13
|
+
/** Strings made of single UTF-16 code units, so fast-check's length bounds match Zod's .length checks */
|
|
14
|
+
export const text = (minLength = 0, maxLength) => fc.string({ unit: char, minLength, ...(maxLength === undefined ? {} : { maxLength }) });
|
|
15
|
+
export function stringArb(schema, path, ctx) {
|
|
16
|
+
const own = schema._zod.def;
|
|
17
|
+
let minLength = 0;
|
|
18
|
+
let maxLength;
|
|
19
|
+
let exact = true;
|
|
20
|
+
// z.email() and friends carry their format on the schema's own def; z.string().email() puts it in checks
|
|
21
|
+
const formats = own.check === 'string_format' ? [own] : [];
|
|
22
|
+
for (const check of checksOf(schema)) {
|
|
23
|
+
switch (check.check) {
|
|
24
|
+
case 'min_length':
|
|
25
|
+
minLength = Math.max(minLength, check.minimum);
|
|
26
|
+
break;
|
|
27
|
+
case 'max_length':
|
|
28
|
+
maxLength = Math.min(maxLength ?? Infinity, check.maximum);
|
|
29
|
+
break;
|
|
30
|
+
case 'length_equals':
|
|
31
|
+
minLength = maxLength = check.length;
|
|
32
|
+
break;
|
|
33
|
+
case 'string_format':
|
|
34
|
+
formats.push(check);
|
|
35
|
+
break;
|
|
36
|
+
default:
|
|
37
|
+
exact = false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (maxLength !== undefined && maxLength < minLength) {
|
|
41
|
+
throw unsatisfiable(path, `length must be at least ${minLength} and at most ${maxLength}`);
|
|
42
|
+
}
|
|
43
|
+
const shape = { prefix: '', suffix: '', includes: '', lower: false, upper: false };
|
|
44
|
+
let format;
|
|
45
|
+
for (const f of formats) {
|
|
46
|
+
switch (f.format) {
|
|
47
|
+
case 'starts_with':
|
|
48
|
+
if (shape.prefix)
|
|
49
|
+
exact = false;
|
|
50
|
+
shape.prefix = f.prefix ?? '';
|
|
51
|
+
break;
|
|
52
|
+
case 'ends_with':
|
|
53
|
+
if (shape.suffix)
|
|
54
|
+
exact = false;
|
|
55
|
+
shape.suffix = f.suffix ?? '';
|
|
56
|
+
break;
|
|
57
|
+
case 'includes':
|
|
58
|
+
if (f.position !== undefined)
|
|
59
|
+
exact = false;
|
|
60
|
+
shape.includes += f.includes ?? '';
|
|
61
|
+
break;
|
|
62
|
+
case 'lowercase':
|
|
63
|
+
shape.lower = true;
|
|
64
|
+
break;
|
|
65
|
+
case 'uppercase':
|
|
66
|
+
shape.upper = true;
|
|
67
|
+
break;
|
|
68
|
+
default:
|
|
69
|
+
if (format)
|
|
70
|
+
exact = false;
|
|
71
|
+
format ??= f;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (format) {
|
|
75
|
+
// Formats are always validated: several have rules beyond their pattern (checksums, URL parsing),
|
|
76
|
+
// and length bounds or other formats aren't encoded in it
|
|
77
|
+
return validated(formatArb(format, maxLength) ?? text(minLength, maxLength), schema, path, ctx);
|
|
78
|
+
}
|
|
79
|
+
const arb = shaped(shape, minLength, maxLength, path);
|
|
80
|
+
return exact && !(shape.lower && shape.upper) ? arb : validated(arb, schema, path, ctx);
|
|
81
|
+
}
|
|
82
|
+
function shaped(shape, minLength, maxLength, path) {
|
|
83
|
+
const fixed = shape.prefix.length + shape.includes.length + shape.suffix.length;
|
|
84
|
+
if (maxLength !== undefined && maxLength < fixed) {
|
|
85
|
+
throw unsatisfiable(path, `the required prefix, suffix and substrings are longer than ${maxLength}`);
|
|
86
|
+
}
|
|
87
|
+
const body = text(Math.max(0, minLength - fixed), maxLength === undefined ? undefined : maxLength - fixed);
|
|
88
|
+
if (!fixed && !shape.lower && !shape.upper)
|
|
89
|
+
return body;
|
|
90
|
+
return fc.tuple(body, fc.nat()).map(([s, at]) => {
|
|
91
|
+
const cased = shape.lower
|
|
92
|
+
? s.replace(/[A-Z]/g, (c) => c.toLowerCase())
|
|
93
|
+
: shape.upper
|
|
94
|
+
? s.replace(/[a-z]/g, (c) => c.toUpperCase())
|
|
95
|
+
: s;
|
|
96
|
+
const i = at % (cased.length + 1);
|
|
97
|
+
return shape.prefix + cased.slice(0, i) + shape.includes + cased.slice(i) + shape.suffix;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function formatArb(format, maxLength) {
|
|
101
|
+
const special = SPECIAL[format.format]?.(format);
|
|
102
|
+
if (special)
|
|
103
|
+
return special;
|
|
104
|
+
if (!format.pattern)
|
|
105
|
+
return undefined;
|
|
106
|
+
try {
|
|
107
|
+
return fc.stringMatching(format.pattern, maxLength === undefined ? {} : { maxLength });
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// fast-check can't generate from every regex, e.g. ones with lookaheads
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// Formats whose patterns fast-check can't generate from, that Zod checks beyond the pattern, or that a
|
|
115
|
+
// dedicated generator produces several times faster than generating from the pattern
|
|
116
|
+
const SPECIAL = {
|
|
117
|
+
uuid: (format) => uuid(format.version ? Number(format.version.slice(1)) : [1, 2, 3, 4, 5, 6, 7, 8]),
|
|
118
|
+
guid: () => uuid(),
|
|
119
|
+
ipv4: () => fc.ipV4(),
|
|
120
|
+
// Only for Zod's default email pattern: z.email({ pattern }) falls back to generating from that pattern
|
|
121
|
+
email: (format) => (format.pattern?.source === regexes.email.source ? email : undefined),
|
|
122
|
+
url: (format) => {
|
|
123
|
+
const schemes = ['https', 'http', 'ftp', 'ws', 'wss'].filter((s) => !format.protocol || format.protocol.test(s));
|
|
124
|
+
return fc.webUrl({
|
|
125
|
+
withQueryParameters: true,
|
|
126
|
+
withFragments: true,
|
|
127
|
+
...(schemes.length ? { validSchemes: schemes } : {}),
|
|
128
|
+
});
|
|
129
|
+
},
|
|
130
|
+
hostname: () => fc.domain(),
|
|
131
|
+
emoji: () => fc.string({
|
|
132
|
+
unit: fc.constantFrom('π', 'π¦', 'π₯', 'π', 'ππ½', 'πΈπͺ', 'β€οΈ', 'π¨βπ©βπ§'),
|
|
133
|
+
minLength: 1,
|
|
134
|
+
maxLength: 4,
|
|
135
|
+
}),
|
|
136
|
+
duration: () => duration,
|
|
137
|
+
base64: () => bytes.map(toBase64),
|
|
138
|
+
base64url: () => bytes.map((b) => toBase64Url(toBase64(b))),
|
|
139
|
+
jwt: (format) => jwt(format.alg ?? 'HS256'),
|
|
140
|
+
credit_card: () => creditCard,
|
|
141
|
+
iban: () => iban,
|
|
142
|
+
json_string: () => fc.json(),
|
|
143
|
+
};
|
|
144
|
+
// Zod accepts any case; keep some uppercase in the mix for code that compares IDs case-sensitively
|
|
145
|
+
const uuid = (version) => {
|
|
146
|
+
const lower = fc.uuid(version === undefined ? {} : { version: version });
|
|
147
|
+
return fc.oneof({ weight: 3, arbitrary: lower }, { weight: 1, arbitrary: lower.map((u) => u.toUpperCase()) });
|
|
148
|
+
};
|
|
149
|
+
const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
|
150
|
+
const ALNUM = `${LETTERS}0123456789`;
|
|
151
|
+
// Built piece by piece to match Zod's default email pattern:
|
|
152
|
+
// (local-segment.)* local-chars local-last-char @ (label.)+ tld
|
|
153
|
+
const email = fc
|
|
154
|
+
.tuple(fc.array(word(`${ALNUM}_'+-`, 1, 8), { maxLength: 2 }), word(`${ALNUM}_'+-`, 0, 8), pick(`${ALNUM}_+-`), fc.array(fc.tuple(pick(ALNUM), word(`${ALNUM}-`, 0, 10)), { minLength: 1, maxLength: 3 }), word(LETTERS, 2, 6))
|
|
155
|
+
.map(([segments, body, last, labels, tld]) => `${segments.map((s) => `${s}.`).join('')}${body}${last}@${labels.map(([a, b]) => `${a}${b}.`).join('')}${tld}`);
|
|
156
|
+
const bytes = fc.uint8Array({ maxLength: 48 });
|
|
157
|
+
const toBase64 = (b) => btoa(String.fromCharCode(...b));
|
|
158
|
+
const toBase64Url = (s) => s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
159
|
+
const jsonPart = (value) => toBase64Url(toBase64(new TextEncoder().encode(JSON.stringify(value))));
|
|
160
|
+
const jwt = (alg) => fc
|
|
161
|
+
.tuple(fc.dictionary(fc.string(), fc.jsonValue(), { maxKeys: 4 }), fc.uint8Array({ minLength: 16, maxLength: 64 }))
|
|
162
|
+
.map(([claims, signature]) => `${jsonPart({ alg, typ: 'JWT' })}.${jsonPart(claims)}.${toBase64Url(toBase64(signature))}`);
|
|
163
|
+
const duration = fc
|
|
164
|
+
.record({ Y: fc.nat(99), M: fc.nat(11), D: fc.nat(30), H: fc.nat(23), Mi: fc.nat(59), S: fc.nat(59) }, { requiredKeys: [] })
|
|
165
|
+
.map((p) => {
|
|
166
|
+
const part = (n, unit) => (n === undefined ? '' : `${n}${unit}`);
|
|
167
|
+
const date = part(p.Y, 'Y') + part(p.M, 'M') + part(p.D, 'D');
|
|
168
|
+
const time = part(p.H, 'H') + part(p.Mi, 'M') + part(p.S, 'S');
|
|
169
|
+
return date || time ? `P${date}${time && `T${time}`}` : 'P0D';
|
|
170
|
+
});
|
|
171
|
+
// The digit that makes a card number pass the Luhn checksum
|
|
172
|
+
function luhnDigit(digits) {
|
|
173
|
+
let sum = 0;
|
|
174
|
+
for (let i = 0; i < digits.length; i++) {
|
|
175
|
+
let d = digits[digits.length - 1 - i];
|
|
176
|
+
if (i % 2 === 0) {
|
|
177
|
+
d *= 2;
|
|
178
|
+
if (d > 9)
|
|
179
|
+
d -= 9;
|
|
180
|
+
}
|
|
181
|
+
sum += d;
|
|
182
|
+
}
|
|
183
|
+
return (10 - (sum % 10)) % 10;
|
|
184
|
+
}
|
|
185
|
+
const creditCard = fc
|
|
186
|
+
.array(fc.integer({ min: 0, max: 9 }), { minLength: 12, maxLength: 18 })
|
|
187
|
+
.map((digits) => digits.join('') + luhnDigit(digits));
|
|
188
|
+
// The two check digits that make an IBAN pass its mod-97 checksum
|
|
189
|
+
function ibanCheckDigits(country, bban) {
|
|
190
|
+
const numeric = (bban + country + '00').replace(/[A-Z]/g, (c) => String(c.charCodeAt(0) - 55));
|
|
191
|
+
let remainder = 0;
|
|
192
|
+
for (const digit of numeric)
|
|
193
|
+
remainder = (remainder * 10 + Number(digit)) % 97;
|
|
194
|
+
return String(98 - remainder).padStart(2, '0');
|
|
195
|
+
}
|
|
196
|
+
const iban = fc
|
|
197
|
+
.tuple(fc.stringMatching(/^[A-Z]{2}$/), fc.stringMatching(/^[A-Z0-9]{11,30}$/))
|
|
198
|
+
.map(([country, bban]) => country + ibanCheckDigits(country, bban) + bban);
|
package/dist/valid.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import fc from 'fast-check';
|
|
2
|
+
import type * as core from 'zod/v4/core';
|
|
3
|
+
import { type Context, type Path, type Schema } from './internal.js';
|
|
4
|
+
import type { Options } from './options.js';
|
|
5
|
+
/** Values the schema accepts, shaped like what you'd pass to schema.parse() */
|
|
6
|
+
export declare function valid<S extends Schema>(schema: S, options?: Options): fc.Arbitrary<core.input<S>>;
|
|
7
|
+
/** What schema.parse() returns for those values, with transforms and defaults applied */
|
|
8
|
+
export declare function parsed<S extends Schema>(schema: S, options?: Options): fc.Arbitrary<core.output<S>>;
|
|
9
|
+
export declare function arbitrary(schema: Schema, path: Path, ctx: Context): fc.Arbitrary<unknown>;
|
|
10
|
+
export declare function trailingOptional(items: readonly Schema[]): number;
|
|
11
|
+
/** The keys of a record keyed by an enum or literal, which Zod requires all of (unless partial) */
|
|
12
|
+
export declare function finiteKeys(keyType: Schema): string[] | undefined;
|