gdp-wired 0.46.0 → 0.47.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/README.md +3 -1
- package/dist/core/cli.d.ts +1 -0
- package/dist/core/cli.js +3 -3
- package/dist/core/effect-schema.d.ts +90 -0
- package/dist/core/effect-schema.js +500 -0
- package/dist/core/effect.d.ts +3 -7
- package/dist/core/effect.js +2 -64
- package/dist/core/extract-check.js +31 -6
- package/dist/core/extract-go-check.js +24 -4
- package/dist/core/extract-go.d.ts +7 -0
- package/dist/core/extract-go.js +29 -2
- package/dist/core/extract-read.d.ts +9 -1
- package/dist/core/extract-read.js +9 -2
- package/dist/core/extract-rs.js +58 -14
- package/dist/core/extract-shapes.d.ts +1 -0
- package/dist/core/extract-shapes.js +82 -0
- package/dist/core/extract-standalone.d.ts +3 -0
- package/dist/core/extract-standalone.js +221 -0
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/extract.js +16 -2
- package/dist/core/laws.js +35 -11
- package/dist/core/rs/Cargo.toml +1 -1
- package/dist/core/rs/src/main.rs +458 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -231,7 +231,9 @@ All of these are proven automatically, and each proof is also a Lean theorem:
|
|
|
231
231
|
`Semaphore` the service makes is modelled once, its own laws proven (bounded, nothing lost, FIFO, the permits) and
|
|
232
232
|
run beside Effect's own on random operations and fibers, so a law states only the service's own
|
|
233
233
|
(`examples/effect-queue.ts`: a worker pool, a release without its acquire refuted by a run). `conforms(rule, service)` runs a rule written by hand
|
|
234
|
-
beside a running service (Effect's own Semaphore, a store)
|
|
234
|
+
beside a running service (Effect's own Semaphore, a store). `fromSchema(schema)` provides typed symbolic
|
|
235
|
+
[Schema kinds](docs/effect-schema.md): exact on declared closed decoded values by default, with checked integer
|
|
236
|
+
bounds and inspectable, opt-in approximation losses
|
|
235
237
|
(`examples/effect.ts`; what is read and refused, with what Effect projects write, in `research/effect/README.md`).
|
|
236
238
|
- **What nobody stated, looked for when the prover alone stops**: where `proveRule` or `proveSteps` doesn't prove the laws
|
|
237
239
|
and no run breaks them, it looks for lemmas about the rule's recurrences and lists (`discover`), lemmas about the
|
package/dist/core/cli.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { type LawText } from './laws.js';
|
|
|
6
6
|
export declare const colors: (env: Record<string, string | undefined>, tty: boolean, json?: boolean) => boolean;
|
|
7
7
|
export type Opts = {
|
|
8
8
|
entry?: string;
|
|
9
|
+
mode?: 'standalone';
|
|
9
10
|
methods?: string[];
|
|
10
11
|
failures?: 'refuse' | 'kept';
|
|
11
12
|
onError?: 'refuse' | 'discard';
|
package/dist/core/cli.js
CHANGED
|
@@ -176,11 +176,11 @@ async function extractWith(t, o) {
|
|
|
176
176
|
catch {
|
|
177
177
|
return undefined;
|
|
178
178
|
} };
|
|
179
|
-
if (/from\s+['"]effect(\/\w+)?['"]/.test(code)) {
|
|
179
|
+
if (o.mode === undefined && /from\s+['"]effect(\/\w+)?['"]/.test(code)) {
|
|
180
180
|
const { extractEffect } = await import("./effect.js"), effect = await own('effect');
|
|
181
181
|
return extractEffect(file, { ...(effect ? { effect } : {}), ...o });
|
|
182
182
|
}
|
|
183
|
-
if (/from\s+['"]xstate['"]/.test(code) && /\bcreateMachine\b/.test(code)) {
|
|
183
|
+
if (o.mode === undefined && /from\s+['"]xstate['"]/.test(code) && /\bcreateMachine\b/.test(code)) {
|
|
184
184
|
const { extractXState } = await import("./extract-xstate.js"), xstate = await own('xstate');
|
|
185
185
|
return extractXState(file, { ...(xstate ? { xstate } : {}), ...o });
|
|
186
186
|
}
|
|
@@ -1089,7 +1089,7 @@ function printRule(r, o) {
|
|
|
1089
1089
|
out();
|
|
1090
1090
|
}
|
|
1091
1091
|
const label = (n) => (n.role === 'answer' ? `${n.code.split('.').pop()}(...)` : n.role === 'input' && n.method ? `${n.method}(${n.code})` : n.role === 'result' && n.method ? `${n.method}() result` : n.code);
|
|
1092
|
-
const USAGE = `gdp-wired check <file|dir>... [--entry X] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose] [--clock s|ms] [--cert <dir>] [--from any] [--require-review] [--security]
|
|
1092
|
+
const USAGE = `gdp-wired check <file|dir>... [--entry X] [--mode standalone] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose] [--clock s|ms] [--cert <dir>] [--from any] [--require-review] [--security]
|
|
1093
1093
|
gdp-wired draft <file> --clause <text> | --clause-file <file> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]
|
|
1094
1094
|
|
|
1095
1095
|
Reads the rule in each file (Python, Ruby, Elixir, Java, Kotlin, Go, Rust, Swift, C, C++, TypeScript, Effect, XState), checks it
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { Bool, Choice, Cond, Int, Kind, Maybe, Str, Term, type Init, type Raw, type TermLike, Variant } from './dsl.js';
|
|
2
|
+
import type { Rand } from './machine.js';
|
|
3
|
+
export type SchemaLike = {
|
|
4
|
+
readonly ast: unknown;
|
|
5
|
+
};
|
|
6
|
+
type Shape<S> = S extends {
|
|
7
|
+
readonly Encoded: infer A;
|
|
8
|
+
} ? A : unknown;
|
|
9
|
+
type Projected<S> = unknown extends Shape<S> ? unknown : S extends {
|
|
10
|
+
readonly fields: infer F;
|
|
11
|
+
} ? Pick<Shape<S>, Extract<keyof F, keyof Shape<S>>> : Shape<S>;
|
|
12
|
+
type IsUnion<A, Whole = A> = A extends Whole ? [Whole] extends [A] ? false : true : never;
|
|
13
|
+
type CasesOf<A extends {
|
|
14
|
+
readonly _tag: string;
|
|
15
|
+
}> = {
|
|
16
|
+
[K in A['_tag']]: {
|
|
17
|
+
[F in Exclude<Extract<keyof Extract<A, {
|
|
18
|
+
readonly _tag: K;
|
|
19
|
+
}>, string>, '_tag'>]-?: Kind<SchemaValue<Extract<A, {
|
|
20
|
+
readonly _tag: K;
|
|
21
|
+
}>[F]>>;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
/** Symbolic values, never Schema.Type cast as a Kind: numbers are signed Int, booleans Bool, strings Str/Choice. */
|
|
25
|
+
export type SchemaValue<A> = 0 extends 1 & A ? unknown : unknown extends A ? unknown : undefined extends A ? Maybe<SchemaValue<NonNullable<A>>> : null extends A ? Maybe<SchemaValue<NonNullable<A>>> : [A] extends [number] ? Int : [A] extends [boolean] ? Bool : [A] extends [string] ? string extends A ? Str : Choice<A & string> : [A] extends [{
|
|
26
|
+
readonly _tag: string;
|
|
27
|
+
}] ? IsUnion<A> extends true ? Variant<CasesOf<A & {
|
|
28
|
+
readonly _tag: string;
|
|
29
|
+
}>, '_tag'> : {
|
|
30
|
+
[K in keyof A]-?: SchemaValue<A[K]>;
|
|
31
|
+
} : [A] extends [readonly unknown[]] ? never : [A] extends [object] ? {
|
|
32
|
+
[K in keyof A]-?: SchemaValue<A[K]>;
|
|
33
|
+
} : never;
|
|
34
|
+
export type SchemaSymbolic<S> = SchemaValue<Projected<S>>;
|
|
35
|
+
export type SchemaOptions = {
|
|
36
|
+
readonly mode?: 'exact' | 'approximate';
|
|
37
|
+
};
|
|
38
|
+
export type SchemaDiagnostic = {
|
|
39
|
+
readonly path: string;
|
|
40
|
+
readonly code: string;
|
|
41
|
+
readonly message: string;
|
|
42
|
+
readonly effect: 'overapproximation' | 'normalization' | 'projection';
|
|
43
|
+
};
|
|
44
|
+
export type SchemaConstraint = {
|
|
45
|
+
readonly path: string;
|
|
46
|
+
readonly kind: 'integer' | 'literals';
|
|
47
|
+
readonly minimum?: number;
|
|
48
|
+
readonly maximum?: number;
|
|
49
|
+
readonly values?: readonly (string | number | boolean)[];
|
|
50
|
+
};
|
|
51
|
+
export type SchemaReport = {
|
|
52
|
+
readonly mode: 'exact' | 'approximate';
|
|
53
|
+
/** Equality is on safe integers (including -0 as 0), booleans, strings, null, and closed structural records. */
|
|
54
|
+
readonly domain: 'decoded-closed-values';
|
|
55
|
+
readonly runtime: 'exact-on-decoded-closed-values' | 'overapproximation' | 'normalized' | 'projection';
|
|
56
|
+
readonly model: 'exact' | 'overapproximation';
|
|
57
|
+
readonly counterexamples: 'validate-with-schema';
|
|
58
|
+
readonly losses: readonly SchemaDiagnostic[];
|
|
59
|
+
readonly constraints: readonly SchemaConstraint[];
|
|
60
|
+
};
|
|
61
|
+
export declare class SchemaError extends Error {
|
|
62
|
+
readonly path: string;
|
|
63
|
+
readonly code: string;
|
|
64
|
+
constructor(path: string, code: string, message: string);
|
|
65
|
+
}
|
|
66
|
+
/** A regular Kind, with a report that distinguishes runtime conversion from symbolic model precision. */
|
|
67
|
+
export declare class SchemaKind<V> extends Kind<V> {
|
|
68
|
+
private readonly inner;
|
|
69
|
+
readonly report: SchemaReport;
|
|
70
|
+
constructor(inner: Kind<V>, report: SchemaReport);
|
|
71
|
+
vars(name: string): string[];
|
|
72
|
+
assume(name: string): Cond[];
|
|
73
|
+
build(name: string, get: (part: string) => Term): V;
|
|
74
|
+
invariant(value: V): Cond[];
|
|
75
|
+
encode(name: string, raw: Raw): Record<string, number>;
|
|
76
|
+
decode(name: string, vars: Record<string, number>): Raw;
|
|
77
|
+
store(name: string, value: unknown): Record<string, TermLike>;
|
|
78
|
+
empty(): Raw;
|
|
79
|
+
random(name: string, rand: Rand, bound: number): Record<string, number>;
|
|
80
|
+
sample(rand: Rand, bound: number): Raw;
|
|
81
|
+
from(init: Raw | ((params: never) => unknown)): Init<V>;
|
|
82
|
+
/** Build a symbolic value through the same checked store path used by state initialization. */
|
|
83
|
+
make(value: unknown): V;
|
|
84
|
+
}
|
|
85
|
+
/** Exact by default. Approximation is opt-in and every discarded constraint/normalization has a path in report.losses. */
|
|
86
|
+
export declare function fromSchema<const S extends SchemaLike>(schema: S, options?: {
|
|
87
|
+
readonly mode?: 'exact';
|
|
88
|
+
}): SchemaKind<SchemaSymbolic<S>>;
|
|
89
|
+
export declare function fromSchema(schema: SchemaLike, options: SchemaOptions | undefined): SchemaKind<unknown>;
|
|
90
|
+
export {};
|
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
// Effect Schema's decoded-value domain as an ordinary Kind. No Effect import (including type imports): the
|
|
2
|
+
// optional frontend reads the 3.22.x / 4.0.x AST, never runs a predicate, decoder, encoder, or transformation.
|
|
3
|
+
import { Choice, Cond, Int, Kind, Maybe, Str, Term, any, bool, int, lit, oneOf, str, variant, Variant } from "./dsl.js";
|
|
4
|
+
export class SchemaError extends Error {
|
|
5
|
+
path;
|
|
6
|
+
code;
|
|
7
|
+
constructor(path, code, message) {
|
|
8
|
+
super(`fromSchema: ${path || 'the schema'} is ${message}`);
|
|
9
|
+
this.path = path;
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.name = 'SchemaError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** A regular Kind, with a report that distinguishes runtime conversion from symbolic model precision. */
|
|
15
|
+
export class SchemaKind extends Kind {
|
|
16
|
+
inner;
|
|
17
|
+
report;
|
|
18
|
+
constructor(inner, report) {
|
|
19
|
+
super();
|
|
20
|
+
this.inner = inner;
|
|
21
|
+
this.report = report;
|
|
22
|
+
}
|
|
23
|
+
vars(name) { return this.inner.vars(name); }
|
|
24
|
+
assume(name) { return this.inner.assume(name); }
|
|
25
|
+
build(name, get) { return this.inner.build(name, get); }
|
|
26
|
+
invariant(value) { return this.inner.invariant(value); }
|
|
27
|
+
encode(name, raw) { return this.inner.encode(name, raw); }
|
|
28
|
+
decode(name, vars) { return this.inner.decode(name, vars); }
|
|
29
|
+
store(name, value) { return this.inner.store(name, value); }
|
|
30
|
+
empty() { return this.inner.empty(); }
|
|
31
|
+
random(name, rand, bound) { return this.inner.random(name, rand, bound); }
|
|
32
|
+
sample(rand, bound) { return this.inner.sample(rand, bound); }
|
|
33
|
+
// Unlike Kind.from's historical callback, no implicit any is handed to a schema callback. Annotate params.
|
|
34
|
+
from(init) {
|
|
35
|
+
if (typeof init !== 'function')
|
|
36
|
+
this.encode('initial', init);
|
|
37
|
+
return { kind: this, init };
|
|
38
|
+
}
|
|
39
|
+
/** Build a symbolic value through the same checked store path used by state initialization. */
|
|
40
|
+
make(value) {
|
|
41
|
+
const parts = this.store('$schema', value);
|
|
42
|
+
return this.build('$schema', part => { const t = parts[part]; return typeof t === 'number' ? lit(t) : t; });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const fail = (path, code, message) => { throw new SchemaError(path, code, message); };
|
|
46
|
+
const badValue = (name, message) => { throw new RangeError(`${name}: ${message}`); };
|
|
47
|
+
const own = (o, key) => Object.prototype.hasOwnProperty.call(o, key);
|
|
48
|
+
const object = (x) => x !== null && typeof x === 'object' ? x : {};
|
|
49
|
+
const node = (x, path) => typeof object(x)._tag === 'string' ? x : fail(path, 'invalid-ast', 'not a supported Effect AST');
|
|
50
|
+
const tags = { NumberKeyword: 'Number', BooleanKeyword: 'Boolean', StringKeyword: 'String', TypeLiteral: 'Objects', UndefinedKeyword: 'Undefined' };
|
|
51
|
+
const tag = (a) => tags[a._tag] ?? a._tag;
|
|
52
|
+
const at = (path, field) => path ? `${path}.${field}` : field;
|
|
53
|
+
const symAnnotation = (a, id) => {
|
|
54
|
+
const annotations = object(a.annotations), key = Object.getOwnPropertySymbols(annotations).find(k => k.description === `effect/annotation/${id}`);
|
|
55
|
+
return key === undefined ? undefined : annotations[key];
|
|
56
|
+
};
|
|
57
|
+
const plainName = (name, path) => {
|
|
58
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || name in Object.prototype || name === 'prototype')
|
|
59
|
+
fail(path, 'field-name', 'a field/case name outside the plain, non-reserved identifier subset');
|
|
60
|
+
};
|
|
61
|
+
// The range is part of both input assumptions AND the state invariant. A transition is never trusted to keep it.
|
|
62
|
+
class IntegerKind extends Kind {
|
|
63
|
+
minimum;
|
|
64
|
+
maximum;
|
|
65
|
+
values;
|
|
66
|
+
constructor(minimum, maximum, values) {
|
|
67
|
+
super();
|
|
68
|
+
this.minimum = minimum;
|
|
69
|
+
this.maximum = maximum;
|
|
70
|
+
this.values = values;
|
|
71
|
+
}
|
|
72
|
+
vars(name) { return int.vars(name); }
|
|
73
|
+
build(name, get) { return int.build(name, get); }
|
|
74
|
+
invariant(x) { return [x.atLeast(this.minimum), x.atMost(this.maximum), ...(this.values ? [any(...this.values.map(n => x.eq(n)))] : [])]; }
|
|
75
|
+
assume(name) { return this.invariant(this.value(name)); }
|
|
76
|
+
check(name, raw) {
|
|
77
|
+
if (typeof raw !== 'number' || !Number.isSafeInteger(raw) || raw < this.minimum || raw > this.maximum || (this.values && !this.values.includes(raw)))
|
|
78
|
+
badValue(name, 'outside the schema integer domain');
|
|
79
|
+
return raw;
|
|
80
|
+
}
|
|
81
|
+
encode(name, raw) { return int.encode(name, this.check(name, raw)); }
|
|
82
|
+
store(name, value) {
|
|
83
|
+
if (!(value instanceof Int) && !(value instanceof Term))
|
|
84
|
+
this.check(name, value);
|
|
85
|
+
return int.store(name, value);
|
|
86
|
+
}
|
|
87
|
+
decode(name, vars) {
|
|
88
|
+
for (const part of this.vars(name))
|
|
89
|
+
if (!Number.isSafeInteger(vars[part]) || vars[part] < 0)
|
|
90
|
+
badValue(name, 'invalid natural part of an integer');
|
|
91
|
+
return this.check(name, int.decode(name, vars));
|
|
92
|
+
}
|
|
93
|
+
empty() { return this.values?.[0] ?? Math.min(this.maximum, Math.max(this.minimum, 0)); }
|
|
94
|
+
sample(rand, bound) {
|
|
95
|
+
if (this.values)
|
|
96
|
+
return this.values[rand(this.values.length)];
|
|
97
|
+
const near = this.empty(), span = Math.max(0, Math.min(1_000_000, Math.floor(bound)));
|
|
98
|
+
const lo = Math.max(this.minimum, near - span), hi = Math.min(this.maximum, near + span);
|
|
99
|
+
const edges = [this.minimum, this.maximum, near];
|
|
100
|
+
return rand(4) === 0 ? edges[rand(edges.length)] : lo + rand(hi - lo + 1);
|
|
101
|
+
}
|
|
102
|
+
random(name, rand, bound) { return this.encode(name, this.sample(rand, bound)); }
|
|
103
|
+
}
|
|
104
|
+
class BooleanKind extends Kind {
|
|
105
|
+
literal;
|
|
106
|
+
constructor(literal) {
|
|
107
|
+
super();
|
|
108
|
+
this.literal = literal;
|
|
109
|
+
}
|
|
110
|
+
vars(name) { return bool.vars(name); }
|
|
111
|
+
build(name, get) { return bool.build(name, get); }
|
|
112
|
+
invariant(b) { return [...bool.invariant(b), ...(this.literal === undefined ? [] : [b.n.eq(Number(this.literal))])]; }
|
|
113
|
+
assume(name) { return this.invariant(this.value(name)); }
|
|
114
|
+
encode(name, raw) {
|
|
115
|
+
if (typeof raw !== 'boolean' || (this.literal !== undefined && raw !== this.literal))
|
|
116
|
+
badValue(name, 'outside the schema boolean domain');
|
|
117
|
+
return bool.encode(name, raw);
|
|
118
|
+
}
|
|
119
|
+
store(name, value) { return value instanceof Cond ? bool.store(name, value) : this.encode(name, value); }
|
|
120
|
+
decode(name, vars) {
|
|
121
|
+
if (vars[name] !== 0 && vars[name] !== 1)
|
|
122
|
+
badValue(name, 'invalid boolean encoding');
|
|
123
|
+
const raw = vars[name] === 1;
|
|
124
|
+
this.encode(name, raw);
|
|
125
|
+
return raw;
|
|
126
|
+
}
|
|
127
|
+
empty() { return this.literal ?? false; }
|
|
128
|
+
sample(rand) { return this.literal ?? rand(2) === 1; }
|
|
129
|
+
random(name, rand) { return this.encode(name, this.sample(rand)); }
|
|
130
|
+
}
|
|
131
|
+
class ChoiceKind extends Kind {
|
|
132
|
+
values;
|
|
133
|
+
inner;
|
|
134
|
+
constructor(values) {
|
|
135
|
+
super();
|
|
136
|
+
this.values = values;
|
|
137
|
+
this.inner = oneOf(...values);
|
|
138
|
+
}
|
|
139
|
+
vars(name) { return this.inner.vars(name); }
|
|
140
|
+
build(name, get) { return this.inner.build(name, get); }
|
|
141
|
+
invariant(x) { return this.inner.invariant(x); }
|
|
142
|
+
assume(name) { return this.inner.assume(name); }
|
|
143
|
+
encode(name, raw) { return this.inner.encode(name, raw); }
|
|
144
|
+
store(name, value) {
|
|
145
|
+
if (value instanceof Choice && (value.values.length !== this.values.length || value.values.some((v, i) => v !== this.values[i])))
|
|
146
|
+
badValue(name, 'a choice from another schema');
|
|
147
|
+
return this.inner.store(name, value);
|
|
148
|
+
}
|
|
149
|
+
decode(name, vars) {
|
|
150
|
+
if (!Number.isInteger(vars[name]) || vars[name] < 0 || vars[name] >= this.values.length)
|
|
151
|
+
badValue(name, 'invalid choice encoding');
|
|
152
|
+
return this.inner.decode(name, vars);
|
|
153
|
+
}
|
|
154
|
+
empty() { return this.inner.empty(); }
|
|
155
|
+
sample(rand, bound) { return this.inner.sample(rand, bound); }
|
|
156
|
+
random(name, rand, bound) { return this.inner.random(name, rand, bound); }
|
|
157
|
+
}
|
|
158
|
+
class StringKind extends Kind {
|
|
159
|
+
inner = str();
|
|
160
|
+
vars(name) { return this.inner.vars(name); }
|
|
161
|
+
assume(name) { return this.inner.assume(name); }
|
|
162
|
+
build(name, get) { return this.inner.build(name, get); }
|
|
163
|
+
invariant(s) { return [s.id.eq(0).iff(s.length.eq(0))]; }
|
|
164
|
+
encode(name, raw) { return this.inner.encode(name, raw); }
|
|
165
|
+
store(name, value) {
|
|
166
|
+
if (typeof value !== 'string' && !(value instanceof Str))
|
|
167
|
+
badValue(name, 'a schema string is expected');
|
|
168
|
+
return this.inner.store(name, value);
|
|
169
|
+
}
|
|
170
|
+
decode(name, vars) {
|
|
171
|
+
const text = this.inner.decode(name, vars);
|
|
172
|
+
if (typeof text !== 'string')
|
|
173
|
+
return badValue(name, 'invalid string encoding');
|
|
174
|
+
if (vars[`${name}$len`] !== text.length)
|
|
175
|
+
badValue(name, 'string id and length disagree (validate symbolic counterexamples)');
|
|
176
|
+
return text;
|
|
177
|
+
}
|
|
178
|
+
empty() { return ''; }
|
|
179
|
+
sample(rand, bound) { return this.inner.sample(rand, bound); }
|
|
180
|
+
random(name, rand, bound) { return this.inner.random(name, rand, bound); }
|
|
181
|
+
}
|
|
182
|
+
class NullableKind extends Kind {
|
|
183
|
+
inner;
|
|
184
|
+
normalizeUndefined;
|
|
185
|
+
constructor(inner, normalizeUndefined = false) {
|
|
186
|
+
super();
|
|
187
|
+
this.inner = inner;
|
|
188
|
+
this.normalizeUndefined = normalizeUndefined;
|
|
189
|
+
}
|
|
190
|
+
has(name) { return `${name}$some`; }
|
|
191
|
+
vars(name) { return [this.has(name), ...this.inner.vars(name)]; }
|
|
192
|
+
build(name, get) { return new Maybe(get(this.has(name)), this.inner.build(name, get)); }
|
|
193
|
+
invariant(m) { return [m.present.atMost(1), ...this.inner.invariant(m.inner).map(c => m.isSome.implies(c))]; }
|
|
194
|
+
assume(name) { const m = this.value(name); return [m.present.atMost(1), ...this.inner.assume(name).map(c => m.isSome.implies(c))]; }
|
|
195
|
+
encode(name, raw) {
|
|
196
|
+
if (raw === undefined && !this.normalizeUndefined)
|
|
197
|
+
badValue(name, 'undefined is not null');
|
|
198
|
+
return raw === null || raw === undefined ? { [this.has(name)]: 0, ...this.inner.encode(name, this.inner.empty()) } : { [this.has(name)]: 1, ...this.inner.encode(name, raw) };
|
|
199
|
+
}
|
|
200
|
+
store(name, value) {
|
|
201
|
+
if (value instanceof Maybe)
|
|
202
|
+
return { [this.has(name)]: value.present, ...this.inner.store(name, value.inner) };
|
|
203
|
+
if (value === null || value === undefined)
|
|
204
|
+
return this.encode(name, value);
|
|
205
|
+
return { [this.has(name)]: 1, ...this.inner.store(name, value) };
|
|
206
|
+
}
|
|
207
|
+
decode(name, vars) {
|
|
208
|
+
if (vars[this.has(name)] !== 0 && vars[this.has(name)] !== 1)
|
|
209
|
+
badValue(name, 'invalid presence bit');
|
|
210
|
+
return vars[this.has(name)] === 0 ? null : this.inner.decode(name, vars);
|
|
211
|
+
}
|
|
212
|
+
empty() { return null; }
|
|
213
|
+
sample(rand, bound) { return rand(4) === 0 ? null : this.inner.sample(rand, bound); }
|
|
214
|
+
random(name, rand, bound) { return this.encode(name, this.sample(rand, bound)); }
|
|
215
|
+
}
|
|
216
|
+
class StructKind extends Kind {
|
|
217
|
+
fields;
|
|
218
|
+
optional;
|
|
219
|
+
constructor(fields, optional = new Set()) {
|
|
220
|
+
super();
|
|
221
|
+
this.fields = fields;
|
|
222
|
+
this.optional = optional;
|
|
223
|
+
}
|
|
224
|
+
each(name, f) { return Object.entries(this.fields).map(([key, k]) => f(k, at(name, key), key)); }
|
|
225
|
+
vars(name) { return this.each(name, (k, p) => k.vars(p)).flat(); }
|
|
226
|
+
assume(name) { return this.each(name, (k, p) => k.assume(p)).flat(); }
|
|
227
|
+
build(name, get) { return Object.fromEntries(this.each(name, (k, p, key) => [key, k.build(p, get)])); }
|
|
228
|
+
invariant(value) { return this.each('', (k, _, key) => k.invariant(value[key])).flat(); }
|
|
229
|
+
check(name, value) {
|
|
230
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
231
|
+
return badValue(name, 'a closed structural object is expected');
|
|
232
|
+
const o = value;
|
|
233
|
+
for (const key of Reflect.ownKeys(o))
|
|
234
|
+
if (typeof key !== 'string' || !own(this.fields, key))
|
|
235
|
+
badValue(name, 'an object has an undeclared field');
|
|
236
|
+
for (const key of Object.keys(this.fields))
|
|
237
|
+
if (!own(o, key) && !this.optional.has(key))
|
|
238
|
+
badValue(at(name, key), 'a required field is absent');
|
|
239
|
+
return o;
|
|
240
|
+
}
|
|
241
|
+
encode(name, raw) { const o = this.check(name, raw); return Object.assign({}, ...this.each(name, (k, p, key) => k.encode(p, o[key]))); }
|
|
242
|
+
store(name, value) { const o = this.check(name, value); return Object.assign({}, ...this.each(name, (k, p, key) => k.store(p, o[key]))); }
|
|
243
|
+
decode(name, vars) { return Object.fromEntries(this.each(name, (k, p, key) => [key, k.decode(p, vars)])); }
|
|
244
|
+
empty() { return Object.fromEntries(this.each('', (k, _, key) => [key, k.empty()])); }
|
|
245
|
+
sample(rand, bound) { return Object.fromEntries(this.each('', (k, _, key) => [key, k.sample(rand, bound)])); }
|
|
246
|
+
random(name, rand, bound) { return this.encode(name, this.sample(rand, bound)); }
|
|
247
|
+
}
|
|
248
|
+
class TaggedKind extends Kind {
|
|
249
|
+
cases;
|
|
250
|
+
inner;
|
|
251
|
+
names;
|
|
252
|
+
constructor(cases) {
|
|
253
|
+
super();
|
|
254
|
+
this.cases = cases;
|
|
255
|
+
this.inner = variant(cases, { tag: '_tag' });
|
|
256
|
+
this.names = Object.keys(cases);
|
|
257
|
+
}
|
|
258
|
+
vars(name) { return this.inner.vars(name); }
|
|
259
|
+
build(name, get) { return this.inner.build(name, get); }
|
|
260
|
+
assume(name) { const x = this.value(name); return [x.tag.lt(this.names.length), ...this.names.flatMap(k => new StructKind(this.cases[k]).assume(at(name, k)).map(c => x.is(k).implies(c)))]; }
|
|
261
|
+
invariant(x) { return [x.tag.lt(this.names.length), ...this.names.flatMap(k => new StructKind(this.cases[k]).invariant(x.cases[k]).map(c => x.is(k).implies(c)))]; }
|
|
262
|
+
raw(name, value) {
|
|
263
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
264
|
+
return badValue(name, 'a closed tagged object is expected');
|
|
265
|
+
const o = value, tag = own(o, '_tag') ? o._tag : undefined;
|
|
266
|
+
if (typeof tag !== 'string' || !own(this.cases, tag))
|
|
267
|
+
return badValue(name, 'a required known _tag is expected');
|
|
268
|
+
const fields = this.cases[tag];
|
|
269
|
+
for (const key of Reflect.ownKeys(o))
|
|
270
|
+
if (typeof key !== 'string' || (key !== '_tag' && !own(fields, key)))
|
|
271
|
+
badValue(name, 'a tagged object has an undeclared field');
|
|
272
|
+
for (const key of Object.keys(fields))
|
|
273
|
+
if (!own(o, key))
|
|
274
|
+
badValue(at(name, key), 'a required field is absent');
|
|
275
|
+
}
|
|
276
|
+
encode(name, raw) { this.raw(name, raw); return this.inner.encode(name, raw); }
|
|
277
|
+
store(name, value) {
|
|
278
|
+
if (!(value instanceof Variant))
|
|
279
|
+
this.raw(name, value);
|
|
280
|
+
return this.inner.store(name, value);
|
|
281
|
+
}
|
|
282
|
+
decode(name, vars) {
|
|
283
|
+
if (!Number.isInteger(vars[name]) || !this.names[vars[name]])
|
|
284
|
+
badValue(name, 'invalid schema tag');
|
|
285
|
+
return this.inner.decode(name, vars);
|
|
286
|
+
}
|
|
287
|
+
empty() { return this.inner.empty(); }
|
|
288
|
+
sample(rand, bound) { return this.inner.sample(rand, bound); }
|
|
289
|
+
random(name, rand, bound) { return this.encode(name, this.sample(rand, bound)); }
|
|
290
|
+
}
|
|
291
|
+
export function fromSchema(schema, options = {}) {
|
|
292
|
+
const mode = options.mode ?? 'exact', losses = [], constraints = [];
|
|
293
|
+
if (mode !== 'exact' && mode !== 'approximate')
|
|
294
|
+
fail('', 'invalid-mode', 'given an invalid mode (expected exact or approximate)');
|
|
295
|
+
let abstractStrings = false;
|
|
296
|
+
const lose = (path, code, message, effect = 'overapproximation') => {
|
|
297
|
+
if (mode === 'exact')
|
|
298
|
+
fail(path, code, message);
|
|
299
|
+
losses.push({ path, code, message, effect });
|
|
300
|
+
};
|
|
301
|
+
const transformed = (a) => a._tag === 'Transformation' || (Array.isArray(a.encoding) && a.encoding.length > 0);
|
|
302
|
+
const filtersOf = (a, path) => {
|
|
303
|
+
if (transformed(a))
|
|
304
|
+
fail(path, 'transformation', 'a transform/encoding (only decoded domains without transforms are read)');
|
|
305
|
+
const filters = [];
|
|
306
|
+
while (a._tag === 'Refinement') {
|
|
307
|
+
const id = symAnnotation(a, 'SchemaId');
|
|
308
|
+
filters.push({ id: typeof id === 'symbol' ? id.description ?? '' : '', payload: object(symAnnotation(a, 'JSONSchema')) });
|
|
309
|
+
a = node(a.from, path);
|
|
310
|
+
if (transformed(a))
|
|
311
|
+
fail(path, 'transformation', 'a transform under a refinement');
|
|
312
|
+
}
|
|
313
|
+
if (Array.isArray(a.checks))
|
|
314
|
+
for (const x of a.checks) {
|
|
315
|
+
const c = object(x), r = object(object(c.annotations).representation);
|
|
316
|
+
filters.push({ id: c._tag === 'Filter' && typeof r.id === 'string' ? r.id : '', payload: object(r.payload) });
|
|
317
|
+
}
|
|
318
|
+
return { base: a, filters };
|
|
319
|
+
};
|
|
320
|
+
const integers = (fs, path, literals) => {
|
|
321
|
+
let integral = !!literals, minimum = Number.MIN_SAFE_INTEGER, maximum = Number.MAX_SAFE_INTEGER;
|
|
322
|
+
const bound = (payload, key) => typeof payload[key] === 'number' && Number.isFinite(payload[key]) ? payload[key] : fail(path, 'invalid-bound', 'an unrecognized or non-finite integer bound');
|
|
323
|
+
for (const f of fs) {
|
|
324
|
+
switch (f.id) {
|
|
325
|
+
case 'effect/SchemaId/Int':
|
|
326
|
+
case 'effect/schema/isInt':
|
|
327
|
+
integral = true;
|
|
328
|
+
break;
|
|
329
|
+
case 'effect/SchemaId/GreaterThan':
|
|
330
|
+
case 'effect/schema/isGreaterThan':
|
|
331
|
+
minimum = Math.max(minimum, Math.floor(bound(f.payload, 'exclusiveMinimum')) + 1);
|
|
332
|
+
break;
|
|
333
|
+
case 'effect/SchemaId/GreaterThanOrEqualTo':
|
|
334
|
+
case 'effect/schema/isGreaterThanOrEqualTo':
|
|
335
|
+
minimum = Math.max(minimum, Math.ceil(bound(f.payload, 'minimum')));
|
|
336
|
+
break;
|
|
337
|
+
case 'effect/SchemaId/LessThan':
|
|
338
|
+
case 'effect/schema/isLessThan':
|
|
339
|
+
maximum = Math.min(maximum, Math.ceil(bound(f.payload, 'exclusiveMaximum')) - 1);
|
|
340
|
+
break;
|
|
341
|
+
case 'effect/SchemaId/LessThanOrEqualTo':
|
|
342
|
+
case 'effect/schema/isLessThanOrEqualTo':
|
|
343
|
+
maximum = Math.min(maximum, Math.floor(bound(f.payload, 'maximum')));
|
|
344
|
+
break;
|
|
345
|
+
case 'effect/SchemaId/Between':
|
|
346
|
+
case 'effect/schema/isBetween':
|
|
347
|
+
minimum = Math.max(minimum, Math.ceil(bound(f.payload, 'minimum')));
|
|
348
|
+
maximum = Math.min(maximum, Math.floor(bound(f.payload, 'maximum')));
|
|
349
|
+
break;
|
|
350
|
+
case 'effect/SchemaId/Finite':
|
|
351
|
+
case 'effect/schema/isFinite':
|
|
352
|
+
case 'effect/SchemaId/NonNaN': break; // implied by safe integer, checked below
|
|
353
|
+
default: lose(path, 'unsupported-refinement', `an unsupported numeric refinement (${f.id || 'custom predicate'}); no predicate is executed`);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (!integral)
|
|
357
|
+
fail(path, 'fractional-number', 'a number that may be fractional (use Schema.Int)');
|
|
358
|
+
if (minimum > maximum || (literals && (!literals.length || literals.some(n => !Number.isSafeInteger(n)))))
|
|
359
|
+
fail(path, 'empty-integer-domain', 'an empty or non-safe integer domain');
|
|
360
|
+
const values = literals?.filter(n => n >= minimum && n <= maximum);
|
|
361
|
+
if (values?.length === 0)
|
|
362
|
+
fail(path, 'empty-integer-domain', 'an empty integer domain');
|
|
363
|
+
constraints.push({ path, kind: 'integer', minimum, maximum, ...(values ? { values } : {}) });
|
|
364
|
+
return new IntegerKind(minimum, maximum, values);
|
|
365
|
+
};
|
|
366
|
+
const fieldsOf = (a, path, tagged = false) => {
|
|
367
|
+
if (!Array.isArray(a.propertySignatures) || (Array.isArray(a.indexSignatures) && a.indexSignatures.length))
|
|
368
|
+
fail(path, 'index-signature', 'an object with an index signature or unknown fields');
|
|
369
|
+
const fields = {}, optional = new Set();
|
|
370
|
+
for (const raw of a.propertySignatures) {
|
|
371
|
+
const p = object(raw), name = p.name;
|
|
372
|
+
if (typeof name !== 'string')
|
|
373
|
+
fail(path, 'field-name', 'a symbol/numeric property (plain named fields are read)');
|
|
374
|
+
plainName(name, path);
|
|
375
|
+
if (tagged && name === '_tag')
|
|
376
|
+
continue;
|
|
377
|
+
const field = name, location = at(path, field), child = node(p.type, location);
|
|
378
|
+
const absent = p.isOptional === true || object(p.context).isOptional === true || object(child.context).isOptional === true;
|
|
379
|
+
if (absent) {
|
|
380
|
+
lose(location, 'optional-to-null', 'an optional property; missing and undefined would normalize to null', 'normalization');
|
|
381
|
+
optional.add(field);
|
|
382
|
+
}
|
|
383
|
+
let k = go(child, location);
|
|
384
|
+
if (absent && !(k instanceof NullableKind))
|
|
385
|
+
k = new NullableKind(k, true);
|
|
386
|
+
if (absent && k instanceof NullableKind && !k.normalizeUndefined)
|
|
387
|
+
k = new NullableKind(k.inner, true);
|
|
388
|
+
if (own(fields, field))
|
|
389
|
+
fail(location, 'duplicate-field', 'a duplicate field');
|
|
390
|
+
fields[field] = k;
|
|
391
|
+
}
|
|
392
|
+
return { fields, optional };
|
|
393
|
+
};
|
|
394
|
+
const go = (source, path) => {
|
|
395
|
+
const { base: a, filters } = filtersOf(source, path), t = tag(a);
|
|
396
|
+
if (t === 'Number')
|
|
397
|
+
return integers(filters, path);
|
|
398
|
+
if (t === 'Literal' && typeof a.literal === 'number')
|
|
399
|
+
return integers(filters, path, [a.literal]);
|
|
400
|
+
for (const f of filters)
|
|
401
|
+
lose(path, 'unsupported-refinement', `an unsupported ${t} refinement (${f.id || 'custom predicate'}); no predicate is executed`);
|
|
402
|
+
if (t === 'Boolean')
|
|
403
|
+
return new BooleanKind();
|
|
404
|
+
if (t === 'String') {
|
|
405
|
+
abstractStrings = true;
|
|
406
|
+
return new StringKind();
|
|
407
|
+
}
|
|
408
|
+
if (t === 'Literal') {
|
|
409
|
+
if (typeof a.literal === 'string') {
|
|
410
|
+
constraints.push({ path, kind: 'literals', values: [a.literal] });
|
|
411
|
+
return new ChoiceKind([a.literal]);
|
|
412
|
+
}
|
|
413
|
+
if (typeof a.literal === 'boolean')
|
|
414
|
+
return new BooleanKind(a.literal);
|
|
415
|
+
}
|
|
416
|
+
if (t === 'Objects') {
|
|
417
|
+
const { fields, optional } = fieldsOf(a, path);
|
|
418
|
+
return new StructKind(fields, optional);
|
|
419
|
+
}
|
|
420
|
+
if (t !== 'Union')
|
|
421
|
+
return fail(path, 'unsupported-schema', `a ${a._tag} schema (arrays, dynamic collections, standalone null/undefined and declarations are not ordinary Kinds)`);
|
|
422
|
+
if (!Array.isArray(a.types) || !a.types.length)
|
|
423
|
+
return fail(path, 'empty-union', 'an empty union');
|
|
424
|
+
const types = a.types.map(x => node(x, path));
|
|
425
|
+
if (types.length === 1)
|
|
426
|
+
return go(types[0], path);
|
|
427
|
+
for (const member of types) {
|
|
428
|
+
const inspected = filtersOf(member, path);
|
|
429
|
+
if (['Literal', 'Null', 'Undefined'].includes(tag(inspected.base)))
|
|
430
|
+
for (const f of inspected.filters)
|
|
431
|
+
lose(path, 'unsupported-refinement', `a refined union alternative (${f.id || 'custom predicate'})`);
|
|
432
|
+
}
|
|
433
|
+
const missing = types.filter(x => tag(x) === 'Null' || tag(x) === 'Undefined' || (x._tag === 'Literal' && x.literal === null));
|
|
434
|
+
const rest = types.filter(x => !missing.includes(x));
|
|
435
|
+
if (missing.length) {
|
|
436
|
+
const hasUndefined = missing.some(x => tag(x) === 'Undefined');
|
|
437
|
+
if (hasUndefined)
|
|
438
|
+
lose(path, 'undefined-to-null', 'a union with undefined; undefined would normalize to null', 'normalization');
|
|
439
|
+
if (rest.length !== 1)
|
|
440
|
+
fail(path, 'unsupported-union', 'a nullable union without exactly one value domain');
|
|
441
|
+
const inner = go(rest[0], path);
|
|
442
|
+
return inner instanceof NullableKind ? new NullableKind(inner.inner, hasUndefined || inner.normalizeUndefined) : new NullableKind(inner, hasUndefined);
|
|
443
|
+
}
|
|
444
|
+
if (types.every(x => x._tag === 'Literal' && typeof x.literal === 'string')) {
|
|
445
|
+
const values = [...new Set(types.map(x => x.literal))];
|
|
446
|
+
constraints.push({ path, kind: 'literals', values });
|
|
447
|
+
return new ChoiceKind(values);
|
|
448
|
+
}
|
|
449
|
+
if (types.every(x => x._tag === 'Literal' && typeof x.literal === 'number'))
|
|
450
|
+
return integers([], path, [...new Set(types.map(x => x.literal))]);
|
|
451
|
+
if (types.every(x => x._tag === 'Literal' && typeof x.literal === 'boolean'))
|
|
452
|
+
return new BooleanKind(types.every(x => x.literal === types[0].literal) ? types[0].literal : undefined);
|
|
453
|
+
const cases = {};
|
|
454
|
+
for (const x of types) {
|
|
455
|
+
// Do not discard checks/transformations attached to a union member while reading its fields.
|
|
456
|
+
const member = filtersOf(x, path);
|
|
457
|
+
if (tag(member.base) !== 'Objects')
|
|
458
|
+
fail(path, 'unsupported-union', 'a union other than literals, NullOr, or distinct _tag structs');
|
|
459
|
+
for (const f of member.filters)
|
|
460
|
+
lose(path, 'unsupported-refinement', `a refined union member (${f.id || 'custom predicate'})`);
|
|
461
|
+
const props = member.base.propertySignatures;
|
|
462
|
+
if (!Array.isArray(props))
|
|
463
|
+
fail(path, 'unsupported-union', 'a tagged member without declared fields');
|
|
464
|
+
const p = props.map(object).find(p => p.name === '_tag'), litTag = p && node(p.type, path);
|
|
465
|
+
if (!litTag || litTag._tag !== 'Literal' || typeof litTag.literal !== 'string' || p?.isOptional || object(p?.context).isOptional || object(litTag.context).isOptional)
|
|
466
|
+
return fail(path, 'unsupported-union', 'a member without a required literal _tag');
|
|
467
|
+
const name = litTag.literal;
|
|
468
|
+
plainName(name, path);
|
|
469
|
+
if (own(cases, name))
|
|
470
|
+
fail(path, 'duplicate-tag', 'a union with duplicate _tag values');
|
|
471
|
+
// Tag predicates are not field metadata.
|
|
472
|
+
go(litTag, at(path, '_tag'));
|
|
473
|
+
const fields = fieldsOf(member.base, at(path, name), true);
|
|
474
|
+
if (fields.optional.size)
|
|
475
|
+
fail(path, 'optional-variant', 'an optional field in a variant (normalization is supported only for records)');
|
|
476
|
+
cases[name] = fields.fields;
|
|
477
|
+
}
|
|
478
|
+
return new TaggedKind(cases);
|
|
479
|
+
};
|
|
480
|
+
let ast = node(schema.ast, '');
|
|
481
|
+
const fields = schema.fields;
|
|
482
|
+
if (fields && tag(ast) !== 'Objects') {
|
|
483
|
+
lose('', 'class-fields', 'a Schema.Class/declaration: only declared fields, not instances, methods or prototype, are projected', 'projection');
|
|
484
|
+
// A class can carry additional predicates; projection does not silently discard those either.
|
|
485
|
+
let outer = ast;
|
|
486
|
+
while (outer._tag === 'Refinement') {
|
|
487
|
+
lose('', 'unsupported-refinement', 'an additional class refinement is not modeled');
|
|
488
|
+
outer = node(outer.from, '');
|
|
489
|
+
}
|
|
490
|
+
if (Array.isArray(outer.checks))
|
|
491
|
+
for (const _check of outer.checks)
|
|
492
|
+
lose('', 'unsupported-refinement', 'an additional class check is not modeled');
|
|
493
|
+
ast = { _tag: 'Objects', propertySignatures: Object.entries(fields).map(([name, f]) => ({ name, type: f.ast })), indexSignatures: [] };
|
|
494
|
+
}
|
|
495
|
+
const inner = go(ast, '');
|
|
496
|
+
const runtime = losses.some(l => l.effect === 'projection') ? 'projection' : losses.some(l => l.effect === 'normalization') ? 'normalized' : losses.length ? 'overapproximation' : 'exact-on-decoded-closed-values';
|
|
497
|
+
const report = Object.freeze({ mode, domain: 'decoded-closed-values', runtime, model: abstractStrings || losses.length ? 'overapproximation' : 'exact', counterexamples: 'validate-with-schema', losses: Object.freeze(losses.map(l => Object.freeze(l))), constraints: Object.freeze(constraints.map(c => Object.freeze({ ...c, ...(c.values ? { values: Object.freeze([...c.values]) } : {}) }))) });
|
|
498
|
+
// The exact overload follows the supported structural shape. Approximation never promises a narrowed Type.
|
|
499
|
+
return new SchemaKind(inner, report);
|
|
500
|
+
}
|
package/dist/core/effect.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Rule } from './dsl.js';
|
|
2
2
|
import { type Law, type Rand } from './machine.js';
|
|
3
3
|
import { type Source } from './extract-read.js';
|
|
4
4
|
import { type ExtractOptions, type Extraction } from './extract.js';
|
|
@@ -73,9 +73,5 @@ export declare function conforms<S>(r: Rule, svc: Service<S>, opts: {
|
|
|
73
73
|
checked: number;
|
|
74
74
|
failure?: string;
|
|
75
75
|
};
|
|
76
|
-
export
|
|
77
|
-
|
|
78
|
-
fields?: Record<string, {
|
|
79
|
-
ast: unknown;
|
|
80
|
-
}>;
|
|
81
|
-
}): Kind<any>;
|
|
76
|
+
export { fromSchema, SchemaError, SchemaKind } from './effect-schema.js';
|
|
77
|
+
export type { SchemaConstraint, SchemaDiagnostic, SchemaLike, SchemaOptions, SchemaReport, SchemaSymbolic, SchemaValue } from './effect-schema.js';
|