@earnestjs/model 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/dist/model.js ADDED
@@ -0,0 +1,140 @@
1
+ import { record } from "./declarations.js";
2
+ import { frozen, isRecord } from "./values.js";
3
+ let partsOf;
4
+ /**
5
+ * A model: named fields, and the actions, rules, ends and views that `m.action`, `m.rule`,
6
+ * `m.end` and `m.view` have declared on it, in the order they were called, which is the order a
7
+ * search tries actions in.
8
+ */
9
+ export class Model {
10
+ name;
11
+ fields;
12
+ #state;
13
+ #parts = { actions: [], rules: [], ends: [], views: [] };
14
+ static {
15
+ partsOf = (model) => model.#parts;
16
+ }
17
+ /** Model files call `m.model(name, fields)` instead. */
18
+ constructor(name, fields) {
19
+ this.name = name;
20
+ this.fields = fields;
21
+ this.#state = record(fields);
22
+ }
23
+ /** Whether `state` has exactly the model's fields, each at a value its declaration has. */
24
+ has(state) {
25
+ return this.#state.has(state);
26
+ }
27
+ /**
28
+ * Every start state, in the order the checker visits them: fields in declaration order, the
29
+ * first field varying slowest.
30
+ */
31
+ starts() {
32
+ const isState = (row) => this.has(row);
33
+ return Object.entries(this.fields)
34
+ .reduce((partial, [name, declared]) => partial.flatMap((prefix) => declared.starts().map((value) => ({ ...prefix, [name]: value }))), [{}])
35
+ .map(frozen)
36
+ .filter(isState);
37
+ }
38
+ /** The views declared so far, in declaration order. */
39
+ get views() {
40
+ return [...this.#parts.views];
41
+ }
42
+ /**
43
+ * The actions, rules and ends declared so far, in a form a search can run without knowing
44
+ * the model's types. `explore` and `replay` are built on this.
45
+ */
46
+ runners() {
47
+ const { actions, rules, ends } = this.#parts;
48
+ return { actions: [...actions], rules: [...rules], ends: [...ends] };
49
+ }
50
+ }
51
+ const known = (model, state) => {
52
+ if (!model.has(state)) {
53
+ throw new Error(`${model.name}: the state is outside what the model declares`);
54
+ }
55
+ return state;
56
+ };
57
+ const changed = (model, state, changes, sentence) => {
58
+ if (!isRecord(changes)) {
59
+ throw new Error(`${model.name}: the change of "${sentence}" must give back an object holding the fields that change`);
60
+ }
61
+ const stray = Object.keys(changes).find((name) => !Object.hasOwn(model.fields, name));
62
+ if (stray !== undefined) {
63
+ throw new Error(`${model.name}: the change of "${sentence}" gives \`${stray}\`, which is not a field of the model`);
64
+ }
65
+ return frozen({ ...state, ...changes });
66
+ };
67
+ /**
68
+ * Declares a model: a name and its fields, each built with an `m` builder. The state type is
69
+ * inferred from the fields; `m.Infer<typeof Model>` names it.
70
+ */
71
+ export const model = (name, fields) => new Model(name, fields);
72
+ /**
73
+ * Declares something that can happen in `model`. `sentence` says it in the reviewer's words.
74
+ * Export the result from the model file: the name of the export is the action's id. Actions are
75
+ * tried in the order they are declared. `input`, `when` and `changes` may be written in any
76
+ * order; `changes` is the only one that is required.
77
+ */
78
+ export const action = (model, sentence, spec) => {
79
+ const declared = spec.input === undefined ? null : record(spec.input);
80
+ const isInput = (input) => declared === null ? isRecord(input) && Object.keys(input).length === 0 : declared.has(input);
81
+ const knownInput = (input) => {
82
+ if (!isInput(input)) {
83
+ throw new Error(`${model.name}: "${sentence}" was given an input it does not declare`);
84
+ }
85
+ return input;
86
+ };
87
+ const declaredAction = Object.freeze({
88
+ kind: "action",
89
+ sentence,
90
+ input: spec.input,
91
+ when: spec.when ?? (() => true),
92
+ changes: spec.changes,
93
+ });
94
+ partsOf(model).actions.push({
95
+ part: declaredAction,
96
+ sentence,
97
+ inputs: spec.input === undefined ? [] : Object.entries(spec.input),
98
+ when: (state, input) => declaredAction.when(known(model, state), knownInput(input)),
99
+ changes: (state, input) => changed(model, state, declaredAction.changes(known(model, state), knownInput(input)), sentence),
100
+ });
101
+ return declaredAction;
102
+ };
103
+ /**
104
+ * Declares a rule of `model`: `holds` must be true in every state the model can reach.
105
+ * `sentence` says it in the reviewer's words. Export the result from the model file: the name
106
+ * of the export is the rule's id.
107
+ */
108
+ export const rule = (model, sentence, holds) => {
109
+ const declaredRule = Object.freeze({ kind: "rule", says: sentence, holds });
110
+ partsOf(model).rules.push({
111
+ part: declaredRule,
112
+ says: sentence,
113
+ holds: (state) => declaredRule.holds(known(model, state)),
114
+ });
115
+ return declaredRule;
116
+ };
117
+ /**
118
+ * Declares where stopping is correct in `model`, so that those states are not reported as
119
+ * stuck. `sentence` says it in the reviewer's words. Export the result from the model file: the
120
+ * name of the export is the end's id.
121
+ */
122
+ export const end = (model, sentence, when) => {
123
+ const declaredEnd = Object.freeze({ kind: "end", says: sentence, when });
124
+ partsOf(model).ends.push({
125
+ part: declaredEnd,
126
+ says: sentence,
127
+ when: (state) => declaredEnd.when(known(model, state)),
128
+ });
129
+ return declaredEnd;
130
+ };
131
+ /**
132
+ * Declares how `earnest chart` draws `model`. A model needs no view, and a view has no id, so
133
+ * its constant needs no export. In a model file, write the second argument, even as `{}`: the
134
+ * checker refuses `m.view(model)`.
135
+ */
136
+ export const view = (model, spec = {}) => {
137
+ const declaredView = Object.freeze({ ...spec, kind: "view" });
138
+ partsOf(model).views.push(declaredView);
139
+ return declaredView;
140
+ };
@@ -0,0 +1,35 @@
1
+ import type { AnyModel } from "./model.ts";
2
+ import { type Exports, type Named } from "./search.ts";
3
+ import { type Json } from "./values.ts";
4
+ /**
5
+ * One step of a path to replay. `action` is the action's id and `label` its sentence; the
6
+ * action is found by id when the model file's exports are passed, and by sentence otherwise.
7
+ * `state` is the whole state the step must lead to.
8
+ */
9
+ export interface ReplayStep {
10
+ readonly action: string;
11
+ readonly label?: string;
12
+ readonly input?: readonly Named[];
13
+ readonly state: readonly Named[];
14
+ }
15
+ /** A path as `earnest verify --json` and `explore` give it; `changes` is not needed. */
16
+ export interface ReplayPath {
17
+ readonly start: readonly Named[];
18
+ readonly steps: readonly ReplayStep[];
19
+ }
20
+ /** `exports` is the model file's exports, which let a step's `action` id be matched. */
21
+ export interface ReplayOptions {
22
+ readonly exports?: Exports;
23
+ }
24
+ /** A state with each field in JSON form. */
25
+ export type StateJson = {
26
+ readonly [field: string]: Json;
27
+ };
28
+ /**
29
+ * Applies a path one action at a time and gives every state it passes through, the start state
30
+ * first, each with its fields in JSON form. Throws an error that names the step when the path
31
+ * does not begin at a start state, a step names no action of the model, an input is missing or
32
+ * undeclared, the action's `when` is false, the action can't be evaluated, or the state after
33
+ * the action differs from the step's `state`. Set members may be listed in any order.
34
+ */
35
+ export declare const replay: (model: AnyModel, path: ReplayPath, options?: ReplayOptions) => StateJson[];
package/dist/replay.js ADDED
@@ -0,0 +1,97 @@
1
+ import { attempt, namer, nextState } from "./search.js";
2
+ import { keyOf, toJson } from "./values.js";
3
+ const messageOf = (thrown) => thrown instanceof Error ? thrown.message : String(thrown);
4
+ const readAll = (where, declared, named) => {
5
+ const given = new Map(named.map((each) => [each.name, each.value]));
6
+ const stray = named.find((each) => !declared.some(([name]) => name === each.name));
7
+ if (stray !== undefined) {
8
+ throw new Error(`${where} names \`${stray.name}\`, which is not declared`);
9
+ }
10
+ return Object.fromEntries(declared.map(([name, declaration]) => {
11
+ const json = given.get(name);
12
+ if (json === undefined) {
13
+ throw new Error(`${where} has no value for \`${name}\``);
14
+ }
15
+ try {
16
+ return [name, declaration.fromJson(json)];
17
+ }
18
+ catch (thrown) {
19
+ throw new Error(`${where} can't be read at \`${name}\`: ${messageOf(thrown)}`);
20
+ }
21
+ }));
22
+ };
23
+ const outside = (declared, row) => {
24
+ const found = declared.find(([name, declaration]) => !declaration.has(row[name]));
25
+ return found === undefined ? null : found[0];
26
+ };
27
+ const stateKey = (fields, row) => fields.map(([name]) => keyOf(row[name])).join(";");
28
+ const text = (value) => JSON.stringify(toJson(value));
29
+ const actionFor = (where, actions, step, options) => {
30
+ const name = namer(options.exports);
31
+ const byId = actions.filter((each) => name(each.part, each.sentence) === step.action);
32
+ const matching = byId.length > 0 ? byId : actions.filter((each) => each.sentence === step.label);
33
+ const [found, ...others] = matching;
34
+ if (found === undefined) {
35
+ throw new Error(`${where}: the model has no action with this id or label; pass the model file's exports so that ids can be matched`);
36
+ }
37
+ if (others.length > 0) {
38
+ throw new Error(`${where}: more than one action matches; pass the model file's exports so that ids can be matched`);
39
+ }
40
+ return found;
41
+ };
42
+ const applied = (where, fields, action, state, input) => {
43
+ const unfit = outside(fields, state);
44
+ if (unfit !== null) {
45
+ throw new Error(`${where}: the state before it is out of range at \`${unfit}\`, so no action can follow`);
46
+ }
47
+ const strange = outside(action.inputs, input);
48
+ if (strange !== null) {
49
+ throw new Error(`${where}: the input \`${strange}\` is ${text(input[strange])}, which is not a value it declares`);
50
+ }
51
+ const can = attempt(() => action.when(state, input));
52
+ if (can.fault !== null) {
53
+ throw new Error(`${where}: the condition of the action ${can.fault} in this state`);
54
+ }
55
+ if (!can.value) {
56
+ throw new Error(`${where}: the condition of the action is false in this state`);
57
+ }
58
+ const next = nextState(action, state, input);
59
+ if (next.fault !== null) {
60
+ throw new Error(`${where}: the change of the action ${next.fault} in this state`);
61
+ }
62
+ return next.value;
63
+ };
64
+ /**
65
+ * Applies a path one action at a time and gives every state it passes through, the start state
66
+ * first, each with its fields in JSON form. Throws an error that names the step when the path
67
+ * does not begin at a start state, a step names no action of the model, an input is missing or
68
+ * undeclared, the action's `when` is false, the action can't be evaluated, or the state after
69
+ * the action differs from the step's `state`. Set members may be listed in any order.
70
+ */
71
+ export const replay = (model, path, options = {}) => {
72
+ const fields = Object.entries(model.fields);
73
+ const actions = model.runners().actions;
74
+ const given = readAll(`${model.name}: the start of the path`, fields, path.start);
75
+ const start = model.starts().find((each) => stateKey(fields, each) === stateKey(fields, given));
76
+ if (start === undefined) {
77
+ throw new Error(`${model.name}: the path does not begin at a start state of the model`);
78
+ }
79
+ const states = [start];
80
+ let state = start;
81
+ for (const [position, step] of path.steps.entries()) {
82
+ const where = `${model.name}: step ${position + 1} (${step.action})`;
83
+ const action = actionFor(where, actions, step, options);
84
+ const input = readAll(`${where}: the input`, action.inputs, step.input ?? []);
85
+ const next = applied(where, fields, action, state, input);
86
+ const expected = readAll(`${where}: the state`, fields, step.state);
87
+ const differing = fields
88
+ .filter(([name]) => keyOf(next[name]) !== keyOf(expected[name]))
89
+ .map(([name]) => `\`${name}\` is ${text(next[name])} but the path has ${text(expected[name])}`);
90
+ if (differing.length > 0) {
91
+ throw new Error(`${where}: the state after the action differs from the path: ${differing.join("; ")}`);
92
+ }
93
+ states.push(next);
94
+ state = next;
95
+ }
96
+ return states.map((row) => Object.fromEntries(fields.map(([name]) => [name, toJson(row[name])])));
97
+ };
@@ -0,0 +1,121 @@
1
+ import type { ActionRunner, AnyModel } from "./model.ts";
2
+ import { type Json, type Row } from "./values.ts";
3
+ /** A field or an input with its value in JSON form. */
4
+ export interface Named {
5
+ readonly name: string;
6
+ readonly value: Json;
7
+ }
8
+ /** A field an action changed, with its value before and after. */
9
+ export interface Change {
10
+ readonly field: string;
11
+ readonly before: Json;
12
+ readonly after: Json;
13
+ }
14
+ /**
15
+ * One action on a path: its id, its sentence as `label`, the input it was tried with, the
16
+ * fields it changed and the whole state after it.
17
+ */
18
+ export interface Step {
19
+ readonly action: string;
20
+ readonly label: string;
21
+ readonly input: readonly Named[];
22
+ readonly changes: readonly Change[];
23
+ readonly state: readonly Named[];
24
+ }
25
+ /** A start state and the actions that lead from it, as `earnest verify --json` prints a path. */
26
+ export interface Path {
27
+ readonly start: readonly Named[];
28
+ readonly steps: readonly Step[];
29
+ }
30
+ /**
31
+ * `unknown` means the rule was not seen broken, but the search stopped early, the rule could
32
+ * not be evaluated in a state it reached, or a state out of range or a fault in an action or an
33
+ * end cut the search short, so some state was not judged or not reached.
34
+ */
35
+ export type Verdict = "holds" | "broken" | "unknown";
36
+ /** One rule's result. `path` is the shortest path to a state that breaks it, or `null`. */
37
+ export interface RuleResult {
38
+ readonly id: string;
39
+ readonly says: string;
40
+ readonly verdict: Verdict;
41
+ readonly path: Path | null;
42
+ }
43
+ /**
44
+ * `stuck`: the condition of every action is false and so is every end. `out-of-range`: an action
45
+ * gave a field a value outside its declaration. `fault`: a rule, the condition or the change of an
46
+ * action, or an end can't be evaluated in the state. A state where a condition or an end can't be
47
+ * evaluated is not stuck: nothing says that it should stop there or go on.
48
+ */
49
+ export type FindingKind = "stuck" | "out-of-range" | "fault";
50
+ /** A problem that is not a broken rule, with the shortest path to the first state showing it. */
51
+ export interface Finding {
52
+ readonly kind: FindingKind;
53
+ readonly message: string;
54
+ readonly path: Path;
55
+ }
56
+ /**
57
+ * `unfinished` means the state limit stopped the search before anything was found wrong. Every
58
+ * state that is counted has its rules judged, also the ones the limit kept the search from
59
+ * going on from.
60
+ */
61
+ export type Status = "pass" | "fail" | "unfinished";
62
+ /**
63
+ * What `explore` found. `states` counts distinct states, out-of-range ones included. `findings`
64
+ * holds at most one of each kind, in the order stuck, out-of-range, fault. `reason` says why an
65
+ * unfinished search stopped, and is `null` otherwise.
66
+ */
67
+ export interface Exploration {
68
+ readonly status: Status;
69
+ readonly states: number;
70
+ readonly rules: readonly RuleResult[];
71
+ readonly findings: readonly Finding[];
72
+ readonly reason: string | null;
73
+ }
74
+ /** The exports of a model file, by name: `import * as cart from "./cart.model.ts"`. */
75
+ export type Exports = Readonly<Record<string, unknown>>;
76
+ /**
77
+ * `maxStates` stops the search before it holds more distinct states than this; the default is
78
+ * 5,000,000. `exports` is the model file's exports, which give each action, rule and end its
79
+ * id: the name it is exported under. One that is not among them has its sentence as its id.
80
+ */
81
+ export interface ExploreOptions {
82
+ readonly maxStates?: number;
83
+ readonly exports?: Exports;
84
+ }
85
+ /** The state limit `explore` uses when it is given none, the same as `earnest verify`. */
86
+ export declare const DEFAULT_MAX_STATES = 5000000;
87
+ /**
88
+ * Gives the function that names a part of a model: the name it is exported under in `exports`,
89
+ * or `fallback`, its sentence, when it is not exported there.
90
+ */
91
+ export declare const namer: (exports?: Exports) => ((part: object, fallback: string) => string);
92
+ /** What `attempt` gives: the result, or the sentence part saying why there is none. */
93
+ export type Attempt<T> = {
94
+ readonly fault: null;
95
+ readonly value: T;
96
+ } | {
97
+ readonly fault: string;
98
+ readonly value: null;
99
+ };
100
+ /**
101
+ * Runs part of a model and turns a fault into a value: reading a field of `null`, or using a
102
+ * value as something it is not. Any other error is a mistake in the model file and is thrown.
103
+ */
104
+ export declare const attempt: <T>(run: () => T) => Attempt<T>;
105
+ /**
106
+ * Applies an action and gives the next state, or the fault that stops it. Besides the faults of
107
+ * `attempt`, a next state that holds `NaN`, which `%` by zero gives, or a number too large for
108
+ * JavaScript to hold exactly is a fault.
109
+ */
110
+ export declare const nextState: (action: ActionRunner, state: Row, input: Row) => Attempt<Row>;
111
+ /** Every input an action is tried with, in the checker's order: the first input varies fastest. */
112
+ export declare const inputsOf: (action: ActionRunner) => readonly Row[];
113
+ /**
114
+ * Searches every state a model can reach, breadth first, and gives the count of distinct
115
+ * states, each rule's verdict with the shortest path to a state that breaks it, and the first
116
+ * stuck, out-of-range and fault findings. An end is asked only in a state where no action can
117
+ * happen. It visits states in the same order as
118
+ * `earnest verify`, so the two results can be compared. Pass the model file's exports as
119
+ * `exports` to get the same ids.
120
+ */
121
+ export declare const explore: (model: AnyModel, options?: ExploreOptions) => Exploration;