@ultimat3/testing 30.6.0 → 30.8.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/CLAUDE.md +3 -3
- package/README.md +1 -1
- package/package.json +17 -17
- package/src/define-exercise.ts +53 -17
- package/src/drill-writes.ts +3 -1
- package/src/errors.ts +9 -90
- package/src/exercise-actor-user.ts +63 -0
- package/src/exercise-actor.ts +64 -11
- package/src/exercise-crash.ts +7 -3
- package/src/exercise-drift-hint.ts +28 -0
- package/src/exercise-input.ts +3 -0
- package/src/exercise-job-tenant.ts +10 -5
- package/src/exercise-judge.ts +78 -0
- package/src/exercise-observed.ts +93 -0
- package/src/exercise-override-input.ts +56 -6
- package/src/exercise-report.ts +43 -2
- package/src/exercise-request.ts +7 -24
- package/src/exercise-setup.ts +34 -17
- package/src/exercise-subjects.ts +20 -5
- package/src/exercise-sweeps.ts +57 -12
- package/src/exercise.ts +141 -109
- package/src/fixture-island.ts +1 -1
- package/src/index.ts +4 -0
- package/src/island-errors.ts +82 -0
- package/src/job-crash-points.ts +36 -0
- package/src/job-crash-proof.ts +23 -6
- package/src/job-sim-errors.ts +24 -0
- package/src/plan-conditions.ts +106 -0
- package/src/plan-oracle.ts +93 -57
- package/src/plan-probes.ts +94 -0
- package/src/plan-sort-key.ts +65 -0
- package/src/plan-sweep-fix.ts +99 -22
- package/src/plan-sweep-report.ts +48 -4
- package/src/scale-sweep-graph.ts +3 -0
- package/src/scale-sweep-run.ts +14 -7
- package/src/seed-graph-plan.ts +11 -0
- package/src/seed-graph-values.ts +20 -11
- package/src/seed-graph.ts +39 -3
- package/src/subject-proof.ts +12 -2
- package/src/tenant-proof-report.ts +84 -25
- package/src/tenant-proof.ts +39 -6
- package/src/seed-pattern-sample.ts +0 -216
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// The tenant proof, as `x exercise` reports it: one line per
|
|
2
|
-
// of A's
|
|
3
|
-
// for the gate to fail on. Only paths, tables and seeded ids
|
|
1
|
+
// The tenant proof, as `x exercise` reports it: one line per leg and code — primitive, leg, and the
|
|
2
|
+
// paths of A's canaries in B's answer or the tables and ids of A's changed rows — and one coded
|
|
3
|
+
// finding each for the gate to fail on. Only paths, tables and seeded ids: never a bound value.
|
|
4
4
|
|
|
5
5
|
import { renderFixShellArg } from '@ultimat3/core';
|
|
6
6
|
import type { ExerciseRecord, TenantFinding } from './exercise-report';
|
|
@@ -16,45 +16,104 @@ export interface TenantProofFinding {
|
|
|
16
16
|
|
|
17
17
|
const LEG = { before: 'before A ran', after: 'after A ran' } as const;
|
|
18
18
|
|
|
19
|
-
/**
|
|
20
|
-
|
|
19
|
+
/** Every finding of one leg and one code: one statement's leak, however many fields it carried. */
|
|
20
|
+
interface Group {
|
|
21
|
+
readonly code: TenantFinding['code'];
|
|
22
|
+
readonly leg: TenantFinding['leg'];
|
|
23
|
+
readonly sweep: boolean;
|
|
24
|
+
readonly where: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `output.items[0].url` — where, never what. */
|
|
28
|
+
const whereOne = (finding: TenantFinding): string =>
|
|
21
29
|
finding.code === 'X_TENANT_LEAK'
|
|
22
30
|
? `${finding.path ?? 'output'}`
|
|
23
31
|
: `${finding.table ?? '?'} row ${finding.id ?? '?'}`;
|
|
24
32
|
|
|
25
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Each distinct place once. Places differing only in a list index — three enqueues carrying the same
|
|
35
|
+
* three fields — collapse to `[*]` with their count; a lone one keeps its index.
|
|
36
|
+
*/
|
|
37
|
+
const whereAll = (findings: readonly TenantFinding[]): string => {
|
|
38
|
+
const counts = new Map<string, { readonly first: string; count: number }>();
|
|
39
|
+
for (const finding of findings) {
|
|
40
|
+
const place = whereOne(finding);
|
|
41
|
+
const shape = place.replace(/\[\d+\]/g, '[*]');
|
|
42
|
+
const seen = counts.get(shape);
|
|
43
|
+
if (seen === undefined) counts.set(shape, { first: place, count: 1 });
|
|
44
|
+
else seen.count += 1;
|
|
45
|
+
}
|
|
46
|
+
const entries = [...counts.entries()];
|
|
47
|
+
const each = entries[0]?.[1].count ?? 1;
|
|
48
|
+
if (each > 1 && entries.every(([, { count }]) => count === each)) {
|
|
49
|
+
return `${entries.map(([shape]) => shape).join(', ')} (${each} each)`;
|
|
50
|
+
}
|
|
51
|
+
return entries
|
|
52
|
+
.map(([shape, { first, count }]) => (count === 1 ? first : `${shape} (×${count})`))
|
|
53
|
+
.join(', ');
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const groupsOf = (findings: readonly TenantFinding[]): readonly Group[] => {
|
|
57
|
+
const byKey = new Map<string, TenantFinding[]>();
|
|
58
|
+
for (const finding of findings) {
|
|
59
|
+
const key = `${finding.leg}\u0000${finding.code}\u0000${finding.sweep === true}`;
|
|
60
|
+
const list = byKey.get(key);
|
|
61
|
+
if (list === undefined) byKey.set(key, [finding]);
|
|
62
|
+
else list.push(finding);
|
|
63
|
+
}
|
|
64
|
+
return [...byKey.values()].map((list) => {
|
|
65
|
+
const head = list[0] as TenantFinding;
|
|
66
|
+
return { code: head.code, leg: head.leg, sweep: head.sweep === true, where: whereAll(list) };
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const crossedGroups = (record: ExerciseRecord): readonly Group[] =>
|
|
71
|
+
record.tenant?.verdict === 'crossed' ? groupsOf(record.tenant.findings) : [];
|
|
72
|
+
|
|
73
|
+
/** One line per leg and code of every crossed record: `action readPost · before · …`. */
|
|
26
74
|
export function tenantFindingLines(records: readonly ExerciseRecord[]): readonly string[] {
|
|
27
75
|
return records.flatMap((record) =>
|
|
28
|
-
record.
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
`${record.kind} ${record.name} · ${finding.leg} · ${finding.code} ${where(finding)}`,
|
|
32
|
-
)
|
|
33
|
-
: [],
|
|
76
|
+
crossedGroups(record).map(
|
|
77
|
+
(group) => `${record.kind} ${record.name} · ${group.leg} · ${group.code} ${group.where}`,
|
|
78
|
+
),
|
|
34
79
|
);
|
|
35
80
|
}
|
|
36
81
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
82
|
+
/**
|
|
83
|
+
* B sends A's own first input, A's ids bound in only where it takes any: `{ occurrenceMs }` carries
|
|
84
|
+
* none, and B still crosses when a statement it ran names no tenant. Both readings, always.
|
|
85
|
+
*/
|
|
86
|
+
const causeOf = (record: ExerciseRecord, group: Group): string =>
|
|
87
|
+
group.code === 'X_TENANT_LEAK'
|
|
88
|
+
? `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[group.leg]}, handed back A's seeded data at ${group.where}: a read reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`
|
|
89
|
+
: `${record.kind} ${record.name}, called by tenant B with A's own input ${LEG[group.leg]}, changed A's ${group.where}: a write reached A's row past the tenant guard — by an id the caller chose, or by a statement no tenant predicate scopes`;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* A `tenant: 'none'` job has no actor's org to scope a read to: reading every org is its job, and
|
|
93
|
+
* the one declaration the proof credits for that is a `crossTenant()` scope (`sweepReason`).
|
|
94
|
+
*/
|
|
95
|
+
const fixOf = (name: string, group: Group): string =>
|
|
96
|
+
group.code === 'X_TENANT_WRITE_CROSSED'
|
|
97
|
+
? `x exercise ${name} --json — then write ${group.where} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`
|
|
98
|
+
: group.sweep
|
|
99
|
+
? `x exercise ${name} --json — then wrap the read behind ${group.where} in ${name}'s run in crossTenant('<why ${name} reads every org>', async () => …) from @ultimat3/entity; the job's actor must hold tenancy:cross`
|
|
100
|
+
: `x exercise ${name} --json — then read the row behind ${group.where} through the repository scoped to ctx.actor, never by the input id alone, nor by an unscoped statement`;
|
|
41
101
|
|
|
42
102
|
/**
|
|
43
|
-
* One coded finding per
|
|
44
|
-
*
|
|
45
|
-
*
|
|
103
|
+
* One coded finding per leg and code. The fix reruns the one primitive: what it reads or writes by
|
|
104
|
+
* input id goes through the repository scoped to `ctx.actor` — or, for a `tenant: 'none'` job's
|
|
105
|
+
* read across every org, a `crossTenant()` scope. Which statement, only the handler shows.
|
|
46
106
|
*/
|
|
47
107
|
export function tenantProofFindings(
|
|
48
108
|
records: readonly ExerciseRecord[],
|
|
49
109
|
): readonly TenantProofFinding[] {
|
|
50
110
|
return records.flatMap((record) => {
|
|
51
|
-
if (record.tenant?.verdict !== 'crossed') return [];
|
|
52
111
|
const name = renderFixShellArg(record.name, '<primitive>');
|
|
53
|
-
return record.
|
|
54
|
-
(
|
|
55
|
-
code:
|
|
56
|
-
cause: causeOf(record,
|
|
57
|
-
fix:
|
|
112
|
+
return crossedGroups(record).map(
|
|
113
|
+
(group): TenantProofFinding => ({
|
|
114
|
+
code: group.code,
|
|
115
|
+
cause: causeOf(record, group),
|
|
116
|
+
fix: fixOf(name, group),
|
|
58
117
|
at: `${record.kind} ${record.name}`,
|
|
59
118
|
}),
|
|
60
119
|
);
|
package/src/tenant-proof.ts
CHANGED
|
@@ -79,6 +79,12 @@ export interface TenantAttack {
|
|
|
79
79
|
* half is skipped. An action or a query answers B directly, so a declared scope excuses nothing.
|
|
80
80
|
*/
|
|
81
81
|
readonly sweep: boolean;
|
|
82
|
+
/**
|
|
83
|
+
* A job declaring `tenant: 'none'` (`bindJobTenant`'s `none`): no org reaches its run. Handed
|
|
84
|
+
* nothing of A's, B's run is A's run — what it writes to A's rows it writes for every enqueuer,
|
|
85
|
+
* so the write half's premise, B choosing A's row, cannot hold: skipped (`tenantlessReason`).
|
|
86
|
+
*/
|
|
87
|
+
readonly tenantless: boolean;
|
|
82
88
|
attack(leg: TenantLeg): Promise<LegAnswer>;
|
|
83
89
|
/** A's positive control: today's exercise of the primitive, and what A's last answer was. */
|
|
84
90
|
control(): Promise<{ readonly record: ExerciseRecord; readonly output: unknown }>;
|
|
@@ -112,6 +118,8 @@ export function leaksIn(
|
|
|
112
118
|
return paths.map((path): TenantFinding => ({ code: 'X_TENANT_LEAK', leg, path }));
|
|
113
119
|
}
|
|
114
120
|
|
|
121
|
+
const asSweep = (finding: TenantFinding): TenantFinding => ({ ...finding, sweep: true });
|
|
122
|
+
|
|
115
123
|
/**
|
|
116
124
|
* The reason a leg's read half is skipped as a declared sweep, or `undefined`: a job, a scope the
|
|
117
125
|
* leg opened, and an input carrying nothing of A's — so no id B chose pointed at A, and what came
|
|
@@ -129,11 +137,25 @@ export function sweepReason(
|
|
|
129
137
|
return `crossTenant(${JSON.stringify(reason)}) declares this job reads across tenants, and B's input named nothing of A's: read half skipped, write half kept`;
|
|
130
138
|
}
|
|
131
139
|
|
|
140
|
+
/**
|
|
141
|
+
* The reason the write half is skipped, or `undefined`: a `tenant: 'none'` job whose input carries
|
|
142
|
+
* none of A's marks — no org and no id of B's choosing reaches the run. Handed one of A's ids, B
|
|
143
|
+
* chose A's row and the write half stands. An action or a query runs as B's actor, so B's org
|
|
144
|
+
* reaches it: a write to A's row with no id handed is an unscoped statement, crossed as ever.
|
|
145
|
+
*/
|
|
146
|
+
export function tenantlessReason(
|
|
147
|
+
plan: Pick<TenantAttack, 'tenantless' | 'taint'>,
|
|
148
|
+
hunted: readonly string[],
|
|
149
|
+
): string | undefined {
|
|
150
|
+
if (!plan.tenantless || hunted.length !== plan.taint.marks.length) return undefined;
|
|
151
|
+
return "tenant: 'none' runs this job under no org, and B's input named nothing of A's: B's run is A's run, so what it writes it writes for every enqueuer — write half skipped, read half kept";
|
|
152
|
+
}
|
|
153
|
+
|
|
132
154
|
const verdictOf = (
|
|
133
155
|
plan: TenantAttack,
|
|
134
156
|
control: { readonly record: ExerciseRecord; readonly output: unknown },
|
|
135
157
|
findings: readonly TenantFinding[],
|
|
136
|
-
|
|
158
|
+
skipped: readonly string[],
|
|
137
159
|
): TenantProof => {
|
|
138
160
|
const { record } = control;
|
|
139
161
|
if (findings.length > 0) return { verdict: 'crossed', findings };
|
|
@@ -144,7 +166,7 @@ const verdictOf = (
|
|
|
144
166
|
};
|
|
145
167
|
}
|
|
146
168
|
if (plan.public !== undefined) return { verdict: 'public', reason: plan.public };
|
|
147
|
-
if (
|
|
169
|
+
if (skipped.length > 0) return { verdict: 'public', reason: skipped.join('; ') };
|
|
148
170
|
// Every mark of A's, handed ones included: A was handed its own ids, and reading them is the point.
|
|
149
171
|
if (plan.read && findTaint(control.output, 'output', plan.taint.marks).length === 0) {
|
|
150
172
|
return {
|
|
@@ -159,19 +181,30 @@ const verdictOf = (
|
|
|
159
181
|
export async function proveTenant(plan: TenantAttack): Promise<ExerciseRecord> {
|
|
160
182
|
const marks = huntedMarks(plan.taint, plan.input);
|
|
161
183
|
const findings: TenantFinding[] = [];
|
|
184
|
+
const unwritten = tenantlessReason(plan, marks);
|
|
162
185
|
let swept: string | undefined;
|
|
163
|
-
|
|
186
|
+
// What `sweepReason` would credit, had the leg opened a scope: the leak's fix is that scope.
|
|
187
|
+
const undeclared = plan.sweep && plan.tenantless && marks.length === plan.taint.marks.length;
|
|
188
|
+
/** B's call, between two snapshots unless the write half is skipped: then none is read. */
|
|
189
|
+
const watched = async (name: TenantLeg): Promise<LegAnswer> => {
|
|
190
|
+
if (unwritten !== undefined) return plan.attack(name);
|
|
164
191
|
const before = await plan.snapshot(plan.taint.rows);
|
|
165
192
|
const answer = await plan.attack(name);
|
|
166
193
|
const after = await plan.snapshot(plan.taint.rows);
|
|
167
194
|
findings.push(...crossedWrites(name, plan.taint, before, after));
|
|
195
|
+
return answer;
|
|
196
|
+
};
|
|
197
|
+
const leg = async (name: TenantLeg): Promise<void> => {
|
|
198
|
+
const answer = await watched(name);
|
|
168
199
|
if (plan.public !== undefined) return;
|
|
169
200
|
const sweep = sweepReason(plan, answer, marks);
|
|
170
|
-
if (sweep
|
|
171
|
-
else
|
|
201
|
+
if (sweep !== undefined) swept = sweep;
|
|
202
|
+
else if (undeclared) findings.push(...leaksIn(name, answer, marks).map(asSweep));
|
|
203
|
+
else findings.push(...leaksIn(name, answer, marks));
|
|
172
204
|
};
|
|
173
205
|
await leg('before');
|
|
174
206
|
const control = await plan.control();
|
|
175
207
|
await leg('after');
|
|
176
|
-
|
|
208
|
+
const skipped = [swept, unwritten].filter((reason) => reason !== undefined);
|
|
209
|
+
return { ...control.record, tenant: verdictOf(plan, control, findings, skipped) };
|
|
177
210
|
}
|
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
// Strings a declared `matches(/…/)` pattern accepts, built by walking the pattern rather than
|
|
2
|
-
// guessing shapes. The common subset only — literals, classes, `.`, groups, alternation,
|
|
3
|
-
// quantifiers, anchors — and an honest `[]` for anything past it (lookaround, backreference, `\b`,
|
|
4
|
-
// `\p{…}`): a pattern this cannot read leaves the column's other candidates to the solver.
|
|
5
|
-
|
|
6
|
-
import { fnv1a } from '@ultimat3/core';
|
|
7
|
-
import { seededRandom } from './determinism';
|
|
8
|
-
|
|
9
|
-
type Node =
|
|
10
|
-
| { readonly kind: 'chars'; readonly chars: readonly string[] }
|
|
11
|
-
| { readonly kind: 'alt'; readonly branches: readonly (readonly Piece[])[] }
|
|
12
|
-
| { readonly kind: 'empty' };
|
|
13
|
-
|
|
14
|
-
interface Piece {
|
|
15
|
-
readonly node: Node;
|
|
16
|
-
readonly min: number;
|
|
17
|
-
readonly max: number;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** How far past its floor an unbounded quantifier draws: enough to vary, short enough to store. */
|
|
21
|
-
const UNBOUNDED_SPAN = 6;
|
|
22
|
-
|
|
23
|
-
/** The universe a class or `.` picks from: printable ASCII, so every sample is plain text. */
|
|
24
|
-
const PRINTABLE = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i));
|
|
25
|
-
const DIGITS = PRINTABLE.filter((c) => c >= '0' && c <= '9');
|
|
26
|
-
const WORD = PRINTABLE.filter((c) => /\w/.test(c));
|
|
27
|
-
const SPACE = [' ', '\t'];
|
|
28
|
-
|
|
29
|
-
const SHORTHAND: Readonly<Record<string, readonly string[]>> = {
|
|
30
|
-
d: DIGITS,
|
|
31
|
-
D: PRINTABLE.filter((c) => !DIGITS.includes(c)),
|
|
32
|
-
w: WORD,
|
|
33
|
-
W: PRINTABLE.filter((c) => !WORD.includes(c)),
|
|
34
|
-
s: SPACE,
|
|
35
|
-
S: PRINTABLE.filter((c) => c !== ' '),
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
const CONTROL: Readonly<Record<string, string>> = { t: '\t', n: '\n', r: '\r', f: '\f', v: '\v' };
|
|
39
|
-
|
|
40
|
-
class Parser {
|
|
41
|
-
private at = 0;
|
|
42
|
-
/** The first construct past the subset; set once, and it ends the walk. */
|
|
43
|
-
private refused: string | undefined;
|
|
44
|
-
constructor(private readonly source: string) {}
|
|
45
|
-
|
|
46
|
-
/** The tree, or `undefined` when any part of the pattern is past the subset. */
|
|
47
|
-
parse(): Node | undefined {
|
|
48
|
-
const node = this.alternation();
|
|
49
|
-
if (this.refused === undefined && this.at < this.source.length) this.refuse('a stray ")"');
|
|
50
|
-
return this.refused === undefined ? node : undefined;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/** Records the refusal and moves to the end, so every loop above stops on its next look. */
|
|
54
|
-
private refuse(construct: string): readonly string[] {
|
|
55
|
-
this.refused ??= construct;
|
|
56
|
-
this.at = this.source.length;
|
|
57
|
-
return [];
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
private peek(): string | undefined {
|
|
61
|
-
return this.source[this.at];
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
private alternation(): Node {
|
|
65
|
-
const branches: Piece[][] = [this.sequence()];
|
|
66
|
-
while (this.peek() === '|') {
|
|
67
|
-
this.at += 1;
|
|
68
|
-
branches.push(this.sequence());
|
|
69
|
-
}
|
|
70
|
-
return { kind: 'alt', branches };
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
private sequence(): Piece[] {
|
|
74
|
-
const pieces: Piece[] = [];
|
|
75
|
-
for (let c = this.peek(); c !== undefined && c !== '|' && c !== ')'; c = this.peek()) {
|
|
76
|
-
const node = this.atom();
|
|
77
|
-
const [min, max] = this.quantifier();
|
|
78
|
-
pieces.push({ node, min, max });
|
|
79
|
-
}
|
|
80
|
-
return pieces;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
private quantifier(): readonly [number, number] {
|
|
84
|
-
const c = this.peek();
|
|
85
|
-
const bounds = /^\{(\d+)(,(\d*))?\}/.exec(this.source.slice(this.at));
|
|
86
|
-
let range: readonly [number, number] | undefined;
|
|
87
|
-
if (c === '*') range = [0, UNBOUNDED_SPAN];
|
|
88
|
-
else if (c === '+') range = [1, 1 + UNBOUNDED_SPAN];
|
|
89
|
-
else if (c === '?') range = [0, 1];
|
|
90
|
-
else if (bounds !== null) {
|
|
91
|
-
const low = Number(bounds[1]);
|
|
92
|
-
const high =
|
|
93
|
-
bounds[2] === undefined ? low : bounds[3] === '' ? low + UNBOUNDED_SPAN : Number(bounds[3]);
|
|
94
|
-
range = [low, high];
|
|
95
|
-
}
|
|
96
|
-
if (range === undefined) return [1, 1];
|
|
97
|
-
this.at += bounds !== null && c === '{' ? bounds[0].length : 1;
|
|
98
|
-
// A lazy quantifier matches the same strings; only the engine's preference differs.
|
|
99
|
-
if (this.peek() === '?') this.at += 1;
|
|
100
|
-
return range;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
private atom(): Node {
|
|
104
|
-
const c = this.peek() as string;
|
|
105
|
-
this.at += 1;
|
|
106
|
-
if (c === '^' || c === '$') return { kind: 'empty' };
|
|
107
|
-
if (c === '.') return { kind: 'chars', chars: PRINTABLE };
|
|
108
|
-
if (c === '[') return { kind: 'chars', chars: this.charClass() };
|
|
109
|
-
if (c === '(') return this.group();
|
|
110
|
-
if (c === '\\') return { kind: 'chars', chars: this.escape(false) };
|
|
111
|
-
if (c === '*' || c === '+' || c === '?' || c === '{')
|
|
112
|
-
return { kind: 'chars', chars: this.refuse(`a bare "${c}"`) };
|
|
113
|
-
return { kind: 'chars', chars: [c] };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
private group(): Node {
|
|
117
|
-
if (this.peek() === '?') {
|
|
118
|
-
const head = this.source.slice(this.at, this.at + 3);
|
|
119
|
-
if (head.startsWith('?:')) this.at += 2;
|
|
120
|
-
else if (/^\?<[A-Za-z_$]/.test(head) && this.source.includes('>', this.at)) {
|
|
121
|
-
this.at = this.source.indexOf('>', this.at) + 1;
|
|
122
|
-
} else return { kind: 'chars', chars: this.refuse(`the lookaround "(${head}"`) };
|
|
123
|
-
}
|
|
124
|
-
const inner = this.alternation();
|
|
125
|
-
if (this.peek() !== ')') return { kind: 'chars', chars: this.refuse('an unclosed group') };
|
|
126
|
-
this.at += 1;
|
|
127
|
-
return inner;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
private escape(inClass: boolean): readonly string[] {
|
|
131
|
-
const c = this.peek();
|
|
132
|
-
if (c === undefined) return this.refuse('a trailing backslash');
|
|
133
|
-
this.at += 1;
|
|
134
|
-
const shorthand = Object.hasOwn(SHORTHAND, c) ? SHORTHAND[c] : undefined;
|
|
135
|
-
if (shorthand !== undefined) return shorthand;
|
|
136
|
-
const control = Object.hasOwn(CONTROL, c) ? CONTROL[c] : undefined;
|
|
137
|
-
if (control !== undefined) return [control];
|
|
138
|
-
const hex = c === 'x' ? 2 : c === 'u' ? 4 : 0;
|
|
139
|
-
if (hex > 0) {
|
|
140
|
-
const digits = this.source.slice(this.at, this.at + hex);
|
|
141
|
-
if (!/^[0-9a-fA-F]+$/.test(digits) || digits.length !== hex) return this.refuse(`\\${c}`);
|
|
142
|
-
this.at += hex;
|
|
143
|
-
return [String.fromCharCode(Number.parseInt(digits, 16))];
|
|
144
|
-
}
|
|
145
|
-
// `\b`, `\B`, a backreference, `\p{…}`, `\k<…>`, `\0`: a position or a reference, not a char.
|
|
146
|
-
if (/[A-Za-z0-9]/.test(c)) return this.refuse(`\\${c}${inClass ? ' in a class' : ''}`);
|
|
147
|
-
return [c];
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/** The members of `[…]`, drawn from printable ASCII; a negated class is its complement there. */
|
|
151
|
-
private charClass(): readonly string[] {
|
|
152
|
-
const negated = this.peek() === '^';
|
|
153
|
-
if (negated) this.at += 1;
|
|
154
|
-
const members = new Set<string>();
|
|
155
|
-
let first = true;
|
|
156
|
-
for (let c = this.peek(); c !== ']' || first; c = this.peek()) {
|
|
157
|
-
if (c === undefined) return this.refuse('an unclosed class');
|
|
158
|
-
first = false;
|
|
159
|
-
const low = this.classMember();
|
|
160
|
-
if (low.length === 1 && this.peek() === '-' && this.source[this.at + 1] !== ']') {
|
|
161
|
-
this.at += 1;
|
|
162
|
-
const high = this.classMember();
|
|
163
|
-
if (high.length !== 1) return this.refuse('a range ending in a shorthand');
|
|
164
|
-
const [from, to] = [(low[0] as string).charCodeAt(0), (high[0] as string).charCodeAt(0)];
|
|
165
|
-
// Past printable ASCII the range's own first member stands in, so `[À-ÿ]` still yields one.
|
|
166
|
-
const inside = PRINTABLE.filter((ch) => ch.charCodeAt(0) >= from && ch.charCodeAt(0) <= to);
|
|
167
|
-
for (const ch of inside.length > 0 ? inside : [String.fromCharCode(from)]) members.add(ch);
|
|
168
|
-
} else {
|
|
169
|
-
for (const ch of low) members.add(ch);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
this.at += 1;
|
|
173
|
-
return negated ? PRINTABLE.filter((ch) => !members.has(ch)) : [...members];
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
private classMember(): readonly string[] {
|
|
177
|
-
const c = this.peek() as string;
|
|
178
|
-
this.at += 1;
|
|
179
|
-
return c === '\\' ? this.escape(true) : [c];
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
const draw = (node: Node, random: () => number): string => {
|
|
184
|
-
const pick = <T>(items: readonly T[]): T | undefined =>
|
|
185
|
-
items[Math.floor(random() * items.length)];
|
|
186
|
-
if (node.kind === 'empty') return '';
|
|
187
|
-
if (node.kind === 'chars') return pick(node.chars) ?? '';
|
|
188
|
-
const branch = pick(node.branches) ?? [];
|
|
189
|
-
return branch
|
|
190
|
-
.map((piece) => {
|
|
191
|
-
const count = piece.min + Math.floor(random() * (piece.max - piece.min + 1));
|
|
192
|
-
return Array.from({ length: count }, () => draw(piece.node, random)).join('');
|
|
193
|
-
})
|
|
194
|
-
.join('');
|
|
195
|
-
};
|
|
196
|
-
|
|
197
|
-
/** Tries per sample: a draw that crosses an anchor (`a^b`) or a flag is retried, never returned. */
|
|
198
|
-
const ATTEMPTS = 8;
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Up to `count` distinct strings `pattern.test` accepts, the same ones for the same `seed` on any
|
|
202
|
-
* machine. Empty when the pattern is past the subset, or when no draw lands inside it.
|
|
203
|
-
*/
|
|
204
|
-
export function patternSamples(pattern: RegExp, seed: string, count = 4): readonly string[] {
|
|
205
|
-
const tree = new Parser(pattern.source).parse();
|
|
206
|
-
if (tree === undefined) return [];
|
|
207
|
-
const random = seededRandom(fnv1a(`${pattern.source}/${pattern.flags}:${seed}`) || 1);
|
|
208
|
-
// `lastIndex` would make `test` stateful under `g`/`y`; a copy without them judges each draw.
|
|
209
|
-
const judge = new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
|
|
210
|
-
const out: string[] = [];
|
|
211
|
-
for (let attempt = 0; attempt < count * ATTEMPTS && out.length < count; attempt += 1) {
|
|
212
|
-
const sample = draw(tree, random);
|
|
213
|
-
if (judge.test(sample) && !out.includes(sample)) out.push(sample);
|
|
214
|
-
}
|
|
215
|
-
return out;
|
|
216
|
-
}
|