gdp-wired 0.25.0 → 0.26.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.
Files changed (50) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +1 -1
  3. package/dist/core/accel.js +336 -101
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.js +72 -18
  28. package/dist/core/machine.d.ts +6 -0
  29. package/dist/core/machine.js +35 -3
  30. package/dist/core/nonterm.d.ts +5 -1
  31. package/dist/core/nonterm.js +109 -41
  32. package/dist/core/q.d.ts +1 -0
  33. package/dist/core/q.js +2 -2
  34. package/dist/core/relation.d.ts +1 -0
  35. package/dist/core/relation.js +20 -36
  36. package/dist/core/solver.d.ts +12 -0
  37. package/dist/core/solver.js +76 -30
  38. package/dist/core/transfer.js +22 -13
  39. package/dist/core/translate.d.ts +1 -1
  40. package/dist/core/translate.js +22 -49
  41. package/dist/core/xstate.d.ts +6 -1
  42. package/dist/core/xstate.js +336 -55
  43. package/dist/kernel/cdcl.js +1 -2
  44. package/dist/kernel/prove.d.ts +6 -1
  45. package/dist/kernel/prove.js +96 -82
  46. package/dist/kernel/reader.d.ts +1 -0
  47. package/dist/kernel/reader.js +4 -3
  48. package/dist/kernel/simplex.d.ts +1 -1
  49. package/dist/kernel/simplex.js +13 -1
  50. package/package.json +3 -2
@@ -1,105 +1,302 @@
1
1
  // XState machines read from the code (core/extract.ts's `extractXState`): the machine as XState builds it (the file
2
2
  // loaded in the check's VM, with the real xstate), its states and transitions read by `fromXState` (core/xstate.ts), and
3
- // each guard and action `setup({guards, actions})` names read from its source by the extractor's executor, printed as
4
- // the bridge fromXState takes: a guard as its condition, an `assign` as the context it writes. The chart is then run
5
- // beside XState's own actor (`conforms`) on random events with payloads, every state and context compared, the code's
6
- // branches counted; any difference refuses it. Refused besides what fromXState refuses: v4 `cond` (the machines read are
7
- // v5's, and XState v5 ignores a `cond`, taking the transition unguarded), a machine made by a function, guards and actions with params, actions that
8
- // raise, send or spawn.
3
+ // each guard and action read from its source by the extractor's executor (named in `setup({guards, actions})`, in v4's
4
+ // options, or inline in the config), printed as the bridge fromXState takes: a guard as its condition, an `assign` as
5
+ // the context it writes. The chart is then run beside XState's own actor (`conforms`) on random events with payloads,
6
+ // every state and kept context field compared, the code's branches counted; any difference refuses it.
7
+ //
8
+ // - A machine made by a function (a factory): read with its arguments as the world gives them. An argument that is an
9
+ // object of functions (the effects a machine is given, its services) is outside: each answer a guard or an action
10
+ // reads of it is an input of the step (any value of its type, read once), a call that answers nothing an effect
11
+ // outside, a promise an actor's (invoked). The argument a config takes as its context makes the initial context: each
12
+ // field a param of the chart.
13
+ // - Invoked actors, timers and eventless transitions are fromXState's: an actor's done and error and a timer firing are
14
+ // events from outside; the actors are replaced by inert ones in the check (their answers are the events it sends).
15
+ // - The context: its fields of the subset's types (numbers, booleans, string unions, strings, each also as `T | null`
16
+ // or optional, a maybe); a field of another type (an object, a function) is left out where no guard or kept write
17
+ // reads it (it reaches only the actors and effects outside), else refused where it is read.
18
+ // - Actions: `assign`; `emit`, `sendParent`, v4's `sendUpdate`, `spawnChild` and `log` write no context (what they
19
+ // send goes outside: an emitted event to listeners, a spawned actor's answers come back as events from outside);
20
+ // `raise`, `sendTo`, `enqueueActions`, `forwardTo`, `cancel`, `stopChild` and v4's `choose` and `pure` are refused.
21
+ // - v4 machines (`createMachine(config, options)`): `cond`, `(context, event)` guards and actions, `services`. The check
22
+ // runs them on the XState v4 given (opts.xstate).
9
23
  import ts from 'typescript';
10
24
  import * as dsl from "./dsl.js";
11
- import { compileFunction } from "./machine.js";
25
+ import { compileFunction, seeded } from "./machine.js";
12
26
  import * as I from "./extract-ir.js";
13
- import { Exec, Refusal, program } from "./extract-read.js";
27
+ import { Exec, Refusal, memberName, normalize, program, shapeOf } from "./extract-read.js";
14
28
  import { kindOf, pb, pterm, sortsOf } from "./extract-print.js";
15
29
  import { sandbox } from "./extract-check.js";
