@earnestjs/model 0.0.0-stage → 0.2.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.
@@ -0,0 +1,150 @@
1
+ /** The state limit `explore` and `search` use when given none, the same as `earnest verify`. */
2
+ export const DEFAULT_MAX_STATES = 5_000_000;
3
+ /** Checks a caller's `maxStates`, or gives `DEFAULT_MAX_STATES` when it is `undefined` or `null`. */
4
+ export const stateLimit = (given) => {
5
+ const maxStates = given ?? DEFAULT_MAX_STATES;
6
+ if (!Number.isInteger(maxStates) || maxStates < 0) {
7
+ throw new Error(`maxStates must be a whole number that is not negative, not ${maxStates}`);
8
+ }
9
+ return maxStates;
10
+ };
11
+ /**
12
+ * The one breadth-first loop that `search` and `explore` share. States with the same `key` are
13
+ * one state, counted once. When counting a state would pass `maxStates`, the search stops going
14
+ * on, and every counted state not yet expanded is judged.
15
+ */
16
+ export const breadthFirst = (starts, key, maxStates, visitor) => {
17
+ const seen = new Set();
18
+ const visits = [];
19
+ const hasRoom = (state, parent) => {
20
+ const found = key(state);
21
+ if (seen.has(found)) {
22
+ return true;
23
+ }
24
+ if (seen.size >= maxStates) {
25
+ return false;
26
+ }
27
+ seen.add(found);
28
+ visits.push({ state, parent });
29
+ return true;
30
+ };
31
+ let isWithin = true;
32
+ for (const start of starts) {
33
+ isWithin = hasRoom(start, null);
34
+ if (!isWithin) {
35
+ break;
36
+ }
37
+ }
38
+ let expanded = 0;
39
+ for (const from of visits) {
40
+ if (!isWithin) {
41
+ break;
42
+ }
43
+ expanded += 1;
44
+ for (const { move, next } of visitor.expand(from)) {
45
+ isWithin = hasRoom(next, { from, move });
46
+ if (!isWithin) {
47
+ break;
48
+ }
49
+ }
50
+ }
51
+ for (const counted of visits.slice(expanded)) {
52
+ visitor.judge(counted);
53
+ }
54
+ return { visits, reason: isWithin ? null : `state limit of ${maxStates}` };
55
+ };
56
+ /** The shortest trail to a counted state, from the start state it was reached from. */
57
+ export const trailTo = (target) => {
58
+ const steps = [];
59
+ let at = target;
60
+ while (at.parent !== null) {
61
+ steps.push({ move: at.parent.move, state: at.state });
62
+ at = at.parent.from;
63
+ }
64
+ return { start: at.state, steps: steps.reverse() };
65
+ };
66
+ const STUCK = "no move can happen here, and the caller does not mark it as an end";
67
+ class Judge {
68
+ #input;
69
+ #rules;
70
+ #firstBroken = new Map();
71
+ #stuck = null;
72
+ #outside = null;
73
+ constructor(input) {
74
+ this.#input = input;
75
+ this.#rules = input.rules ?? [];
76
+ }
77
+ expand(at) {
78
+ if (!this.#isInRange(at)) {
79
+ return [];
80
+ }
81
+ const moves = this.#input.moves(at.state);
82
+ if (moves.length === 0 && !(this.#input.isEnd?.(at.state) ?? false)) {
83
+ this.#stuck ??= at;
84
+ }
85
+ return moves;
86
+ }
87
+ judge(at) {
88
+ this.#isInRange(at);
89
+ }
90
+ #isInRange(at) {
91
+ const message = this.#input.outside?.(at.state) ?? null;
92
+ if (message !== null) {
93
+ this.#outside ??= { at, message };
94
+ return false;
95
+ }
96
+ for (const [index, rule] of this.#rules.entries()) {
97
+ if (!rule.holds(at.state) && !this.#firstBroken.has(index)) {
98
+ this.#firstBroken.set(index, at);
99
+ }
100
+ }
101
+ return true;
102
+ }
103
+ outcome({ visits, reason }) {
104
+ const findings = [];
105
+ if (this.#stuck !== null) {
106
+ findings.push({ kind: "stuck", message: STUCK, path: trailTo(this.#stuck) });
107
+ }
108
+ if (this.#outside !== null) {
109
+ const { at, message } = this.#outside;
110
+ findings.push({ kind: "out-of-range", message, path: trailTo(at) });
111
+ }
112
+ const unbroken = reason === null && this.#outside === null ? "holds" : "unknown";
113
+ const rules = this.#rules.map((rule, index) => {
114
+ const first = this.#firstBroken.get(index);
115
+ return {
116
+ id: rule.id,
117
+ says: rule.says,
118
+ verdict: first === undefined ? unbroken : "broken",
119
+ path: first === undefined ? null : trailTo(first),
120
+ };
121
+ });
122
+ const hasFailed = findings.length > 0 || rules.some((rule) => rule.verdict === "broken");
123
+ const unfailed = reason === null ? "pass" : "unfinished";
124
+ return {
125
+ status: hasFailed ? "fail" : unfailed,
126
+ states: visits.length,
127
+ rules,
128
+ findings,
129
+ reason,
130
+ *reached() {
131
+ for (const visit of visits) {
132
+ yield trailTo(visit);
133
+ }
134
+ },
135
+ };
136
+ }
137
+ }
138
+ /**
139
+ * Searches every state reachable from `starts` through `moves`, breadth first, for states that
140
+ * are not models: a plain object, a snapshot of a state machine, anything `key` can name. It
141
+ * gives what `explore` gives, with trails of the caller's own moves and states as paths: the
142
+ * count of distinct states, each rule's verdict with the shortest trail to a state that breaks
143
+ * it, the first stuck and out-of-range states, and the shortest trail to every state it
144
+ * reached. States are judged in the order they are reached: start states in the order given,
145
+ * then the moves of each state in the order `moves` lists them.
146
+ */
147
+ export const search = (input) => {
148
+ const judge = new Judge(input);
149
+ return judge.outcome(breadthFirst(input.starts, (state) => input.key(state), stateLimit(input.maxStates), judge));
150
+ };
@@ -0,0 +1,201 @@
1
+ import { type Json, LockValue, MapValue, OwnedLockValue, QueueValue, RequestValue, RetryValue, type Row, SeqValue, SetValue, TimerValue } from "./values.ts";
2
+ /** The most values `Declaration.values` will list before it throws instead. */
3
+ export declare const MOST_VALUES_LISTED = 1000000;
4
+ /**
5
+ * What one kind of declaration knows about its values. `rest` is where a field of this kind
6
+ * starts when it has no `.initial`; `null` means it starts at every value. `adopt` turns what
7
+ * `.initial` accepts into a value, and `decode` reads a value back from its JSON form, throwing
8
+ * when the JSON is of another kind. `libraryKind` is the kind of the first part whose values are
9
+ * objects of this library, or `null` when every value is plain JavaScript. `source` is the `m`
10
+ * expression that builds it. `fields` is a record's declaration of each field, and `inner` the
11
+ * declaration an optional adds `null` to; other kinds leave both out.
12
+ */
13
+ export interface Shape<T, In = T> {
14
+ readonly kind: string;
15
+ readonly source: string;
16
+ readonly count: number;
17
+ readonly libraryKind: string | null;
18
+ readonly fields?: Fields;
19
+ readonly inner?: Declaration<unknown, never>;
20
+ readonly rest: {
21
+ readonly value: T;
22
+ } | null;
23
+ values(): readonly T[];
24
+ has(value: unknown): value is T;
25
+ adopt(value: In): T;
26
+ decode(json: Json): unknown;
27
+ }
28
+ /**
29
+ * The finite set of values a field, an input or a collection member can take. Build one with
30
+ * `m.boolean()`, `m.int(lo, hi)` and the other builders; it is a plain value, so one declaration
31
+ * can be shared by several fields and models. `.optional()` and `.initial(value)` give back a
32
+ * new declaration and leave this one as it was.
33
+ */
34
+ export declare class Declaration<T, In = T> {
35
+ #private;
36
+ /** Model files use the `m` builders instead of calling this. */
37
+ constructor(shape: Shape<T, In>, initial?: {
38
+ readonly value: T;
39
+ } | null);
40
+ /** What was declared, in words: `"enum"`, `"number"`, `"set"` and so on. */
41
+ get kind(): string;
42
+ /** How many values the declaration has. Very large counts are approximate. */
43
+ get count(): number;
44
+ /**
45
+ * Where the values are not plain JavaScript, the kind of the first part that holds objects of
46
+ * this library, such as `SetValue`: `"set"` for `m.set(item)`, also inside `.optional()` or a
47
+ * record. `null` when every value is a boolean, a number, a text, `null` or a record of those,
48
+ * values that any JavaScript code can hold, copy and compare by content.
49
+ */
50
+ get libraryKind(): string | null;
51
+ /**
52
+ * The `m` expression that declares the same values, as a model file writes it, such as
53
+ * `m.int(0, 3).optional()` or `m.record({ seat: m.enum(["A", "B"]) })`. It leaves out
54
+ * `.initial`. Code that writes model files puts it after `m.model`'s field names.
55
+ */
56
+ get source(): string;
57
+ /**
58
+ * For a declaration made with `m.record`, the declaration of each field, as given to
59
+ * `m.record`; `null` for every other kind, an optional record included. Code that checks a
60
+ * value field by field reads it, as `@earnestjs/xstate` does to let an optional field inside a
61
+ * record be missing.
62
+ */
63
+ get fields(): Fields | null;
64
+ /**
65
+ * For a declaration made with `.optional()`, the same declaration without `null` and without
66
+ * `.initial`; `null` for every other kind. Code that checks a value against the declaration
67
+ * step by step reads it, as `fields` is read for a record.
68
+ */
69
+ get inner(): Declaration<unknown, never> | null;
70
+ /**
71
+ * Every value, in the order the checker tries them: `false` before `true`, numbers upward,
72
+ * enum values as listed, `null` before the values of an optional, a record's fields in the
73
+ * order declared with the first one changing slowest. Throws when there are more than
74
+ * `MOST_VALUES_LISTED`.
75
+ */
76
+ values(): readonly T[];
77
+ /** Whether `value` is one of the declared values. Any value may be asked about. */
78
+ has(value: unknown): value is T;
79
+ /**
80
+ * The values a field declared this way starts at: the `.initial` value when there is one;
81
+ * otherwise the empty, free, idle or zero value of a collection, lock, timer, request or
82
+ * retry; otherwise every value.
83
+ */
84
+ starts(): readonly T[];
85
+ /**
86
+ * Reads a value from the form `earnest verify --json` prints. The result may lie outside the
87
+ * declaration, as a value on an out-of-range path does, so check it with `has`. Throws when
88
+ * the JSON is of another kind altogether, such as text where a set is declared.
89
+ */
90
+ fromJson(json: Json): unknown;
91
+ /** The same declaration, starting at `value`. Throws when `value` is not a declared value. */
92
+ initial(value: In): Declaration<T, In>;
93
+ /**
94
+ * The same declaration with `null` as one more value. Without `.initial` it then starts at
95
+ * every value, `null` included. Throws for a declaration that is already optional and for a
96
+ * lock with an owner, whose free state is already `null`.
97
+ */
98
+ optional(): Declaration<T | null, In | null>;
99
+ }
100
+ /**
101
+ * The value a field declared as `declared` starts at when it is given `value` as `.initial`
102
+ * would be. Throws when `value` is not a value of the declaration.
103
+ */
104
+ export declare const startingAt: (declared: Declaration<unknown, never>, value: unknown) => unknown;
105
+ /** The fields of a model or a record, or the inputs of an action: a declaration for each name. */
106
+ export type Fields = Readonly<Record<string, Declaration<unknown, never>>>;
107
+ /**
108
+ * Every row of values the declarations in `entries` give, in the order the checker tries an
109
+ * action's inputs: the first name varies fastest.
110
+ */
111
+ export declare const rowsOf: (entries: readonly (readonly [string, Declaration<unknown, never>])[]) => readonly Row[];
112
+ /**
113
+ * Every combination of one value for each of `fields`, in the order `explore` tries an action's
114
+ * inputs: the first field varies fastest, each through its values in the order of `values()`.
115
+ * Gives one empty row when there are no fields. Throws, before it lists any, when there are more
116
+ * than `MOST_VALUES_LISTED` combinations.
117
+ */
118
+ export declare const combinationsOf: (fields: Fields) => readonly Row[];
119
+ /** The type of the values a declaration has. */
120
+ export type ValueOf<D> = D extends Declaration<infer T, infer _In> ? T : never;
121
+ /** The object type with one read-only property per declared name. */
122
+ export type StateOf<F extends Fields> = {
123
+ readonly [Name in keyof F]: ValueOf<F[Name]>;
124
+ };
125
+ /** Declares a field that is `true` or `false`. */
126
+ export declare const booleanOf: () => Declaration<boolean>;
127
+ /**
128
+ * Declares a whole number from `lo` to `hi`, both included. Arithmetic that leaves the range is
129
+ * not an error in the action: the checker reports the state as out of range. Throws when a bound
130
+ * is not a whole number or `lo` is above `hi`.
131
+ */
132
+ export declare const int: (lo: number, hi: number) => Declaration<number>;
133
+ /** Declares a field that is one of the listed texts. Its type is the union of those literals. */
134
+ export declare const enumOf: <const T extends string>(options: readonly T[]) => Declaration<T>;
135
+ /**
136
+ * Declares a field that is one of the listed values, which are all text, all numbers or all
137
+ * booleans. Its type is the union of those literals.
138
+ */
139
+ export declare const oneOf: <const T extends string | number | boolean>(options: readonly T[]) => Declaration<T>;
140
+ /**
141
+ * Declares a record: an object with exactly the given fields. Read a field with `r.field` and
142
+ * change one with `{ ...r, field: value }`. Compare records field by field: `===` on two records
143
+ * compares the objects, not their content.
144
+ */
145
+ export declare const record: <F extends Fields>(fields: F) => Declaration<StateOf<F>>;
146
+ /** Declares a set of values of `item`. Without `.initial` it starts empty. */
147
+ export declare const set: <T>(item: Declaration<T, never>) => Declaration<SetValue<T>>;
148
+ /**
149
+ * Declares a map from values of `key` to values of `value`. Without `.initial` it starts empty.
150
+ * Throws when `value` is a lock with an owner.
151
+ */
152
+ export declare const map: <K, V>(key: Declaration<K, never>, valueDeclared: Declaration<V, never>) => Declaration<MapValue<K, V>>;
153
+ /**
154
+ * Declares a sequence of at most `max` values of `item`. Without `.initial` it starts empty.
155
+ * Pushing past `max` is not an error in the action: the checker reports the state as out of
156
+ * range. Throws when `item` is a lock with an owner.
157
+ */
158
+ export declare const seq: <T>(itemDeclared: Declaration<T, never>, limit: {
159
+ readonly max: number;
160
+ }) => Declaration<SeqValue<T>>;
161
+ /**
162
+ * Declares a first-in, first-out queue of at most `capacity` values of `item`. Without
163
+ * `.initial` it starts empty; `.initial(m.seqOf(a, b))` starts it with `a` at the head. Sending
164
+ * to a full queue is not an error in the action: the checker reports the state as out of range.
165
+ * Throws when `item` is a lock with an owner.
166
+ */
167
+ export declare const queue: <T>(itemDeclared: Declaration<T, never>, limit: {
168
+ readonly capacity: number;
169
+ }) => Declaration<QueueValue<T>, QueueValue<T> | SeqValue<T>>;
170
+ /**
171
+ * Declares a lock. `m.lock()` is free or held; `m.lock(Owner)` also remembers which value of
172
+ * `Owner` holds it. Without `.initial` it starts free.
173
+ */
174
+ export declare function lock(): Declaration<LockValue>;
175
+ export declare function lock<Owner>(owner: Declaration<Owner, never>): Declaration<OwnedLockValue<Owner>>;
176
+ /** Declares a timer that is idle, running or fired. Without `.initial` it starts idle. */
177
+ export declare const timer: () => Declaration<TimerValue>;
178
+ /**
179
+ * Declares an async request that is idle, pending, succeeded or failed. Without `.initial` it
180
+ * starts idle.
181
+ */
182
+ export declare const request: () => Declaration<RequestValue>;
183
+ /**
184
+ * Declares a count of attempts from zero to `max`. Without `.initial` it starts at zero.
185
+ * Counting past `max` is not an error in the action: the checker reports the state as out of
186
+ * range, so guard `again()` with `canRetry`.
187
+ */
188
+ export declare const retry: (limit: {
189
+ readonly max: number;
190
+ }) => Declaration<RetryValue>;
191
+ /**
192
+ * Whether `test` is true for every value of a declaration, or for every member of a set,
193
+ * sequence or queue. Over a map it is given `[key, value]` pairs. True when there is nothing to
194
+ * test.
195
+ */
196
+ export declare const forall: <T>(over: Declaration<T, never> | Iterable<T>, test: (item: T) => boolean) => boolean;
197
+ /**
198
+ * Whether `test` is true for some value of a declaration, or for some member of a set, sequence
199
+ * or queue. Over a map it is given `[key, value]` pairs. False when there is nothing to test.
200
+ */
201
+ export declare const exists: <T>(over: Declaration<T, never> | Iterable<T>, test: (item: T) => boolean) => boolean;