16
- import { conforms, fromXState } from "./xstate.js";
30
+ import { conforms, eventsOf, fromXState } from "./xstate.js";
17
31
  const where = (n) => { const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`; };
18
32
  const refuse = (n, what) => { throw new Refusal(where(n), what); };
19
33
  const strip = (e) => (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) ? strip(e.expression) : e);
34
+ const isFn = (e) => ts.isArrowFunction(e) || ts.isFunctionExpression(e);
20
35
  export function extractXState(code, opts) {
21
36
  const file = opts.file ?? 'machine.ts', t0 = performance.now(), notes = [];
22
37
  try {
23
38
  const cwd = globalThis.process?.cwd?.() ?? '.';
24
- const { sf, checker } = program(code, `${cwd}/${file}`);
25
- // The machine's expression: setup({...}).createMachine({...}) or createMachine({...}), bound to the entry.
26
- let init;
27
- for (const st of sf.statements)
39
+ const at = `${cwd}/${file}`, root = at.slice(0, at.length - file.split('/').pop().length);
40
+ const extra = Object.fromEntries(Object.entries(opts.files ?? {}).map(([p, c]) => [normalize(`${root}${p}`), c]));
41
+ const { sf, checker } = program(code, at, extra);
42
+ // The entry: a machine (setup(...).createMachine(...), createMachine(...)) or a function that returns one.
43
+ let init, factory;
44
+ for (const st of sf.statements) {
28
45
  if (ts.isVariableStatement(st))
29
46
  for (const d of st.declarationList.declarations)
30
- if (ts.isIdentifier(d.name) && d.name.text === opts.entry)
31
- init = d.initializer;
32
- if (!init) {
33
- const fn = sf.statements.find((st) => ts.isFunctionDeclaration(st) && st.name?.text === opts.entry);
34
- if (fn)
35
- refuse(fn, `${opts.entry} makes the machine when called (a machine made by a function: export the machine itself)`);
36
- return { ok: false, refusals: [{ where: file, what: `no machine ${opts.entry} in the file` }], notes };
47
+ if (ts.isIdentifier(d.name) && d.name.text === opts.entry && d.initializer) {
48
+ const x = strip(d.initializer);
49
+ if (isFn(x))
50
+ factory = x;
51
+ else
52
+ init = d.initializer;
53
+ }
54
+ if (ts.isFunctionDeclaration(st) && st.name?.text === opts.entry)
55
+ factory = st;
37
56
  }
57
+ if (factory) {
58
+ const body = factory.body ?? refuse(factory, `${opts.entry} has no body`);
59
+ if (!ts.isBlock(body))
60
+ init = body;
61
+ else {
62
+ const stmts = body.statements.filter(s => !ts.isTypeAliasDeclaration(s) && !ts.isInterfaceDeclaration(s));
63
+ const ret = stmts.at(-1);
64
+ if (stmts.length !== 1 || !ret || !ts.isReturnStatement(ret) || !ret.expression)
65
+ refuse(body, `${opts.entry} does more than return the machine (a factory read here is one return)`);
66
+ init = ret.expression;
67
+ }
68
+ if (factory.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword))
69
+ refuse(factory, 'an async factory');
70
+ }
71
+ if (!init)
72
+ return { ok: false, refusals: [{ where: file, what: `no machine ${opts.entry} in the file` }], notes };
38
73
  const call = strip(init);
39
- if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression) && !ts.isIdentifier(call.expression))
40
- refuse(init, 'a machine not made by setup(...).createMachine or createMachine');
41
- const c = call;
42
- const callee = c.expression, made = ts.isPropertyAccessExpression(callee) ? callee.name.text : callee.text;
74
+ if (!ts.isCallExpression(call) || (!ts.isPropertyAccessExpression(call.expression) && !ts.isIdentifier(call.expression)))
75
+ return refuse(init, 'a machine not made by setup(...).createMachine or createMachine');
76
+ const callee = call.expression, made = ts.isPropertyAccessExpression(callee) ? callee.name.text : callee.text;
43
77
  if (made !== 'createMachine')
44
- refuse(c, 'a machine not made by createMachine');
78
+ refuse(call, 'a machine not made by createMachine');
45
79
  const setupArg = ts.isPropertyAccessExpression(callee) && ts.isCallExpression(callee.expression) && ts.isIdentifier(callee.expression.expression) && callee.expression.expression.text === 'setup' ? callee.expression.arguments[0] : undefined;
46
- const props = (o, name) => {
80
+ const config = call.arguments[0] && strip(call.arguments[0]), options = call.arguments[1] && strip(call.arguments[1]);
81
+ if (!config || !ts.isObjectLiteralExpression(config))
82
+ return refuse(call, 'a machine whose config is not an object literal');
83
+ if (call.arguments.length > 2)
84
+ refuse(call, 'createMachine with more than a config and its options');
85
+ const propRaw = (o, name) => {
47
86
  if (!o || !ts.isObjectLiteralExpression(o))
48
87
  return undefined;
49
- const p = o.properties.find(x => ts.isPropertyAssignment(x) && x.name.getText() === name);
50
- if (!p)
88
+ const p = o.properties.find(x => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && memberName(x.name) === name);
89
+ return p && (ts.isPropertyAssignment(p) ? p.initializer : ts.isShorthandPropertyAssignment(p) ? p.name : undefined);
90
+ };
91
+ const prop = (o, name) => { const x = propRaw(o, name); return x && strip(x); };
92
+ const objOf = (o, name) => {
93
+ const v = prop(o, name);
94
+ if (v === undefined)
51
95
  return undefined;
52
- const v = strip(p.initializer);
53
- return ts.isObjectLiteralExpression(v) ? v : refuse(v, `setup's ${name} as other than an object of them`);
96
+ return ts.isObjectLiteralExpression(v) ? v : refuse(v, `the ${name} given as other than an object of them`);
97
+ };
98
+ const args = [];
99
+ const ctxExpr = prop(config, 'context');
100
+ for (const param of factory?.parameters ?? []) {
101
+ if (param.dotDotDotToken)
102
+ refuse(param, 'a rest argument');
103
+ const parts = [];
104
+ const classify = (name, node, t) => {
105
+ if (ctxExpr && ts.isIdentifier(ctxExpr) && ctxExpr.text === name)
106
+ return { name, kind: 'context', node, type: t };
107
+ const nn = checker.getNonNullableType(t), props = checker.getPropertiesOfType(nn);
108
+ const fnTyped = (p) => checker.getSignaturesOfType(checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, node)), ts.SignatureKind.Call).length > 0;
109
+ if (props.length && props.every(fnTyped))
110
+ return { name, kind: 'outside', node, type: nn, fields: props.map(p => [p.getName(), checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, node))]) };
111
+ const bad = props.find(p => !fnTyped(p));
112
+ return refuse(node, `${name}: a factory argument that is neither the machine's context nor an object of functions (${props.length ? `${bad.getName()} is of type ${checker.typeToString(checker.getTypeOfSymbolAtLocation(bad, node))}` : `of type ${checker.typeToString(t)}`})`);
113
+ };
114
+ if (ts.isIdentifier(param.name))
115
+ parts.push(classify(param.name.text, param, checker.getTypeAtLocation(param)));
116
+ else if (ts.isObjectBindingPattern(param.name))
117
+ for (const el of param.name.elements) {
118
+ if (el.dotDotDotToken || el.propertyName || !ts.isIdentifier(el.name))
119
+ refuse(el, 'a destructured factory argument other than {a, b}');
120
+ parts.push(classify(el.name.text, el, checker.getTypeAtLocation(el)));
121
+ }
122
+ else
123
+ refuse(param, 'an array-destructured argument');
124
+ args.push({ param, parts });
125
+ }
126
+ const ctxArg = args.flatMap(a => a.parts).find(p => p.kind === 'context');
127
+ // The machine as XState builds it: the factory called with stubs (each answer read from the step's payload, a promise
128
+ // that never settles, nothing), and with the initial context drawn per run.
129
+ const box = sandbox(code, file, [opts.entry], { xstate: opts.xstate }, undefined, opts.files ?? {});
130
+ const answers = {};
131
+ const stubOf = (a) => {
132
+ const out = {};
133
+ for (const [f, t] of a.fields ?? []) {
134
+ const sig = checker.getSignaturesOfType(t, ts.SignatureKind.Call)[0], rt = checker.getReturnTypeOfSignature(sig);
135
+ const promise = rt.getSymbol()?.getName() === 'Promise', path = `${a.name}.${f}`;
136
+ out[f] = promise ? () => new Promise(() => { }) : () => answers[path];
137
+ }
138
+ return out;
54
139
  };
55
- // v4's `cond` (XState v5 ignores it): refused where it is, not dropped.
56
- const config = c.arguments[0];
57
- const visit = (n) => { if (ts.isPropertyAssignment(n) && n.name.getText() === 'cond')
58
- refuse(n, 'a v4 `cond` (XState v5 reads `guard` and takes this transition unguarded: name the guard in `guard`)'); ts.forEachChild(n, visit); };
59
- if (config)
60
- visit(config);
61
- // The machine as XState builds it, from the code loaded with the real xstate.
62
- const box = sandbox(code, file, [opts.entry], { xstate: opts.xstate });
63
- const machine = box.get(opts.entry);
64
- const ctx0 = machine.config.context;
65
- if (ctx0 !== undefined && (typeof ctx0 !== 'object' || ctx0 === null))
66
- refuse(config ?? c, 'a context computed by a function');
67
- // The context's variables and the payload's inputs, in one setup the guards and actions are read with.
68
- const s = { ours: f => f === sf, checker, sf, names: new Set(), vars: new Map(), maps: new Map(), lazySorts: new Map(), nowRole: 'input', hints: new WeakMap(), notes: new Set(), lazy: new Map() };
69
- const ex = new Exec(s), ctxVars = new Map(), init0 = {};
70
- for (const [k, v] of Object.entries(ctx0 ?? {})) {
71
- if (typeof v === 'number' && Number.isSafeInteger(v)) {
72
- const x = ex.newVar(k, { k: 'num' }, 'state');
73
- ctxVars.set(k, x);
74
- init0[x.name] = { s: 'num', e: I.num(v) };
140
+ const instance = (ctx) => {
141
+ if (!factory)
142
+ return box.get(opts.entry);
143
+ const values = args.map(({ param, parts }) => {
144
+ const one = (p) => (p.kind === 'outside' ? stubOf(p) : ctx);
145
+ return ts.isIdentifier(param.name) ? one(parts[0]) : Object.fromEntries(parts.map(p => [p.name, one(p)]));
146
+ });
147
+ const r = box.call(opts.entry, undefined, values);
148
+ if (!r.ok)
149
+ throw new Refusal(where(factory), `${opts.entry}(...) throws when called: ${r.error}`);
150
+ return r.value;
151
+ };
152
+ const version = (m) => (typeof m.getInitialSnapshot === 'function' ? 5 : typeof m.withConfig === 'function' ? 4 : refuse(call, 'createMachine made no machine of XState 4 or 5'));
153
+ // The context's fields, by their type (setup's types, v4's createMachine<Context>, the factory's argument) or else
154
+ // by the values the config starts them at.
155
+ const s = { ours: f => f === sf || f.fileName in extra, checker, sf, names: new Set(), vars: new Map(), maps: new Map(), lazySorts: new Map(), nowRole: 'input', hints: new WeakMap(), notes: new Set(), lazy: new Map(), xstate: { outside: new Map() } };
156
+ const ex = new Exec(s);
157
+ const ctxType = (() => {
158
+ if (ctxArg)
159
+ return ctxArg.type;
160
+ const types = propRaw(setupArg, 'types');
161
+ if (types) {
162
+ const t = checker.getTypeAtLocation(types), c = t.getProperty('context');
163
+ if (c)
164
+ return checker.getTypeOfSymbolAtLocation(c, types);
75
165
  }
76
- else if (typeof v === 'boolean') {
77
- const x = ex.newVar(k, { k: 'bool' }, 'state');
78
- ctxVars.set(k, x);
79
- init0[x.name] = { s: 'bool', e: v ? I.T : I.F };
166
+ const ta = call.typeArguments?.[0];
167
+ if (ta)
168
+ return checker.getTypeFromTypeNode(ta);
169
+ const schema = propRaw(prop(config, 'schema'), 'context');
170
+ if (schema)
171
+ return checker.getTypeAtLocation(schema);
172
+ return undefined;
173
+ })();
174
+ const m0 = instance(ctxArg ? {} : undefined), v = version(m0);
175
+ const raw0 = (m0.config?.context ?? (v === 4 ? m0.context : undefined));
176
+ if (!ctxArg && raw0 !== undefined && (typeof raw0 !== 'object' || raw0 === null))
177
+ refuse(ctxExpr ?? config, 'a context computed by a function');
178
+ const fields = [];
179
+ const sortOf = (sh) => (sh.k === 'num' || sh.k === 'bool' || sh.k === 'choice' || sh.k === 'str' ? sh : undefined);
180
+ const keys = ctxType ? checker.getPropertiesOfType(ctxType).map(p => p.getName()) : Object.keys((raw0 ?? {}));
181
+ for (const k of keys) {
182
+ if (s.names.has(k) || ['event', 'in', 'last'].includes(k))
183
+ refuse(config, `the context's ${k} shares a name with the chart's own`);
184
+ const value = raw0?.[k];
185
+ let sort, maybe, why;
186
+ if (ctxType) {
187
+ const p = ctxType.getProperty(k), t = checker.getTypeOfSymbolAtLocation(p, config);
188
+ const parts = t.isUnion() ? t.types : [t], missing = parts.filter(x => x.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined));
189
+ const rest = parts.filter(x => !(x.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
190
+ if (missing.some(x => x.flags & ts.TypeFlags.Null) && (missing.some(x => x.flags & ts.TypeFlags.Undefined) || p.flags & ts.SymbolFlags.Optional))
191
+ why = 'null or undefined (two ways missing)';
192
+ else {
193
+ maybe = missing.length ? (missing[0].flags & ts.TypeFlags.Null ? 'null' : 'undefined') : p.flags & ts.SymbolFlags.Optional ? 'undefined' : undefined;
194
+ try {
195
+ const rt = rest.length === 1 ? rest[0] : rest.every(x => x.flags & ts.TypeFlags.BooleanLiteral) ? checker.getBooleanType() : undefined;
196
+ const sh = rt ? shapeOf(rt, checker, config) : rest.every(x => x.flags & ts.TypeFlags.StringLiteral) ? { k: 'choice', values: rest.map(x => x.value) } : undefined;
197
+ sort = sh && sortOf(sh);
198
+ if (!sort)
199
+ why = `of type ${checker.typeToString(t)}`;
200
+ }
201
+ catch (e) {
202
+ if (!(e instanceof Refusal))
203
+ throw e;
204
+ why = e.what;
205
+ }
206
+ }
207
+ }
208
+ else {
209
+ if (typeof value === 'number' && Number.isSafeInteger(value))
210
+ sort = { k: 'num' };
211
+ else if (typeof value === 'boolean')
212
+ sort = { k: 'bool' };
213
+ else if (typeof value === 'string')
214
+ sort = { k: 'str' };
215
+ else
216
+ why = `starting at ${JSON.stringify(value)} with no type given`;
217
+ }
218
+ if (!sort) {
219
+ fields.push({ k, dropped: why });
220
+ continue;
221
+ }
222
+ if (maybe) {
223
+ const has = { name: `${k}.isSome`, sort: { k: 'bool' }, role: 'state' }, inner = { name: `${k}.inner`, sort, role: 'state' };
224
+ s.names.add(k);
225
+ s.vars.set(has.name, has);
226
+ s.vars.set(inner.name, inner);
227
+ fields.push({ k, maybe: { has, inner, null: maybe === 'null' } });
228
+ }
229
+ else {
230
+ const x = ex.newVar(k, sort, 'state');
231
+ if (x.name !== k)
232
+ refuse(config, `the context's ${k} shares a name with the builders'`);
233
+ fields.push({ k, var: x });
80
234
  }
81
- else
82
- refuse(config ?? c, `the context's ${k} (${JSON.stringify(v)}): numbers and booleans are the context the subset reads`);
83
- if (ctxVars.get(k).name !== k)
84
- refuse(config ?? c, `the context's ${k} shares a name with the builders'`);
85
235
  }
86
- // One function of ({context, event}) at a time, with the context as variables and the event's fields as inputs.
236
+ // The chart's events: those the machine reacts to, and those its type declares that no state takes (each a step
237
+ // that changes nothing, as XState ignores it). event.type in a guard or an action is which event it is.
238
+ const declared = (() => {
239
+ const et = (() => {
240
+ const types = propRaw(setupArg, 'types');
241
+ if (types) {
242
+ const t = checker.getTypeAtLocation(types), e = t.getProperty('events');
243
+ if (e)
244
+ return checker.getTypeOfSymbolAtLocation(e, types);
245
+ }
246
+ const ta = call.typeArguments?.[1];
247
+ if (ta)
248
+ return checker.getTypeFromTypeNode(ta);
249
+ const schema = propRaw(prop(config, 'schema'), 'events');
250
+ return schema && checker.getTypeAtLocation(schema);
251
+ })();
252
+ if (!et)
253
+ return [];
254
+ const out = [];
255
+ for (const m of et.isUnion() ? et.types : [et]) {
256
+ const tp = m.getProperty('type'), tt = tp && checker.getTypeOfSymbolAtLocation(tp, config);
257
+ for (const x of tt ? (tt.isUnion() ? tt.types : [tt]) : [])
258
+ if (x.flags & ts.TypeFlags.StringLiteral && !out.includes(x.value))
259
+ out.push(x.value);
260
+ }
261
+ return out;
262
+ })();
263
+ const handled = eventsOf(m0), events = [...handled, ...declared.filter(e => !handled.includes(e))];
264
+ if (events.length > handled.length)
265
+ notes.push(`events its type declares that no state takes, each a step that changes nothing: ${events.slice(handled.length).join(', ')}`);
266
+ const eventVar = { name: 'event', sort: { k: 'choice', values: events }, role: 'input' };
267
+ s.vars.set('event', eventVar);
268
+ s.names.add('event');
269
+ const ctxValue = () => ({ t: 'ref', id: 'xs.context' });
270
+ const ctxHeap = () => {
271
+ const heap = new Map();
272
+ heap.set('xs.context', { k: 'rec', origin: 'input', fields: new Map(fields.map(f => [f.k, f.var ? Exec.valueOf(f.var) : f.maybe ? { t: 'opt', has: I.bvar(f.maybe.has.name), v: Exec.valueOf(f.maybe.inner), ...(f.maybe.null ? { null: true } : {}) } : { t: 'opaque', what: `the context's ${f.k} is ${f.dropped}` }])) });
273
+ heap.set('xs.event', { k: 'rec', fields: new Map([['type', Exec.valueOf(eventVar)]]), origin: 'input', lazy: { prefix: '' } });
274
+ heap.set('xs.arg', { k: 'rec', fields: new Map([['context', ctxValue()], ['event', { t: 'ref', id: 'xs.event' }]]), origin: 'input' });
275
+ return heap;
276
+ };
277
+ // The factory's arguments, in scope: those of functions as outside, the context's start as unreadable (it is the
278
+ // start, not the context as it is).
279
+ const scope = new Map(args.flatMap(a => a.parts).filter(p => p.kind === 'outside').map(p => [p.name, { t: 'outside', path: p.name }]));
280
+ // One function of ({context, event}) (v4: (context, event)) at a time, with the context as variables and the event's
281
+ // fields as inputs.
87
282
  const run = (f, what) => {
88
283
  const fn = strip(f);
89
- if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn))
284
+ if (!isFn(fn))
90
285
  return refuse(f, `${what}: a reference to a function defined elsewhere`);
91
- if (fn.parameters.length > 1)
92
- refuse(fn, `${what} reads its params (named guards and actions with params are not in the subset)`);
93
- const heap = new Map();
94
- heap.set('xs.context', { k: 'rec', fields: new Map([...ctxVars].map(([k, x]) => [k, Exec.valueOf(x)])), origin: 'input' });
95
- heap.set('xs.event', { k: 'rec', fields: new Map(), origin: 'input', lazy: { prefix: '' } });
96
- heap.set('xs.arg', { k: 'rec', fields: new Map([['context', { t: 'ref', id: 'xs.context' }], ['event', { t: 'ref', id: 'xs.event' }]]), origin: 'input' });
97
- let p = { pc: [], locals: new Map(), heap: heap, wrote: [], nows: 0 };
98
- if (fn.parameters[0])
286
+ if (fn.parameters.length > (v === 4 ? 2 : 1))
287
+ refuse(fn, `${what} reads its params (guards and actions with params are not in the subset)`);
288
+ if (fn.getSourceFile() === sf)
289
+ (s.spans ??= []).push([fn.getStart(), fn.end]);
290
+ let p = { pc: [], locals: new Map(scope), heap: ctxHeap(), wrote: [], nows: 0 };
291
+ if (v === 5 && fn.parameters[0])
99
292
  p = ex.bind(fn.parameters[0].name, { t: 'ref', id: 'xs.arg' }, p);
293
+ if (v === 4 && fn.parameters[0])
294
+ p = ex.bind(fn.parameters[0].name, ctxValue(), p);
295
+ if (v === 4 && fn.parameters[1])
296
+ p = ex.bind(fn.parameters[1].name, { t: 'ref', id: 'xs.event' }, p);
100
297
  if (!ts.isBlock(fn.body)) {
101
- const [v, q] = ex.ev(fn.body, p);
102
- return { v, p: q };
298
+ const [x, q] = ex.ev(fn.body, p);
299
+ return { v: x, p: q };
103
300
  }
104
301
  const flow = ex.block(fn.body.statements, p);
105
302
  if (flow.live || flow.rets.length !== 1 || ex.throws.length)
@@ -107,103 +304,123 @@ export function extractXState(code, opts) {
107
304
  return { v: flow.rets[0][1], p: flow.rets[0][0] };
108
305
  };
109
306
  // A guard: a condition of ({context, event}), or stateIn.
110
- const guardOf = (v, name) => {
111
- v = strip(v);
112
- // stateIn({a: 'b'}) or stateIn('#id.a.b'): whether the machine is in that state.
113
- if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && v.expression.text === 'stateIn') {
114
- const a = v.arguments[0] && strip(v.arguments[0]);
307
+ const guardOf = (g, name) => {
308
+ g = strip(g);
309
+ if (ts.isCallExpression(g) && ts.isIdentifier(g.expression) && g.expression.text === 'stateIn') {
310
+ const a = g.arguments[0] && strip(g.arguments[0]);
115
311
  const path = (o) => (ts.isStringLiteral(o) ? o.text : ts.isObjectLiteralExpression(o) && o.properties.length === 1 && ts.isPropertyAssignment(o.properties[0]) ? `${o.properties[0].name.getText()}.${path(strip(o.properties[0].initializer))}` : refuse(o, 'a stateIn of other than one state'));
116
- return { in: a ? path(a).replace(/^#[^.]*\./, '') : refuse(v, 'stateIn()') };
312
+ return { in: a ? path(a).replace(/^#[^.]*\./, '') : refuse(g, 'stateIn()') };
117
313
  }
118
- const { v: out } = run(v, `the guard ${name}`);
314
+ const { v: out } = run(g, `the guard ${name}`);
119
315
  if (out.t !== 'bool')
120
- refuse(v, `the guard ${name} returns other than a boolean`);
316
+ refuse(g, `the guard ${name} returns other than a boolean`);
121
317
  return out.e;
122
318
  };
123
- // An action: the context an assign writes, null for one that writes none; refused for one that sends or spawns.
124
- const actionOf = (v, name) => {
125
- v = strip(v);
126
- if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && v.expression.text === 'assign') {
127
- const arg = v.arguments[0] ? strip(v.arguments[0]) : refuse(v, 'assign()');
128
- const writes = {};
129
- const put = (k, x, at) => {
130
- const cv = ctxVars.get(k) ?? refuse(at, `assigns ${k}, not in the context`);
131
- if (cv.sort.k === 'num' && x.t === 'num')
132
- writes[k] = { s: 'num', e: x.e };
133
- else if (cv.sort.k === 'bool' && x.t === 'bool')
134
- writes[k] = { s: 'bool', e: x.e };
135
- else
136
- refuse(at, `assigns ${k} a ${x.t}`);
137
- };
319
+ const failing = (f) => { try {
320
+ return f();
321
+ }
322
+ catch (e) {
323
+ if (e instanceof Refusal)
324
+ return { failed: `${e.where}: ${e.what}` };
325
+ throw e;
326
+ } };
327
+ const actionOf = (a, name) => {
328
+ a = strip(a);
329
+ const fname = ts.isCallExpression(a) && ts.isIdentifier(a.expression) ? a.expression.text : undefined;
330
+ if (fname === 'assign' && ts.isCallExpression(a)) {
331
+ const arg = a.arguments[0] ? strip(a.arguments[0]) : refuse(a, 'assign()');
332
+ const writes = [];
138
333
  if (ts.isObjectLiteralExpression(arg)) {
139
334
  for (const p of arg.properties) {
140
335
  if (!ts.isPropertyAssignment(p)) {
141
336
  refuse(p, 'an assign entry other than key: value');
142
337
  continue;
143
338
  }
144
- const k = p.name.getText(), init1 = strip(p.initializer);
145
- if (ts.isArrowFunction(init1) || ts.isFunctionExpression(init1))
146
- put(k, run(init1, `the action ${name}'s ${k}`).v, p);
147
- else {
148
- const [x] = ex.ev(init1, { pc: [], locals: new Map(), heap: new Map(), wrote: [], nows: 0 });
149
- put(k, x, p);
150
- }
339
+ const k = memberName(p.name), v1 = strip(p.initializer);
340
+ const x = failing(() => (isFn(v1) ? run(v1, `the action ${name}'s ${k}`).v : ex.ev(v1, { pc: [], locals: new Map(scope), heap: ctxHeap(), wrote: [], nows: 0 })[0]));
341
+ writes.push('failed' in x ? { k, failed: x.failed } : { k, x });
151
342
  }
152
343
  }
153
344
  else {
154
- const { v: out, p } = run(arg, `the action ${name}`);
155
- const o = out.t === 'ref' ? p.heap.get(out.id) : undefined;
156
- if (o?.k !== 'rec')
157
- refuse(arg, `the action ${name} returns other than an object of context fields`);
158
- for (const [k, x] of o.fields)
159
- put(k, x, arg);
345
+ const r = failing(() => run(arg, `the action ${name}`));
346
+ if ('failed' in r) {
347
+ // Unread as a whole: the fields it returns (an object literal's) each written by it, unread.
348
+ const body = isFn(arg) ? (ts.isBlock(arg.body) ? (arg.body.statements.at(-1) && ts.isReturnStatement(arg.body.statements.at(-1)) ? arg.body.statements.at(-1).expression : undefined) : arg.body) : undefined;
349
+ const lit = body && strip(body);
350
+ if (!lit || !ts.isObjectLiteralExpression(lit))
351
+ refuse(arg, r.failed);
352
+ for (const p of lit.properties)
353
+ if (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p))
354
+ writes.push({ k: memberName(p.name), failed: r.failed });
355
+ }
356
+ else {
357
+ const { v: out, p } = r;
358
+ const o = out.t === 'ref' ? p.heap.get(out.id) : undefined;
359
+ if (o?.k !== 'rec')
360
+ refuse(arg, `the action ${name} returns other than an object of context fields`);
361
+ for (const [k, x] of o.fields)
362
+ writes.push({ k, x });
363
+ }
160
364
  }
365
+ for (const w of writes)
366
+ if (!fields.some(f => f.k === w.k))
367
+ refuse(a, `the action ${name} assigns ${w.k}, not in the context`);
161
368
  return writes;
162
369
  }
163
- if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && ['raise', 'sendTo', 'sendParent', 'emit', 'enqueueActions', 'spawnChild', 'stopChild', 'forwardTo', 'cancel'].includes(v.expression.text))
164
- return refuse(v, `the action ${name}: ${v.expression.text} (an action that sends or spawns is not in the subset)`);
165
- if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && v.expression.text === 'log')
370
+ if (fname && ['raise', 'sendTo', 'enqueueActions', 'forwardTo', 'cancel', 'stopChild', 'choose', 'pure', 'send', 'respond', 'escalate'].includes(fname))
371
+ return refuse(a, `the action ${name}: ${fname} (an action that sends to the machine itself, or picks its actions as it runs, is not in the subset)`);
372
+ if (fname && ['emit', 'sendParent', 'sendUpdate', 'spawnChild', 'log'].includes(fname)) {
373
+ notes.push(`the action ${name}: ${fname} writes no context (${fname === 'spawnChild' ? 'the actor it starts answers by events from outside' : 'what it sends goes outside the machine'})`);
166
374
  return null;
375
+ }
167
376
  // A plain function: it writes no context (XState's actions write it through assign only); its effects are
168
377
  // outside the machine, left out.
169
- if (ts.isArrowFunction(v) || ts.isFunctionExpression(v)) {
378
+ if (isFn(a)) {
170
379
  notes.push(`the action ${name} writes no context (its effects outside the machine are left out)`);
171
380
  return null;
172
381
  }
173
- return refuse(v, `the action ${name}: an action the subset doesn't read`);
382
+ return refuse(a, `the action ${name}: an action the subset doesn't read`);
174
383
  };
175
- const guards = [];
176
- for (const g of props(setupArg, 'guards')?.properties ?? []) {
177
- if (!ts.isPropertyAssignment(g))
178
- refuse(g, 'a guard written other than name: function');
179
- guards.push([g.name.getText(), guardOf(g.initializer, g.name.getText())]);
180
- }
181
- const actions = [];
182
- for (const a of props(setupArg, 'actions')?.properties ?? []) {
183
- if (!ts.isPropertyAssignment(a))
184
- refuse(a, 'an action written other than name: action');
185
- actions.push([a.name.getText(), actionOf(a.initializer, a.name.getText())]);
186
- }
384
+ const named = (o) => (o?.properties ?? []).map(x => (ts.isPropertyAssignment(x) ? [memberName(x.name), x.initializer] : refuse(x, 'an entry written other than name: value')));
385
+ const guards = [], actions = [];
386
+ const where0 = v === 5 ? setupArg : options;
387
+ for (const [n, g] of named(objOf(where0, 'guards')))
388
+ guards.push([n, guardOf(g, n)]);
389
+ for (const [n, a] of named(objOf(where0, 'actions')))
390
+ actions.push([n, actionOf(a, n)]);
391
+ if (v === 4 && setupArg)
392
+ refuse(setupArg, 'setup() with XState v4');
393
+ const unread = (where0 && ts.isObjectLiteralExpression(where0) ? where0.properties : []).map(x => (x.name ? memberName(x.name) : '')).filter(k => !['guards', 'actions', 'delays', 'actors', 'services', 'types', 'schemas'].includes(k));
394
+ if (unread.length)
395
+ refuse(where0, `${unread.join(', ')} in ${v === 5 ? 'setup' : 'the options'}: not read`);
187
396
  // Inline guards and actions: the config's source and the machine's own config walked together, each function the
188
397
  // config holds named by its path in it (what fromXState's `inline` takes).
189
398
  const inlineGuards = [], inlineActions = [];
190
399
  const key = (k) => (/^[A-Za-z_$][\w$]*$/.test(k) ? `.${k}` : `[${JSON.stringify(k)}]`);
400
+ const machineName = factory ? 'machine' : opts.entry;
401
+ // A computed key ([RECONNECT_DELAY_MS]): its value, a number or a string the module's consts make.
402
+ const computed = (n) => {
403
+ const [x] = ex.ev(n.expression, { pc: [], locals: new Map(), heap: new Map(), wrote: [], nows: 0 });
404
+ return x.t === 'num' && x.e.op === 'const' ? String(x.e.v) : x.t === 'str' && x.e.op === 'slit' ? x.e.value : refuse(n, 'a computed key that is not a constant');
405
+ };
191
406
  // Each transition's actions with its guard (an action runs only where the guard holds: a write's sign is proven there).
192
407
  const uses = [];
193
- const keyOf = (e, path) => (ts.isStringLiteral(strip(e)) ? `named:${strip(e).text}` : path);
408
+ const keyOf = (e, path) => (ts.isStringLiteral(strip(e)) ? `named:${strip(e).text}` : ts.isObjectLiteralExpression(strip(e)) && prop(strip(e), 'type') && ts.isStringLiteral(prop(strip(e), 'type')) ? `named:${prop(strip(e), 'type').text}` : path);
194
409
  const walk = (ast, rt, path, role) => {
195
410
  ast = strip(ast);
196
411
  if (!role && ts.isObjectLiteralExpression(ast)) {
197
- const get = (k) => ast.properties.find((x) => ts.isPropertyAssignment(x) && x.name.getText() === k);
198
- const a = get('actions'), g = get('guard');
412
+ const a = prop(ast, 'actions'), g = prop(ast, 'guard') ?? prop(ast, 'cond');
199
413
  if (a) {
200
- const gk = g ? keyOf(g.initializer, `${path}.guard`) : undefined, av = strip(a.initializer);
201
- const aks = ts.isArrayLiteralExpression(av) ? av.elements.map((el, i) => keyOf(el, `${path}.actions[${i}]`)) : [keyOf(av, `${path}.actions`)];
414
+ const gk = g ? keyOf(g, `${path}.${prop(ast, 'guard') ? 'guard' : 'cond'}`) : undefined;
415
+ const aks = ts.isArrayLiteralExpression(a) ? a.elements.map((el, i) => keyOf(el, `${path}.actions[${i}]`)) : [keyOf(a, `${path}.actions`)];
202
416
  for (const ak of aks)
203
417
  uses.push({ action: ak, ...(gk ? { guard: gk } : {}) });
204
418
  }
205
419
  }
206
420
  if (role === 'actions' && !ts.isArrayLiteralExpression(ast)) {
421
+ // {type: name, params}: the named action (its params read by no write here, or refused where it is read).
422
+ if (ts.isObjectLiteralExpression(ast))
423
+ return;
207
424
  if (typeof rt === 'function' && !ts.isStringLiteral(ast))
208
425
  inlineActions.push([path, actionOf(ast, path)]);
209
426
  return;
@@ -215,95 +432,316 @@ export function extractXState(code, opts) {
215
432
  }
216
433
  if (ts.isObjectLiteralExpression(ast) && rt && typeof rt === 'object') {
217
434
  for (const p of ast.properties) {
435
+ if (ts.isShorthandPropertyAssignment(p) || ts.isSpreadAssignment(p) || ts.isMethodDeclaration(p))
436
+ refuse(p, 'a config entry written other than key: value');
218
437
  if (!ts.isPropertyAssignment(p))
219
438
  continue;
220
- const k = ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : p.name.getText(), sub = rt[k];
221
- if (sub === undefined || k === 'context' || k === 'types')
439
+ const k = ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) || ts.isNumericLiteral(p.name) ? p.name.text : ts.isComputedPropertyName(p.name) ? computed(p.name) : p.name.getText();
440
+ const sub = rt[k];
441
+ if (sub === undefined || k === 'context' || k === 'types' || k === 'schema' || k === 'tsTypes' || k === 'input' || k === 'src')
222
442
  continue;
223
- walk(p.initializer, sub, `${path}${key(k)}`, k === 'actions' || k === 'entry' || k === 'exit' ? 'actions' : k === 'guard' ? 'guard' : undefined);
443
+ walk(p.initializer, sub, `${path}${key(k)}`, k === 'actions' || k === 'entry' || k === 'exit' ? 'actions' : k === 'guard' || k === 'cond' ? 'guard' : undefined);
224
444
  }
225
445
  }
226
446
  else if (ts.isArrayLiteralExpression(ast) && Array.isArray(rt))
227
447
  ast.elements.forEach((el, i) => walk(el, rt[i], `${path}[${i}]`, role));
228
448
  };
229
- if (config)
230
- walk(config, machine.config, `${opts.entry}.config`);
449
+ walk(config, m0.config, `${machineName}.config`);
231
450
  if (inlineActions.length || inlineGuards.length)
232
451
  notes.push(`${inlineActions.length} inline actions and ${inlineGuards.length} inline guards, each given by its place in the config`);
233
- for (const [p, ws] of inlineActions)
234
- actions.push([`(inline)${p}`, ws]);
452
+ // A write of another kind than its field's, or unread: as a failure.
453
+ const fits = (f, x) => {
454
+ const target = f.var ?? f.maybe.inner, scalar = (y) => (target.sort.k === 'num' ? y.t === 'num' : target.sort.k === 'bool' ? y.t === 'bool' : y.t === 'choice' || y.t === 'str');
455
+ if (x.t === 'opaque')
456
+ return x.what;
457
+ if (!f.maybe)
458
+ return x.t === 'undef' || x.t === 'opt' ? `a value that may be missing, written to ${f.k}` : scalar(x) ? undefined : `a ${x.t} written to ${f.k}`;
459
+ if (x.t === 'undef')
460
+ return !!x.null === f.maybe.null ? undefined : `${x.null ? 'null' : 'undefined'} written to ${f.k}, where its type says ${f.maybe.null ? 'null' : 'undefined'}`;
461
+ if (x.t === 'opt')
462
+ return !!x.null !== f.maybe.null && !(x.has.op === 'const' && x.has.v) ? `a value missing as ${x.null ? 'null' : 'undefined'} written to ${f.k}` : scalar(x.v) ? undefined : `a ${x.v.t} written to ${f.k}`;
463
+ return scalar(x) ? undefined : `a ${x.t} written to ${f.k}`;
464
+ };
465
+ const everyWrite = [...actions, ...inlineActions].flatMap(([, ws]) => ws ?? []);
466
+ for (const w of everyWrite) {
467
+ const f = fields.find(x => x.k === w.k);
468
+ if (!f.dropped && w.x && !w.failed) {
469
+ const why = fits(f, w.x);
470
+ if (why) {
471
+ w.failed = why;
472
+ delete w.x;
473
+ }
474
+ }
475
+ }
476
+ // The names a term reads (a field by its own name, a maybe's by its parts').
477
+ const namesOf = (x, out = new Set()) => {
478
+ if ('op' in x) {
479
+ I.varsOf(x, out);
480
+ return out;
481
+ }
482
+ if (x.t === 'num' || x.t === 'bool' || x.t === 'choice' || x.t === 'str')
483
+ I.varsOf(x.e, out);
484
+ else if (x.t === 'opt') {
485
+ I.varsOf(x.has, out);
486
+ namesOf(x.v, out);
487
+ }
488
+ return out;
489
+ };
490
+ const reads = (k, ws) => {
491
+ const names = new Set();
492
+ for (const [, g] of [...guards, ...inlineGuards])
493
+ if (!('in' in g))
494
+ namesOf(g, names);
495
+ for (const w of ws)
496
+ if (w.x && w.k !== k)
497
+ namesOf(w.x, names);
498
+ return [...names].some(n => n === k || n.startsWith(`${k}.`));
499
+ };
500
+ for (const f of fields) {
501
+ const bad = everyWrite.find(w => w.k === f.k && w.failed);
502
+ if (!bad || f.dropped)
503
+ continue;
504
+ if (reads(f.k, everyWrite.filter(w => !fields.find(g => g.k === w.k).dropped)))
505
+ throw new Refusal(file, `the context's ${f.k} is read, and written from what the subset doesn't read (${bad.failed})`);
506
+ f.dropped = `written from what the subset doesn't read (${bad.failed})`;
507
+ }
508
+ // A field left out must be read by nothing kept: a guard, or a write to a field kept.
509
+ for (const f of fields)
510
+ if (f.dropped)
511
+ notes.push(`the context's ${f.k} (${f.dropped}) is left out: no guard reads it, nor any write the chart keeps (it reaches only the actors and effects outside)`);
512
+ const kept = (k) => !fields.find(f => f.k === k).dropped;
235
513
  // Which context numbers are naturals: as a rule's state, each written by every use of an action that writes it,
236
- // under its transition's guard (an action no transition names, or one named elsewhere, without one).
237
- const writesOf = new Map(actions.map(([n, ws]) => [n.startsWith('(inline)') ? n.slice(8) : `named:${n}`, ws]));
514
+ // under its transition's guard (an action no transition names, or an entry or exit action, without one).
515
+ const writesOf = new Map([...actions.map(([n, ws]) => [`named:${n}`, ws]), ...inlineActions]);
238
516
  const guardOfKey = new Map([...guards.map(([n, g]) => [`named:${n}`, g]), ...inlineGuards]);
239
517
  const used = new Set(uses.map(u => u.action));
240
518
  const all = [...uses, ...[...writesOf.keys()].filter(k => !used.has(k)).map(action => ({ action }))];
519
+ const num = (x) => (x.t === 'num' ? x.e : x.t === 'opt' && x.v.t === 'num' ? x.v.e : undefined);
241
520
  const writes = {};
242
- for (const [k, x] of ctxVars) {
243
- let w;
244
- all.forEach((u, i) => {
245
- const t = writesOf.get(u.action)?.[k], g = u.guard ? guardOfKey.get(u.guard) : undefined;
246
- if (!t || t.s !== 'num')
247
- return;
248
- const under = g && !('in' in g) ? I.nite(g, t.e, I.nvar(x.name)) : t.e;
249
- w = { s: 'num', e: I.nite(I.bvar(`$use${i}`), under, w && w.s === 'num' ? w.e : I.nvar(x.name)) };
250
- });
251
- if (w)
252
- writes[x.name] = w;
521
+ all.forEach((u, i) => {
522
+ for (const w of writesOf.get(u.action) ?? []) {
523
+ const f = fields.find(x => x.k === w.k), name = f.var?.name ?? f.maybe?.inner.name, t = w.x && !f.dropped ? num(w.x) : undefined;
524
+ if (!name || t === undefined)
525
+ continue;
526
+ const g = u.guard ? guardOfKey.get(u.guard) : undefined, under = g && !('in' in g) ? I.nite(g, t, I.nvar(name)) : t;
527
+ const prev = writes[name];
528
+ writes[name] = { s: 'num', e: I.nite(I.bvar(`$use${i}`), under, prev && prev.s === 'num' ? prev.e : I.nvar(name)) };
529
+ }
530
+ });
531
+ const init0 = {};
532
+ for (const f of fields) {
533
+ const x = f.var ?? f.maybe?.inner;
534
+ if (!x || x.sort.k !== 'num')
535
+ continue;
536
+ const val = raw0?.[f.k];
537
+ if (ctxArg)
538
+ continue;
539
+ init0[x.name] = { s: 'num', e: I.num(typeof val === 'number' ? val : 0) };
253
540
  }
254
541
  const vars = [...s.vars.values()];
255
- const model = { name: opts.entry, shape: 'reducer', file, entry: opts.entry, params: [], inputs: vars.filter(x => x.role === 'input'), state: vars.filter(x => x.role === 'state'), maps: [],
542
+ const params = ctxArg ? fields.filter(f => !f.dropped).flatMap(f => (f.var ? [{ ...f.var, name: `${f.k}0`, role: 'param' }] : [{ ...f.maybe.inner, name: `${f.k}0`, role: 'param' }])) : [];
543
+ const model = { name: opts.entry, shape: 'reducer', file, entry: opts.entry, params, inputs: vars.filter(x => x.role === 'input' && x.name !== 'event'), state: vars.filter(x => x.role === 'state'), maps: [],
256
544
  init: init0, writes, mapWrites: {}, outputs: [], refuse: I.F, pre: I.T, layout: { k: 'rec', fields: [] }, events: [], notes: [], hints: s.hints };
257
545
  const { sorts, notes: sn } = sortsOf(model);
258
546
  notes.push(...sn);
259
- const P = { sorts, m: model, hoisted: new Map(), choiceVars: new Map() };
547
+ if (ctxArg)
548
+ for (const f of fields) {
549
+ const x = f.var ?? f.maybe?.inner;
550
+ if (x?.sort.k === 'num') {
551
+ sorts.set(`${f.k}0`, sorts.get(x.name) === 'nat' ? 'nat' : 'int');
552
+ if (sorts.get(x.name) === 'int')
553
+ sorts.set(x.name, 'int');
554
+ }
555
+ }
556
+ const P = { sorts, m: model, hoisted: new Map(), choiceVars: new Map([[events.join('\u0000'), 'event']]) };
557
+ for (const f of fields)
558
+ if (f.var?.sort.k === 'choice')
559
+ P.choiceVars.set(f.var.sort.values.join('\u0000'), f.var.name);
260
560
  const cx = () => ({ m: model, sorts, atoms: [] });
261
561
  const envOf = (...xs) => { const vs = new Set(); for (const x of xs)
262
- I.varsOf(x, vs); return `{${[...vs].join(', ')}}`; };
562
+ I.varsOf(x, vs); const names = [...new Set([...vs].map(n => n.split('.')[0]))]; return names.length ? `{${names.join(', ')}}` : ''; };
563
+ // A field's kind and a value written to it, as the chart's builders take them.
564
+ const kindOfField = (f) => {
565
+ const x = f.var ?? f.maybe.inner, k = kindOf(x, sorts);
566
+ return f.maybe ? `maybe(${k})` : k;
567
+ };
568
+ const valueOfWrite = (f, x, at) => {
569
+ if (x.t === 'opaque')
570
+ throw new Refusal(file, `${at}: ${x.what}`);
571
+ const one = (y) => {
572
+ const target = f.var ?? f.maybe.inner;
573
+ const t = y.t === 'num' ? { s: 'num', e: y.e } : y.t === 'bool' ? { s: 'bool', e: y.e } : y.t === 'choice' ? { s: 'choice', e: y.e } : y.t === 'str' ? { s: 'str', e: y.e } : undefined;
574
+ if (!t || (target.sort.k === 'num') !== (t.s === 'num') || (target.sort.k === 'bool') !== (t.s === 'bool'))
575
+ throw new Refusal(file, `${at} writes ${f.k} a ${y.t}`);
576
+ if (target.sort.k === 'choice' && t.s === 'str') {
577
+ const e = ex.asChoice(y, target.sort.values, sf);
578
+ return { text: pterm({ s: 'choice', e }, P, cx(), target.name), terms: [e] };
579
+ }
580
+ return { text: pterm(t, P, cx(), target.name), terms: [t.e] };
581
+ };
582
+ if (!f.maybe) {
583
+ if (x.t === 'undef' || x.t === 'opt')
584
+ throw new Refusal(file, `${at} writes ${f.k} a value that may be missing`);
585
+ return one(x);
586
+ }
587
+ // A maybe is written whole: optional(there, value); missing, with any value of its kind (its own, as it is).
588
+ if (x.t === 'undef') {
589
+ if (!!x.null !== f.maybe.null)
590
+ throw new Refusal(file, `${at} writes ${f.k} ${x.null ? 'null' : 'undefined'}, where its type says ${f.maybe.null ? 'null' : 'undefined'}`);
591
+ return { text: `optional(no, ${f.k}.inner)`, terms: [I.nvar(`${f.k}.inner`)] };
592
+ }
593
+ if (x.t === 'opt') {
594
+ if (!!x.null !== f.maybe.null && !(x.has.op === 'const' && x.has.v))
595
+ throw new Refusal(file, `${at} writes ${f.k} a value missing as ${x.null ? 'null' : 'undefined'}, where its type says ${f.maybe.null ? 'null' : 'undefined'}`);
596
+ const inner = one(x.v);
597
+ return { text: `optional(${pb(x.has, P, cx())}, ${inner.text})`, terms: [x.has, ...inner.terms] };
598
+ }
599
+ const inner = one(x);
600
+ return { text: `optional(yes, ${inner.text})`, terms: inner.terms };
601
+ };
602
+ const actionSrc = (ws, name) => {
603
+ if (!ws)
604
+ return 'null';
605
+ const out = ws.filter(w => kept(w.k)).map(w => {
606
+ const f = fields.find(x => x.k === w.k);
607
+ if (!w.x)
608
+ throw new Refusal(file, `the action ${name} writes ${w.k}: ${w.failed}`);
609
+ // A write of a field to itself (a spread of the context): no write.
610
+ if (f.var && (w.x.t === 'num' || w.x.t === 'bool' || w.x.t === 'choice' || w.x.t === 'str') && w.x.e.op === (f.var.sort.k === 'str' ? 'svar' : 'var') && w.x.e.name === f.var.name)
611
+ return undefined;
612
+ return [w.k, valueOfWrite(f, w.x, `the action ${name}`)];
613
+ }).filter((x) => !!x);
614
+ return out.length ? `(${envOf(...out.flatMap(([, x]) => x.terms))}) => ({${out.map(([k, x]) => `${k}: ${x.text}`).join(', ')}})` : 'null';
615
+ };
616
+ const guardSrc = (g) => ('in' in g ? `env => env.in(${JSON.stringify(g.in)})` : `(${envOf(g)}) => ${pb(g, P, cx())}`);
617
+ // The bridge fromXState takes.
263
618
  const parts = [];
264
- if (model.inputs.length)
265
- parts.push(`inputs: {${model.inputs.map(x => `${x.name}: ${kindOf(x, sorts)}`).join(', ')}}`);
266
- const ints = model.state.filter(x => x.sort.k === 'num' && sorts.get(x.name) === 'int');
267
- if (ints.length)
268
- parts.push(`context: {${ints.map(x => `${x.name}: int.from(${init0[x.name].e.v})`).join(', ')}}`);
619
+ if (params.length)
620
+ parts.push(`params: {${params.map(x => `${x.name}: ${kindOfField(fields.find(f => `${f.k}0` === x.name))}`).join(', ')}}`);
621
+ const inputsAt = parts.length;
622
+ const ctxParts = fields.filter(f => !f.dropped).flatMap(f => {
623
+ const x = f.var ?? f.maybe.inner;
624
+ if (ctxArg)
625
+ return [`${f.k}: ${kindOfField(f)}.from(({${f.k}0}) => ${f.k}0)`];
626
+ const val = raw0?.[f.k];
627
+ const plainNat = !f.maybe && x.sort.k === 'num' && sorts.get(x.name) === 'nat';
628
+ if (plainNat || (!f.maybe && x.sort.k === 'bool'))
629
+ return [];
630
+ return [`${f.k}: ${kindOfField(f)}.from(${val === undefined ? 'null' : JSON.stringify(val)})`];
631
+ });
632
+ if (ctxParts.length)
633
+ parts.push(`context: {${ctxParts.join(', ')}}`);
634
+ const dropped = fields.filter(f => f.dropped).map(f => f.k);
635
+ if (dropped.length)
636
+ parts.push(`ignore: ${JSON.stringify(dropped)}`);
637
+ if (events.length > handled.length)
638
+ parts.push(`events: ${JSON.stringify(events)}`);
269
639
  if (guards.length)
270
- parts.push(`guards: {${guards.map(([n, g]) => `${JSON.stringify(n)}: ${'in' in g ? `env => env.in(${JSON.stringify(g.in)})` : `(${envOf(g)}) => ${pb(g, P, cx())}`}`).join(', ')}}`);
271
- const namedActions = actions.filter(([n]) => !n.startsWith('(inline)'));
272
- if (namedActions.length)
273
- parts.push(`actions: {${namedActions.map(([n, ws]) => `${JSON.stringify(n)}: ${ws ? `(${envOf(...Object.values(ws).map(t => t.e))}) => ({${Object.entries(ws).map(([k, t]) => `${k}: ${pterm(t, P, cx(), k)}`).join(', ')}})` : 'null'}`).join(', ')}}`);
274
- const named = actions.filter(([n]) => !n.startsWith('(inline)'));
275
- const guardSrc = (g) => ('in' in g ? `env => env.in(${JSON.stringify(g.in)})` : `(${envOf(g)}) => ${pb(g, P, cx())}`);
276
- const actionSrc = (ws) => (ws ? `(${envOf(...Object.values(ws).map(t => t.e))}) => ({${Object.entries(ws).map(([k, t]) => `${k}: ${pterm(t, P, cx(), k)}`).join(', ')}})` : 'null');
640
+ parts.push(`guards: {${guards.map(([n, g]) => `${JSON.stringify(n)}: ${guardSrc(g)}`).join(', ')}}`);
641
+ if (actions.length)
642
+ parts.push(`actions: {${actions.map(([n, ws]) => `${JSON.stringify(n)}: ${actionSrc(ws, n)}`).join(', ')}}`);
277
643
  if (inlineGuards.length || inlineActions.length)
278
- parts.push(`inline: {${[inlineGuards.length ? `guards: new Map([${inlineGuards.map(([p, g]) => `[${p}, ${guardSrc(g)}]`).join(', ')}])` : '', inlineActions.length ? `actions: new Map([${inlineActions.map(([p, ws]) => `[${p}, ${actionSrc(ws)}]`).join(', ')}])` : ''].filter(Boolean).join(', ')}}`);
644
+ parts.push(`inline: {${[inlineGuards.length ? `guards: new Map([${inlineGuards.map(([p, g]) => `[${p}, ${guardSrc(g)}]`).join(', ')}])` : '', inlineActions.length ? `actions: new Map([${inlineActions.map(([p, ws]) => `[${p}, ${actionSrc(ws, p)}]`).join(', ')}])` : ''].filter(Boolean).join(', ')}}`);
645
+ // The inputs: those the guards and the writes kept read.
646
+ const usedNames = new Set();
647
+ for (const [, g] of [...guards, ...inlineGuards])
648
+ if (!('in' in g))
649
+ namesOf(g, usedNames);
650
+ for (const w of everyWrite)
651
+ if (w.x && kept(w.k))
652
+ namesOf(w.x, usedNames);
653
+ const inputs = model.inputs.filter(x => usedNames.has(x.name));
654
+ if (inputs.length)
655
+ parts.splice(inputsAt, 0, `inputs: {${inputs.map(x => `${x.name}: ${kindOf(x, sorts)}`).join(', ')}}`);
279
656
  const bridge = `{${parts.join(', ')}}`;
657
+ const builders = ['bool', 'int', 'nat', 'oneOf', 'str', 'maybe', 'optional', 'when', 'all', 'any', 'not', 'min', 'max', 'lit', 'Int', 'yes', 'no', 'intern'].filter(n => new RegExp(`\\b${n}\\b`).test(bridge.replace(/'[^']*'|"[^"]*"/g, '')));
658
+ const makes = factory ? `${opts.entry}(${(factory.parameters).map(() => '{} as never').join(', ')})` : opts.entry;
280
659
  const source = [
281
- `// Extracted by gdp-wired/extract from ${file} (${opts.entry}, an XState machine): its guards and actions read from setup().`,
660
+ `// Extracted by gdp-wired/extract from ${file} (${opts.entry}, ${factory ? 'a function that makes an XState machine' : 'an XState machine'}): its guards and actions read from the code.`,
282
661
  `// Checked against XState's own actor; read again with extractXState() after the code changes.`,
283
662
  `import {fromXState} from 'gdp-wired/xstate'`,
284
- ...(/\b(int|nat|bool|oneOf|str)\b/.test(bridge) ? [`import {${['bool', 'int', 'nat', 'oneOf', 'str', 'when', 'all', 'any', 'not', 'min', 'max', 'lit', 'Int', 'yes', 'no'].filter(n => new RegExp(`\\b${n}\\b`).test(bridge.replace(/'[^']*'|"[^"]*"/g, ''))).join(', ')}} from 'gdp-wired'`] : []),
285
- `import {${opts.entry}} from './${file.replace(/\.(ts|js)$/, '')}'`,
663
+ ...(builders.length ? [`import {${builders.join(', ')}} from 'gdp-wired'`] : []),
664
+ `import {${opts.entry}} from './${file.replace(/\.(ts|js|tsx|jsx)$/, '')}'`,
286
665
  '',
287
- `export const ${opts.entry}Chart = fromXState(${opts.entry}, ${bridge})`,
666
+ ...(factory ? [`// The machine's states and transitions are the same whatever it is given (the functions are its inputs, the context its params).`, `const machine = ${makes}`] : []),
667
+ `export const ${opts.entry}Chart = fromXState(${machineName}, ${bridge})`,
288
668
  '',
289
669
  ].join('\n');
290
- const NAMES = ['nat', 'int', 'bool', 'oneOf', 'str', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'Int'];
291
- void named;
292
- const chart = compileFunction([...NAMES, 'fromXState', opts.entry], `return fromXState(${opts.entry}, ${bridge})`)(...NAMES.map(n => dsl[n]), fromXState, machine);
293
- // The check: XState's actor and the chart's compiled rule on the same events, payloads drawn for every input read.
294
- let x = opts.check?.seed ?? 3;
295
- const rand = (k) => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); };
296
- const draw = (v) => (v.sort.k === 'bool' ? rand(2) === 1 : v.sort.k === 'choice' ? v.sort.values[rand(v.sort.values.length)] : v.sort.k === 'str' ? ['a', 'b', ''][rand(3)] : sorts.get(v.name) === 'nat' ? rand(12) : rand(25) - 12);
297
- const runs = opts.check?.runs ?? 200, depth = opts.check?.depth ?? 16;
298
- let result;
670
+ const NAMES = ['nat', 'int', 'bool', 'oneOf', 'str', 'maybe', 'optional', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'Int', 'intern'];
671
+ // fromXState's own refusals (what a chart can't run the same way), with its reason.
672
+ let chart;
299
673
  try {
300
- result = conforms(chart, machine, opts.xstate.createActor, { runs, depth, seed: opts.check?.seed ?? 3, payload: () => Object.fromEntries(model.inputs.map(v => [v.name, draw(v)])) });
674
+ chart = compileFunction([...NAMES, 'fromXState', machineName], `return fromXState(${machineName}, ${bridge})`)(...NAMES.map(n => dsl[n]), fromXState, m0);
675
+ void chart.rule.machine;
301
676
  }
302
677
  catch (e) {
303
- result = { checked: 0, failure: `the chart's run throws: ${e.message}` };
678
+ if (e instanceof Refusal)
679
+ throw e;
680
+ return { ok: false, source, refusals: [{ where: file, what: `fromXState: ${e.message}` }], notes };
681
+ }
682
+ // The check: XState's actor (its actors inert: their answers are events the run sends) and the chart's compiled
683
+ // rule on the same events, payloads drawn for every input read; for a factory's context, a start drawn per batch.
684
+ const rand = seeded(opts.check?.seed ?? 3);
685
+ const draw = (x, name = x.name) => (x.sort.k === 'bool' ? rand(2) === 1 : x.sort.k === 'choice' ? x.sort.values[rand(x.sort.values.length)] : x.sort.k === 'str' ? ['a', 'b', ''][rand(3)] : sorts.get(name) === 'nat' ? rand(12) : rand(25) - 12);
686
+ const xs = opts.xstate;
687
+ const inert = (m) => (v === 5
688
+ ? m.provide({ actors: Object.fromEntries(Object.keys(m.implementations?.actors ?? {}).map(k => [k, xs.fromCallback(() => { })])) })
689
+ : m.withConfig({ services: Object.fromEntries(Object.keys(m.options?.services ?? {}).map(k => [k, () => () => { }])) }));
690
+ const createActor = (m) => (v === 5 ? xs.createActor(m) : xs.interpret(m));
691
+ const outside = s.xstate.outside;
692
+ // The event XState is sent: the payload's fields by the names the code reads them by; a field the code reads only
693
+ // into what the chart leaves out, an inert value (an object answering every read, a call, a conversion), so the
694
+ // code runs as it would with whatever the world sends there.
695
+ const anything = new Proxy(function inert() { }, { get: (_, k) => (k === Symbol.toPrimitive ? () => 0 : k === 'then' ? undefined : anything), apply: () => anything });
696
+ const toEvent = (type, payload) => {
697
+ const e = { type };
698
+ for (const [n, l] of s.lazy)
699
+ if (l.prefix === '' && l.field !== 'type')
700
+ e[l.field] = n in payload ? payload[n] : anything;
701
+ return e;
702
+ };
703
+ const runs = opts.check?.runs ?? 200, depth = opts.check?.depth ?? 16, batches = ctxArg ? Math.min(runs, 50) : 1;
704
+ const keptKeys = fields.filter(f => !f.dropped).map(f => f.k);
705
+ let result = { checked: 0 };
706
+ for (let b = 0; b < batches && !result.failure; b++) {
707
+ const ps = {}, ctx = {};
708
+ if (ctxArg)
709
+ for (const f of fields) {
710
+ if (f.dropped) {
711
+ ctx[f.k] = undefined;
712
+ continue;
713
+ }
714
+ const x = f.var ?? f.maybe.inner, val = f.maybe && rand(3) === 0 ? null : draw(x);
715
+ ps[`${f.k}0`] = val;
716
+ ctx[f.k] = val === null && f.maybe && !f.maybe.null ? undefined : val;
717
+ }
718
+ let machine;
719
+ try {
720
+ machine = inert(instance(ctxArg ? ctx : undefined));
721
+ }
722
+ catch (e) {
723
+ if (e instanceof Refusal)
724
+ throw e;
725
+ result = { checked: 0, failure: `the machine can't be made: ${e.message}` };
726
+ break;
727
+ }
728
+ try {
729
+ const r = conforms(chart, machine, createActor, { runs: Math.ceil(runs / batches), depth, seed: (opts.check?.seed ?? 3) + b, params: ps, context: keptKeys,
730
+ payload: () => Object.fromEntries(inputs.map(x => [x.name, draw(x)])),
731
+ beforeSend: (_, payload) => { for (const [n, o] of outside)
732
+ answers[o.path] = payload[n]; },
733
+ event: toEvent });
734
+ result = { checked: result.checked + r.checked, ...(r.failure ? { failure: `${ctxArg ? `starting at ${JSON.stringify(ps)}: ` : ''}${r.failure}` } : {}) };
735
+ }
736
+ catch (e) {
737
+ result = { checked: result.checked, failure: `the chart's run throws: ${e.message}` };
738
+ }
304
739
  }
305
- const coverage = { arms: box.arms.length, hit: box.counts.filter(n => n > 0).length, missed: box.arms.filter((_, i) => box.counts[i] === 0).map(a => `${a.label} at ${a.where}`) };
740
+ // The arms of the code the chart reads: its guards' and actions' (what the actors and effects outside run isn't).
741
+ const counted = box.arms.map((a, i) => [a, i]).filter(([a]) => (s.spans ?? []).some(([s0, e0]) => a.pos >= s0 && a.pos < e0));
742
+ const coverage = { arms: counted.length, hit: counted.filter(([, i]) => box.counts[i] > 0).length, missed: counted.filter(([, i]) => box.counts[i] === 0).map(([a]) => `${a.label} at ${a.where}`) };
306
743
  const evidence = { runs, events: result.checked, coverage, ms: Math.round(performance.now() - t0), ...(result.failure ? { mismatch: result.failure } : {}) };
744
+ notes.push(...s.notes);
307
745
  if (result.failure)
308
746
  return { ok: false, source, evidence, notes, refusals: [{ where: file, what: `the chart and XState differ: ${result.failure}` }] };
309
747
  return { ok: true, source, chart, evidence, notes, refusals: [] };
@@ -311,10 +749,6 @@ export function extractXState(code, opts) {
311
749
  catch (e) {
312
750
  if (e instanceof Refusal)
313
751
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
314
- // fromXState's own refusals (`always`, `after`, `invoke`, ...), with its reason.
315
- const msg = e.message;
316
- if (/has no chart counterpart|refus|inline|give its|a parallel state|several targets|wildcard|shallow history|both write|forbidden event|entry actions|exit actions|no state/.test(msg))
317
- return { ok: false, refusals: [{ where: file, what: `fromXState: ${msg}` }], notes };
318
752
  throw e;
319
753
  }
320
754
  }