gdp-wired 0.30.1 → 0.31.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,481 @@
1
+ // Effect (the `effect` package, 3.x and 4.x) as a front end (`gdp-wired/effect`): a service whose make effect creates
2
+ // Refs and returns an object of methods, read as core/extract.ts reads a factory's object of functions
3
+ // (core/extract-shapes.ts). Each Ref (Ref, SynchronizedRef, SubscriptionRef, 4.x's TxRef) is a field of the state, each
4
+ // method an event, its success value `<method>_result`, a failure (Effect.fail, Effect.die, `yield* new E(...)`) the
5
+ // step's refusal, Clock.currentTimeMillis an input, a Semaphore of 1's withPermits(1) a lock; each method is one step
6
+ // (true where calls don't interleave). What is read and refused, with the reasons, is in
7
+ // skills/gdp-wired/references/writing-rules.md ("Effect services") and research/effect/README.md.
8
+ //
9
+ // const x = extractEffect(code, {file: 'limiter.ts', entry: 'make', effect: await import('effect')})
10
+ //
11
+ // The check runs the code on the Effect given: the service made, and each request run, by Effect.runSyncExit with a
12
+ // Clock fixed at the request's time (4.x's TestClock.setTime yields to its scheduler, which runSync can't), every Ref
13
+ // read after it. `conforms(rule, service)` runs a rule written by hand beside a running service; `fromSchema(schema)` is
14
+ // a Schema's kind.
15
+ import ts from 'typescript';
16
+ import * as dsl from "./dsl.js";
17
+ import { interpret, seeded } from "./machine.js";
18
+ import { allowed } from "./watch.js";
19
+ import * as I from "./extract-ir.js";
20
+ import { Refusal, bare as strip, impure, memberName, placed, refuse, shapeOf, text } from "./extract-read.js";
21
+ import { readFactory } from "./extract-shapes.js";
22
+ import { fromModel } from "./extract.js";
23
+ import { check } from "./extract-check.js";
24
+ const REFS = new Set(['Ref', 'SynchronizedRef', 'SubscriptionRef', 'TxRef']), MAKES = ['make', 'makeUnsafe', 'unsafeMake'];
25
+ const STM = (api) => `${api}: STM (v3) is not read (a Ref, SynchronizedRef, or v4's TxRef is)`, MATCH = (x) => `${x}: a matcher (write the dispatch as a switch on _tag, or ifs)`;
26
+ // Where on a path the step has changed a Ref so far (a condition in the heap, so merges and helpers carry it).
27
+ const CHANGED = '$changed';
28
+ const changedOn = (p) => { const o = p.heap.get(CHANGED); return o?.k === 'alias' && o.to.t === 'bool' ? o.to.e : I.F; };
29
+ const changedOf = (v, c) => (v.t === 'phi' ? I.bite(v.c, changedOf(v.a, c), changedOf(v.b, c)) : v.t === 'ref' && c.t === 'ref' && v.id === c.id ? I.F
30
+ : (v.t === 'num' || v.t === 'bool' || v.t === 'str' || v.t === 'choice') && v.t === c.t && I.same(v.e, c.e) ? I.F : I.T);
31
+ // --- the reader -----------------------------------------------------------------------------------------------------
32
+ // The module of Effect a name is (Ref for `import * as Ref from 'effect/Ref'`, `import {Ref} from 'effect'`, or `E.Ref`
33
+ // of `import * as E from 'effect'`), with the member read of it: 'Ref.get'.
34
+ function apiOf(s, e) {
35
+ e = strip(e);
36
+ if (!ts.isPropertyAccessExpression(e))
37
+ return undefined;
38
+ const mod = (x) => {
39
+ x = strip(x);
40
+ if (ts.isPropertyAccessExpression(x))
41
+ return mod(x.expression) === '' ? memberName(x.name) : undefined;
42
+ let d = ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.declarations?.[0] : undefined;
43
+ const spec = (() => { let n = d; while (n && !ts.isImportDeclaration(n))
44
+ n = n.parent; return n && ts.isStringLiteral(n.moduleSpecifier) ? n.moduleSpecifier.text : undefined; })();
45
+ if (d && ts.isNamespaceImport(d))
46
+ return spec === 'effect' ? '' : spec?.match(/^effect\/(\w+)$/)?.[1];
47
+ return d && ts.isImportSpecifier(d) && spec === 'effect' ? (d = d.propertyName ?? d.name, d.text) : undefined;
48
+ };
49
+ const m = mod(e.expression);
50
+ return m ? `${m}.${memberName(e.name)}` : undefined;
51
+ }
52
+ const callOf = (s, e) => (e = strip(e), ts.isCallExpression(e) ? apiOf(s, e.expression) : undefined);
53
+ // A function a service writes: Effect.fn('name')(function* ...), Effect.fn(function* ...), Effect.fnUntraced(...), an
54
+ // arrow or a function.
55
+ function fnOf(s, e) {
56
+ e = strip(e);
57
+ if (ts.isArrowFunction(e) || ts.isFunctionExpression(e))
58
+ return e;
59
+ const head = ts.isCallExpression(e) ? (ts.isCallExpression(e.expression) ? callOf(s, e.expression) : apiOf(s, e.expression)) : undefined;
60
+ if (!ts.isCallExpression(e) || (head !== 'Effect.fn' && head !== 'Effect.fnUntraced'))
61
+ return undefined;
62
+ const g = e.arguments[0] && strip(e.arguments[0]);
63
+ if (!g || !ts.isFunctionExpression(g) || !g.asteriskToken)
64
+ return undefined;
65
+ if (e.arguments.length > 1)
66
+ refuse(e.arguments[1], `${head} with combinators after its body (their effects aren't read)`);
67
+ return g;
68
+ }
69
+ const genOf = (s, e) => {
70
+ if (callOf(s, e) !== 'Effect.gen')
71
+ return undefined;
72
+ const args = strip(e).arguments, g = args.at(-1);
73
+ if (args.length !== 1)
74
+ refuse(e, 'Effect.gen with a this (a generator of one function is read)');
75
+ return g && ts.isFunctionExpression(g) && g.asteriskToken ? g : refuse(e, 'Effect.gen of other than a function*');
76
+ };
77
+ // A type's type argument: Ref<A>'s A, Effect<A, E, R>'s A, Generator<Y, R, N>'s R.
78
+ const argOf = (s, t, i) => (t.aliasTypeArguments ?? (t.flags & ts.TypeFlags.Object ? s.checker.getTypeArguments(t) : undefined))?.[i];
79
+ const lastReturn = (b) => { const st = b && ts.isBlock(b) ? b.statements.at(-1) : undefined; return st && ts.isReturnStatement(st) ? st.expression : b && !ts.isBlock(b) ? b : undefined; };
80
+ // The service's make: the generator whose statements make the Refs and return the object, its params, and how the check
81
+ // makes the service (by calling the entry, or the effect captured where it is written).
82
+ function factoryOf(s, entry) {
83
+ const [name, member] = entry.split('.'), NO = 'no make effect (an Effect.gen, a function returning one, Effect.fn, or Layer.effect of one)';
84
+ let decl;
85
+ for (const st of s.sf.statements) {
86
+ if ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st)) && st.name?.text === name)
87
+ decl = st;
88
+ if (ts.isVariableStatement(st))
89
+ for (const d of st.declarationList.declarations)
90
+ if (ts.isIdentifier(d.name) && d.name.text === name)
91
+ decl = d;
92
+ }
93
+ if (!decl)
94
+ return refuse(s.sf.statements[0] ?? s.sf, `no ${name} in the file`);
95
+ // The make effect as written (a class's option or static member, a variable's value), through Layer.effect and names.
96
+ let e, at = decl;
97
+ if (ts.isClassDeclaration(decl)) {
98
+ const opts = member ? undefined : decl.heritageClauses?.[0]?.types[0]?.expression, o = opts && ts.isCallExpression(opts) && opts.arguments[1] ? strip(opts.arguments[1]) : undefined;
99
+ const prop = member ? decl.members.find(x => ts.isPropertyDeclaration(x) && memberName(x.name) === member) : o && ts.isObjectLiteralExpression(o) ? o.properties.find(p => ts.isPropertyAssignment(p) && ['make', 'effect', 'scoped'].includes(memberName(p.name))) : undefined;
100
+ e = prop?.initializer;
101
+ }
102
+ else if (ts.isVariableDeclaration(decl))
103
+ e = decl.initializer;
104
+ else if (ts.isFunctionDeclaration(decl))
105
+ return fromFunction(decl);
106
+ for (let i = 0; e && i < 8; i++) {
107
+ e = strip(e);
108
+ const api = callOf(s, e), d = ts.isIdentifier(e) ? s.checker.getSymbolAtLocation(e)?.valueDeclaration : undefined;
109
+ if ((api === 'Layer.effect' || api === 'Layer.scoped') && ts.isCallExpression(e))
110
+ e = e.arguments[1];
111
+ else if (d && ts.isVariableDeclaration(d) && d.getSourceFile() === s.sf) {
112
+ e = d.initializer;
113
+ at = d;
114
+ }
115
+ else
116
+ break;
117
+ }
118
+ if (!e)
119
+ return refuse(at, `${entry}: ${NO}`);
120
+ const gen = genOf(s, e), f = gen ? undefined : fnOf(s, e);
121
+ if (gen)
122
+ return made(gen, [], e);
123
+ if (f && ts.isFunctionExpression(f) && f.asteriskToken)
124
+ return made(f, f.parameters);
125
+ return f ? fromFunction(f) : refuse(e, `${entry}: ${text(e)} is ${NO.replace('no make effect', 'no make effect the reader reads')}`);
126
+ function fromFunction(f) {
127
+ const r = lastReturn(f.body), g = r && genOf(s, r);
128
+ if (!g || (ts.isBlock(f.body) && f.body.statements.length > 1))
129
+ return refuse(f, `${entry} returns no Effect.gen (a function whose body is the make effect is read)`);
130
+ return made(g, f.parameters);
131
+ }
132
+ // The make effect at `capture` (a value, not a function): captured where the code makes it, so the check runs it.
133
+ function made(fn, params, capture) {
134
+ let o = lastReturn(fn.body) && strip(lastReturn(fn.body));
135
+ if (o && ts.isCallExpression(o) && ts.isPropertyAccessExpression(o.expression) && memberName(o.expression.name) === 'of' && o.arguments.length === 1)
136
+ o = strip(o.arguments[0]);
137
+ if (!o || !ts.isObjectLiteralExpression(o))
138
+ return refuse(fn, `${entry}'s make effect returns no object of methods (\`return {...}\` or \`return Tag.of({...})\`)`);
139
+ const refs = new Map(), locks = new Set(), effects = new Map();
140
+ s.effect = hook(s, refs, locks, effects);
141
+ s.notes.add(`${entry} is an Effect service: its state is its Refs, each method an event, a failure the step's refusal; each method is one step, which holds where calls don't interleave (one at a time, or under a Semaphore of 1)`);
142
+ const R = 'require("gdp-wired:effect")', run = (f) => `{ const f = ${f}; return __R.run(typeof f === 'function' ? f(...args) : f, __now()) }`;
143
+ return {
144
+ fn, params, obj: o,
145
+ decl: d => {
146
+ const init = d.initializer && strip(d.initializer), id = d.name.text;
147
+ if (!init)
148
+ return undefined;
149
+ if (fnOf(s, init))
150
+ return 'helper';
151
+ const call = ts.isYieldExpression(init) && init.expression ? strip(init.expression) : init, api = callOf(s, call) ?? '', [m = '', op = ''] = api.split('.');
152
+ if (REFS.has(m) && MAKES.includes(op)) {
153
+ const start = call.arguments[0] ?? refuse(call, `${api}() with no start`);
154
+ const t = argOf(s, s.checker.getTypeAtLocation(d.name), 0) ?? refuse(d, `${text(d)}: no type for the Ref's value`);
155
+ refs.set(id, m);
156
+ return { shape: shapeOf(t, s.checker, d), init: start };
157
+ }
158
+ if (m === 'TRef' || m === 'STM')
159
+ return refuse(d, STM(api));
160
+ if (m === 'Semaphore' || /^Effect\.(unsafeM|m)akeSemaphore$/.test(api)) {
161
+ const n = call.arguments[0];
162
+ if (!n || !ts.isNumericLiteral(n) || n.text !== '1')
163
+ return refuse(d, `${text(d)}: a Semaphore of other than 1 permit (one of 1 is read as a lock)`);
164
+ locks.add(d);
165
+ return 'helper';
166
+ }
167
+ if (ts.isYieldExpression(init))
168
+ return refuse(d, `${id}: ${text(init)} run while the service is made (its value comes from outside the Refs read)`);
169
+ // An effect the service keeps (`const next = Ref.modify(...)`): made again, and run, where a method yields it.
170
+ if (s.checker.getTypeAtLocation(d.name).getSymbol()?.getName() === 'Effect') {
171
+ effects.set(d, init);
172
+ return 'helper';
173
+ }
174
+ return undefined;
175
+ },
176
+ fnOf: x => fnOf(s, x),
177
+ result: f => { const t = s.checker.getReturnTypeOfSignature(s.checker.getSignatureFromDeclaration(f)); return argOf(s, t, f.asteriskToken ? 1 : 0) ?? refuse(f, `${text(f)}: no type for its result (${s.checker.typeToString(t)})`); },
178
+ run: (_, v, at2, p) => (v.t === 'eff' ? v.run(p) : refuse(at2, `${text(at2)} returns a ${v.t} where a method returns an effect`)),
179
+ get: n => (refs.has(n) ? `${n}: ${R}.get(${JSON.stringify(refs.get(n))}, ${n})` : undefined),
180
+ set: n => (refs.has(n) ? `${R}.set(${JSON.stringify(refs.get(n))}, ${n}, __s.${n});` : undefined),
181
+ calls: `const __R = ${R}; __gdp.$new = function (...args) ${run(capture ? 'globalThis.__gdpMake' : `__gdp[${JSON.stringify(entry)}]`)}; __gdp.$method = function (name, args) ${run('this[name]')}; __gdp.$get = function () { return this.__gdpGet() }; __gdp.$at = function (fields, args) { const o = __gdp.$new(...args); o.__gdpSet(fields); return o }`,
182
+ ...(capture ? { extra: [[capture.getStart(), '(globalThis.__gdpMake = '], [capture.end, ')']] } : {}),
183
+ start: [[CHANGED, { k: 'alias', to: { t: 'bool', e: I.F } }]],
184
+ };
185
+ }
186
+ }
187
+ // Effect's expressions in a step: yield* runs an effect; Ref's, Effect's and Clock's calls make one (an `eff` value, run
188
+ // where it is yielded, so a helper or a branch may make it and another place run it).
189
+ const LOGS = new Set(['log', 'logTrace', 'logDebug', 'logInfo', 'logWarning', 'logError', 'logFatal', 'annotateCurrentSpan']), FAILS = new Set(['fail', 'failSync', 'die', 'dieMessage']);
190
+ const ANNOTATIONS = new Set(['Effect.withSpan', 'Effect.withLogSpan', 'Effect.annotateLogs', 'Effect.annotateSpans']);
191
+ // What a Ref operation answers: the value before, the value after, or nothing; and whether it takes a value or a function.
192
+ const ANSWERS = { get: 'old', set: 'none', getAndSet: 'old', setAndGet: 'new', update: 'none', updateAndGet: 'new', getAndUpdate: 'old', modify: 'none' };
193
+ function hook(s, refs, locks, effects) {
194
+ const eff = (run) => ({ t: 'eff', run }), undef = { t: 'undef' };
195
+ const lockOf = (x) => { const d = x && ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.valueDeclaration : undefined; return !!d && locks.has(d); };
196
+ // An error made of pure values: `new E({...})` of a class (an error class has no effects), or a plain value.
197
+ const effectful = (x) => (x = strip(x), ts.isNewExpression(x) && ts.isIdentifier(x.expression) ? (x.arguments ?? []).some(impure) : impure(x));
198
+ // A failure: the step refused where it is reached; where a Ref has been changed on the path, the Ref keeps it.
199
+ const fail = (ex, at, q) => {
200
+ if (!ex.known(q, I.not(changedOn(q))))
201
+ refuse(at, `fails after writing ${q.wrote.join(', ')}: a Ref keeps what was written (a rule's refusal leaves the state as it was)`);
202
+ ex.throws.push({ pc: q.pc });
203
+ return [undef, { ...q, pc: [...q.pc, I.F] }];
204
+ };
205
+ // A function's body run on a path, with the locals where it was made.
206
+ const body = (ex, f, at, locals, args = []) => eff(q => ex.inline({ decl: f }, args, at, q, locals));
207
+ return (ex, e, p) => {
208
+ if (ts.isYieldExpression(e)) {
209
+ if (!e.asteriskToken || !e.expression)
210
+ return refuse(e, 'yield without * (Effect.gen runs an effect with yield*)');
211
+ const x = strip(e.expression);
212
+ // A yielded error (Schema.TaggedError, Data.TaggedError): its failure.
213
+ if (ts.isNewExpression(x))
214
+ return effectful(x) ? refuse(x, `${text(x)}: an error made with effects`) : fail(ex, x, p);
215
+ const [v, q] = ex.ev(x, p);
216
+ return v.t === 'eff' ? v.run(q) : refuse(x, `yield* of ${text(x)}, not an effect the reader runs (a ${v.t})`);
217
+ }
218
+ if (ts.isIdentifier(e)) {
219
+ const d = s.checker.getSymbolAtLocation(e)?.valueDeclaration, init = d && effects.get(d);
220
+ if (!init)
221
+ return undefined;
222
+ const [v, q] = ex.ev(init, { ...p, locals: new Map() });
223
+ return [v, { ...q, locals: p.locals }];
224
+ }
225
+ if (ts.isPropertyAccessExpression(e)) {
226
+ const api = apiOf(s, e);
227
+ if (api === 'Effect.void' || api === 'Effect.unit')
228
+ return [eff(q => [undef, q]), p];
229
+ if (api === 'Clock.currentTimeMillis')
230
+ return [eff(q => ex.now(e, q)), p];
231
+ if (api?.startsWith('Clock.'))
232
+ return refuse(e, `${api} (Clock.currentTimeMillis is read, as an input)`);
233
+ if (api && /^(Random|DateTime|Crypto|Console|Config|FileSystem)\./.test(api) && ts.isYieldExpression(e.parent))
234
+ return refuse(e, `${api}: an answer from outside the Refs read (Clock.currentTimeMillis is the one read, as an input)`);
235
+ return undefined;
236
+ }
237
+ if (!ts.isCallExpression(e))
238
+ return undefined;
239
+ const callee = strip(e.expression), api = apiOf(s, callee), [m = '', op = ''] = api?.split('.') ?? [], one = e.arguments[0];
240
+ // A lock: sem.withPermit(effect), sem.withPermits(1)(effect), Semaphore.withPermits(sem, 1)(effect).
241
+ if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'withPermit' && lockOf(callee.expression) && e.arguments.length === 1)
242
+ return ex.ev(one, p);
243
+ if (ts.isCallExpression(callee) && e.arguments.length === 1) {
244
+ const inner = strip(callee.expression), n = callee.arguments.at(-1);
245
+ const sem = ts.isPropertyAccessExpression(inner) && memberName(inner.name) === 'withPermits' ? (lockOf(inner.expression) ? inner.expression : apiOf(s, inner) === 'Semaphore.withPermits' ? callee.arguments[0] : undefined) : undefined;
246
+ if (lockOf(sem))
247
+ return n && ts.isNumericLiteral(n) && n.text === '1' ? ex.ev(one, p) : refuse(e, 'withPermits of other than 1 (a Semaphore of 1 is a lock; more permits let calls interleave)');
248
+ }
249
+ // x.pipe(...): only annotations (a span, a log annotation) are read through.
250
+ if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'pipe' && !api) {
251
+ const head = strip(callee.expression);
252
+ if (callOf(s, head)?.startsWith('Match.'))
253
+ return refuse(head, MATCH(text(head)));
254
+ for (const a of e.arguments)
255
+ if (!ANNOTATIONS.has(callOf(s, a) ?? ''))
256
+ return refuse(a, `${text(a)} in a pipe (a combinator's effect isn't read: write the step in Effect.gen)`);
257
+ return ex.ev(callee.expression, p);
258
+ }
259
+ // A helper of the same files written with Effect.fn: its body run where it is yielded.
260
+ if (ts.isIdentifier(callee)) {
261
+ const d = s.checker.getSymbolAtLocation(callee)?.valueDeclaration;
262
+ const f = d && ts.isVariableDeclaration(d) && d.initializer && s.ours(d.getSourceFile()) ? fnOf(s, d.initializer) : undefined;
263
+ if (!f?.asteriskToken)
264
+ return undefined;
265
+ const [args, q] = ex.args(e.arguments, p);
266
+ return [body(ex, f, e, new Map(), args), q];
267
+ }
268
+ if (REFS.has(m))
269
+ return refOp(ex, e, m, op, p);
270
+ if (m === 'Effect') {
271
+ if (op === 'gen')
272
+ return [body(ex, genOf(s, e), e, p.locals), p];
273
+ if (op === 'succeed') {
274
+ const [v, q] = ex.ev(one ?? refuse(e, 'Effect.succeed()'), p);
275
+ return [eff(r => [v, r]), q];
276
+ }
277
+ if (op === 'sync')
278
+ return [body(ex, fnOf(s, one ?? refuse(e, 'Effect.sync()')) ?? refuse(e, 'Effect.sync of other than a function written here'), e, p.locals), p];
279
+ if (FAILS.has(op))
280
+ return e.arguments.some(effectful) ? refuse(e, `Effect.${op} of a value that has effects`) : [eff(q => fail(ex, e, q)), p];
281
+ if (LOGS.has(op)) {
282
+ if (e.arguments.some(impure))
283
+ return refuse(e, `Effect.${op} of values that have effects`);
284
+ s.notes.add('Effect.log and span annotations are left out (they write nothing the rule keeps)');
285
+ return [eff(q => [undef, q]), p];
286
+ }
287
+ return refuse(e, op === 'fn' || op === 'fnUntraced' ? `Effect.${op} as a value inside a step (a method or a helper of the service is read)` : `Effect.${op} (Effect.gen, Effect.fn bodies, succeed, sync, fail, die, void and log are read; the effect of ${op} isn't)`);
288
+ }
289
+ if (m === 'Match')
290
+ return refuse(e, MATCH(api));
291
+ if (m === 'STM' || m === 'TRef')
292
+ return refuse(e, STM(api));
293
+ if (m === 'Semaphore')
294
+ return refuse(e, `${api} (a Semaphore of 1 made by the service, as a lock, is read)`);
295
+ return undefined;
296
+ };
297
+ // Ref.op(ref, ...): the ref a Ref the service made (by its name), its value the state's field.
298
+ function refOp(ex, e, m, op, p) {
299
+ const r = e.arguments[0] && strip(e.arguments[0]), base = op.replace(/Effect$/, ''), answer = ANSWERS[base], f = e.arguments[1];
300
+ if (MAKES.includes(op))
301
+ return refuse(e, `${m}.${op} in a step (each call would make a new Ref: the service's Refs are made by its make effect)`);
302
+ if (!r)
303
+ return refuse(e, `${m}.${op} with no Ref`);
304
+ if (!answer)
305
+ return refuse(e, `${m}.${op} (get, set, update, modify, updateAndGet, getAndUpdate, getAndSet and setAndGet are read)`);
306
+ const name = ts.isIdentifier(r) && refs.has(r.text) && s.closure?.has(s.checker.getSymbolAtLocation(r)?.valueDeclaration) ? r.text : refuse(r, `${text(r)}: a Ref other than one the service's make effect makes (a Ref held in a value, or given to it)`);
307
+ const self = { t: 'ref', id: 'this' };
308
+ // A Ref set to a value: where it is the one it held, nothing changes.
309
+ const put = (v, q) => {
310
+ const changed = changedOf(v, ex.field(self, name, r, q)[0]);
311
+ if (changed.op === 'const' && !changed.v)
312
+ return q;
313
+ const [w, q2] = ex.whole(v, q, r), q3 = ex.writeField(self, name, w, q2, r);
314
+ return { ...q3, heap: new Map(q3.heap).set(CHANGED, { k: 'alias', to: { t: 'bool', e: I.or(changedOn(q3), changed) } }) };
315
+ };
316
+ // The new value: the one given (set), or the function's of the old (update, modify: a function written here).
317
+ const locals = p.locals, fn = base === 'get' || /[sS]et/.test(base) ? undefined : f && (fnOf(s, f) ?? (ts.isIdentifier(f) ? (d => (d && ts.isFunctionDeclaration(d) && s.ours(d.getSourceFile()) ? d : undefined))(s.checker.getSymbolAtLocation(f)?.valueDeclaration) : undefined));
318
+ if (base !== 'get' && !/[sS]et/.test(base) && (!fn || fn.asteriskToken))
319
+ return f ? refuse(f, `${m}.${op} of other than a function written here`) : refuse(e, `${m}.${op} with no function`);
320
+ const [given, q0] = /[sS]et/.test(base) ? ex.ev(f ?? refuse(e, `${m}.${op} with no value`), p) : [undefined, p];
321
+ return [eff(q => {
322
+ const [c, q1] = ex.field(self, name, r, q);
323
+ if (base === 'get')
324
+ return [c, q1];
325
+ let [v, q2] = given ? [given, q1] : ex.inline({ decl: fn }, [c], f, q1, ts.isIdentifier(f) ? new Map() : locals);
326
+ if (/Effect$/.test(op))
327
+ [v, q2] = v.t === 'eff' ? v.run(q2) : refuse(f, `${m}.${op}'s function returns other than an effect`);
328
+ if (base === 'modify') {
329
+ if (v.t !== 'tuple' || v.xs.length !== 2)
330
+ return refuse(f, `${m}.${op}'s function returns other than [result, value]`);
331
+ return [v.xs[0], put(v.xs[1], q2)];
332
+ }
333
+ return [answer === 'old' ? c : answer === 'new' ? v : undef, put(v, q2)];
334
+ }), q0];
335
+ }
336
+ }
337
+ export function runner(E) {
338
+ const { Effect, Exit, Cause, Clock } = E, v4 = 'TxRef' in E;
339
+ if (!Effect?.runSyncExit)
340
+ throw new Error('effect: give the `effect` package itself (import * as effect from \'effect\')');
341
+ let now = 0;
342
+ // A Clock at `now`: 4.x names its unsafe reads currentTime<X>Unsafe, 3.x unsafeCurrentTime<X>.
343
+ const unsafe = (x) => (v4 ? `currentTime${x}Unsafe` : `unsafeCurrentTime${x}`), ns = () => BigInt(now) * 1000000n;
344
+ const clock = Object.create(Effect.runSync(v4 ? Effect.clockWith((c) => Effect.succeed(c)) : Effect.clock), { [unsafe('Millis')]: { value: () => now }, currentTimeMillis: { value: Effect.sync(() => now) }, [unsafe('Nanos')]: { value: ns }, currentTimeNanos: { value: Effect.sync(ns) } });
345
+ const exit = (eff, t) => {
346
+ if (!Effect.isEffect(eff))
347
+ return { ok: false, error: `not an effect: ${String(eff).slice(0, 60)}` };
348
+ now = t;
349
+ const x = Effect.runSyncExit(v4 ? Effect.provideService(eff, Clock.Clock, clock) : Effect.withClock(eff, clock));
350
+ return Exit.isSuccess(x) ? { ok: true, value: x.value } : { ok: false, error: String(Cause.pretty(x.cause)).split('\n')[0] };
351
+ };
352
+ const run = (eff, t = now) => { const x = exit(eff, t); if (!x.ok)
353
+ throw new Error(x.error); return x.value; };
354
+ return { run, exit, get: (mod, ref) => run(E[mod].get(ref)), set: (mod, ref, v) => run(E[mod].set(ref, v)) };
355
+ }
356
+ export function extractEffect(code, opts) {
357
+ const file = opts.file ?? 'input.ts', E = opts.effect;
358
+ let m;
359
+ try {
360
+ m = readFactory(code, placed(file), opts, s => factoryOf(s, opts.entry));
361
+ m.file = file;
362
+ }
363
+ catch (e) {
364
+ if (e instanceof Refusal)
365
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
366
+ throw e;
367
+ }
368
+ // The modules the code imports, by specifier (effect, effect/<Module>), and the check's runner.
369
+ const model = m, modules = { effect: E, ...Object.fromEntries(Object.entries(E).map(([k, x]) => [`effect/${k}`, x])), 'gdp-wired:effect': runner(E), ...opts.modules };
370
+ return fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) }));
371
+ }
372
+ export function conforms(r, svc, opts) {
373
+ const R = runner(svc.effect), rand = seeded(opts.seed ?? 1), g = r.compiled(), interp = interpret(r.machine), isEffect = (x) => svc.effect.Effect.isEffect(x);
374
+ let checked = 0;
375
+ for (let run = 0; run < (opts.runs ?? 100); run++) {
376
+ const params = opts.params?.(rand) ?? {}, ps = r.encodeParams(params), m0 = svc.make(params), made = isEffect(m0) ? R.exit(m0, 0) : { ok: true, value: m0 };
377
+ if (!made.ok)
378
+ return { checked, failure: `the service with ${JSON.stringify(params)} fails to be made: ${made.error}` };
379
+ const self = made.value, sent = [];
380
+ let st = g.init(ps);
381
+ for (let d = 0; d < (opts.depth ?? 12); d++) {
382
+ const input = opts.draw(rand), now = svc.now ? Number(input[svc.now]) : 0;
383
+ let enc, ok;
384
+ try {
385
+ enc = r.encodeInput(input, params);
386
+ }
387
+ catch (e) {
388
+ return { checked, failure: `${JSON.stringify(input)} is outside the rule's inputs: ${e.message}` };
389
+ }
390
+ sent.push(JSON.stringify(input));
391
+ const at = `${Object.keys(params).length ? `with ${JSON.stringify(params)}, ` : ''}after ${sent.join(', ')}`;
392
+ try {
393
+ ok = allowed(r.machine, interp, ps, st, enc) && (g.step(ps, g.fork(st), enc), true);
394
+ }
395
+ catch {
396
+ ok = false;
397
+ }
398
+ const x = R.exit(svc.request(self, input, params), now);
399
+ if (ok !== x.ok)
400
+ return { checked, failure: `${at}: the ${x.ok ? 'service takes the request' : `service fails (${x.error})`}, the rule ${ok ? 'takes it' : 'refuses it'}` };
401
+ if (!ok)
402
+ continue;
403
+ st = g.step(ps, st, enc);
404
+ if (svc.observe) {
405
+ let o = svc.observe(self, x.value, input);
406
+ if (isEffect(o))
407
+ o = R.run(o, now);
408
+ const mine = r.decode(st), want = svc.view ? svc.view(mine, input) : mine;
409
+ for (const [k, v] of Object.entries(o))
410
+ if (JSON.stringify(v) !== JSON.stringify(want[k]))
411
+ return { checked, failure: `${at}: the service's ${k} is ${JSON.stringify(v)}, the rule's ${JSON.stringify(want[k])}` };
412
+ }
413
+ checked++;
414
+ }
415
+ }
416
+ return { checked };
417
+ }
418
+ // A Schema's kind (its type side, 3.x or 4.x): a struct a record, string literals a choice, a tagged union of structs a
419
+ // variant on `_tag`, integers int (nat where at least 0), Boolean, String, `X | null` and optional fields a maybe, a
420
+ // Schema.Class its fields. A number that may be fractional, and any other Schema, is refused with the path to it.
421
+ // 3.x's AST nodes by 4.x's names:
422
+ const TAGS = { NumberKeyword: 'Number', BooleanKeyword: 'Boolean', StringKeyword: 'String', TypeLiteral: 'Objects', UndefinedKeyword: 'Undefined' };
423
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
424
+ export function fromSchema(schema) {
425
+ const fail = (path, what) => { throw new Error(`fromSchema: ${path || 'the schema'} is ${what}`); };
426
+ const tagOf = (a) => TAGS[a?._tag] ?? a?._tag;
427
+ const ann = (a, id) => { const k = Object.getOwnPropertySymbols(a.annotations ?? {}).find(x => x.description === id); return k ? a.annotations[k] : undefined; };
428
+ const base = (a) => (a._tag === 'Refinement' ? base(a.from) : a);
429
+ // An integer: 4.x's checks on Number (isInt, a minimum), 3.x's Refinements down to NumberKeyword (Int, a JSON Schema minimum).
430
+ const num = (a, path) => {
431
+ let int = false, min = -Infinity;
432
+ for (let x = a; x; x = x._tag === 'Refinement' ? x.from : undefined) {
433
+ const js = ann(x, 'effect/annotation/JSONSchema');
434
+ for (const c of [...(x.checks ?? []).map((c) => c.annotations ?? {}).map((an) => ({ int: an.representation?.id === 'effect/schema/isInt' || an.arbitraryConstraint?.number?.isInteger, min: an.arbitraryConstraint?.minimum })),
435
+ { int: js?.type === 'integer' || ann(x, 'effect/annotation/SchemaId')?.description === 'effect/SchemaId/Int', min: js?.minimum }]) {
436
+ int ||= !!c.int;
437
+ if (typeof c.min === 'number')
438
+ min = Math.max(min, c.min);
439
+ }
440
+ }
441
+ return int ? (min >= 0 ? dsl.nat : dsl.int) : fail(path, 'a number that may be fractional (an integer schema, Schema.Int, is read)');
442
+ };
443
+ const props = (a) => a.propertySignatures;
444
+ const go = (a, path) => {
445
+ const tag = tagOf(a);
446
+ if (tag === 'Transformation')
447
+ return go(a.to, path);
448
+ if (tag === 'Number' || (tag === 'Refinement' && tagOf(base(a)) === 'Number'))
449
+ return num(a, path);
450
+ if (tag === 'Refinement')
451
+ return go(a.from, path);
452
+ if (tag === 'Boolean')
453
+ return dsl.bool;
454
+ if (tag === 'String')
455
+ return dsl.str();
456
+ if (tag === 'Literal')
457
+ return typeof a.literal === 'string' ? dsl.oneOf(a.literal) : fail(path, `the literal ${String(a.literal)} (string literals are read)`);
458
+ if (tag === 'Objects') {
459
+ if (a.indexSignatures?.length)
460
+ fail(path, 'a record with an index signature');
461
+ return dsl.record(fieldsOf(a, path, false));
462
+ }
463
+ if (tag !== 'Union')
464
+ return fail(path, `a ${a?._tag} schema (structs, literals, tagged unions, integers, booleans and strings are read)`);
465
+ const types = a.types, missing = types.filter(t => ['Null', 'Undefined'].includes(tagOf(t)) || (t._tag === 'Literal' && t.literal === null)), rest = types.filter(t => !missing.includes(t));
466
+ const caseOf = (t) => { const p = tagOf(t) === 'Objects' ? props(t).find(x => x.name === '_tag') : undefined; return p?.type._tag === 'Literal' && typeof p.type.literal === 'string' ? p.type.literal : undefined; };
467
+ if (missing.length && rest.length === 1)
468
+ return dsl.maybe(go(rest[0], path));
469
+ if (rest.every(t => t._tag === 'Literal' && typeof t.literal === 'string'))
470
+ return dsl.oneOf(...rest.map(t => t.literal));
471
+ if (!missing.length && rest.every(caseOf))
472
+ return dsl.variant(Object.fromEntries(rest.map(t => [caseOf(t), fieldsOf(t, path, true)])), { tag: '_tag' });
473
+ return fail(path, 'a union other than of string literals, of structs tagged by _tag, or with null');
474
+ };
475
+ const fieldsOf = (a, path, tagged) => Object.fromEntries(props(a).filter(p => !(tagged && p.name === '_tag')).map(p => {
476
+ const k = go(p.type, `${path ? `${path}.` : ''}${String(p.name)}`);
477
+ return [String(p.name), (p.isOptional || p.context?.isOptional) && !('of' in k) ? dsl.maybe(k) : k];
478
+ }));
479
+ const ast = schema.ast;
480
+ return schema.fields && tagOf(ast) !== 'Objects' ? dsl.record(Object.fromEntries(Object.entries(schema.fields).map(([f, x]) => [f, go(x.ast, f)]))) : go(ast, '');
481
+ }
@@ -172,7 +172,7 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
172
172
  }
173
173
  case 'map': {
174
174
  const d = m.maps.find(x => x.name === layout.name), cells = {};
175
- const entries = isMap(v) ? [...v.entries()] : typeof v === 'object' && v !== null ? Object.entries(v) : (() => { throw new Error(`${path} is not a map`); })();
175
+ const entries = isMap(v) ? [...v.entries()] : Object.prototype.toString.call(v) === '[object Set]' ? [...v].map(k => [k, {}]) : typeof v === 'object' && v !== null ? Object.entries(v) : (() => { throw new Error(`${path} is not a map`); })();
176
176
  for (const [k, x] of entries) {
177
177
  if (d.key === 'num' && !(typeof k === 'number' || (typeof k === 'string' && /^\d+$/.test(k))))
178
178
  throw new Error(`${path} has a key ${String(k)} that isn't a natural`);
@@ -261,7 +261,7 @@ function valueOf(s, layout, m, consts, ctx) {
261
261
  }
262
262
  };
263
263
  ctx.__in = JSON.stringify(tree(layout));
264
- return vmOf().runInContext('JSON.parse(__in, (k, v) => v && typeof v === "object" && v.$map ? (v.$map === "Map" ? new Map(v.entries) : Object.fromEntries(v.entries)) : v && typeof v === "object" && "$date" in v ? new Date(v.$date) : v)', ctx);
264
+ return vmOf().runInContext('JSON.parse(__in, (k, v) => v && typeof v === "object" && v.$map ? (v.$map === "Map" ? new Map(v.entries) : v.$map === "Set" ? new Set(v.entries.map(e => e[0])) : Object.fromEntries(v.entries)) : v && typeof v === "object" && "$date" in v ? new Date(v.$date) : v)', ctx);
265
265
  }
266
266
  export const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
267
267
  export const sameSnap = (a, b) => {
@@ -364,7 +364,7 @@ export function draw(sort, sorts, name, rand, near, bound, strs) {
364
364
  }
365
365
  export function check(code, file, m, r, sorts, opts = {}) {
366
366
  const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
367
- const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text]] : []);
367
+ const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text], ...(m.factory.extra ?? [])] : []);
368
368
  // An object a factory makes: its state is what its functions close over, read and set through the two functions the
369
369
  // check added to it.
370
370
  const stateOf = (self) => (m.factory ? box.call('$get', self, []).value : self);
@@ -376,7 +376,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
376
376
  if (isClass && !m.factory)
377
377
  vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return new __gdp[${E}](...args) }; __gdp.$at = function (fields) { return Object.assign(Object.create(__gdp[${E}].prototype), fields) }`, box.ctx);
378
378
  if (m.factory)
379
- vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return __gdp[${E}](...args) }; __gdp.$get = function () { return this.__gdpGet() }; __gdp.$at = function (fields, args) { const o = __gdp[${E}](...args); o.__gdpSet(fields); return o }`, box.ctx);
379
+ vmOf().runInContext(m.factory.calls ?? `__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return __gdp[${E}](...args) }; __gdp.$get = function () { return this.__gdpGet() }; __gdp.$at = function (fields, args) { const o = __gdp[${E}](...args); o.__gdpSet(fields); return o }`, box.ctx);
380
380
  // A class's fields holding a function: each answers the request's input (set on the object before each call; a
381
381
  // function given to the constructor is one such too).
382
382
  let answers = {};
@@ -445,5 +445,5 @@ export const kindOf = (v, sorts, at = v.name) => {
445
445
  case 'str': return 'str()';
446
446
  }
447
447
  };
448
- export const mapKind = (d, sorts) => `record({has: bool, ${d.fields.map(f => `${f.name}: ${kindOf(f, sorts, `${d.name}.${f.name}`)}`).join(', ')}})`;
449
- export const mapEmpty = (d) => `{has: false, ${d.fields.map(f => `${f.name}: ${f.sort.k === 'num' ? '0' : f.sort.k === 'bool' ? 'false' : f.sort.k === 'choice' ? q(f.sort.values[0]) : "''"}`).join(', ')}}`;
448
+ export const mapKind = (d, sorts) => `record({${['has: bool', ...d.fields.map(f => `${f.name}: ${kindOf(f, sorts, `${d.name}.${f.name}`)}`)].join(', ')}})`;
449
+ export const mapEmpty = (d) => `{${['has: false', ...d.fields.map(f => `${f.name}: ${f.sort.k === 'num' ? '0' : f.sort.k === 'bool' ? 'false' : f.sort.k === 'choice' ? q(f.sort.values[0]) : "''"}`)].join(', ')}}`;
@@ -28,7 +28,7 @@ export type Shape = Sort | {
28
28
  k: 'map';
29
29
  key: 'num' | 'str';
30
30
  val: Shape;
31
- js: 'Map' | 'record';
31
+ js: 'Map' | 'record' | 'Set';
32
32
  } | {
33
33
  k: 'list';
34
34
  of: Sort;
@@ -44,7 +44,7 @@ export type MapDecl = {
44
44
  key: 'num' | 'str';
45
45
  fields: Var[];
46
46
  scalar: boolean;
47
- js: 'Map' | 'record';
47
+ js: 'Map' | 'record' | 'Set';
48
48
  untyped?: boolean;
49
49
  };
50
50
  export type Layout = {
@@ -159,6 +159,8 @@ export type Model = {
159
159
  factory?: {
160
160
  at: number;
161
161
  text: string;
162
+ calls?: string;
163
+ extra?: [number, string][];
162
164
  };
163
165
  results?: Record<string, {
164
166
  k: 'scalar';
@@ -216,6 +218,12 @@ type V = {
216
218
  c: B;
217
219
  a: V;
218
220
  b: V;
221
+ } | {
222
+ t: 'eff';
223
+ run: (p: Path) => [V, Path];
224
+ } | {
225
+ t: 'tuple';
226
+ xs: V[];
219
227
  };
220
228
  type Rec = {
221
229
  k: 'rec';
@@ -263,6 +271,10 @@ type Flow = {
263
271
  breaks: Path[];
264
272
  };
265
273
  export declare const unparen: (x: ts.Expression) => ts.Expression;
274
+ export declare const bare: (x: ts.Expression) => ts.Expression;
275
+ export declare const where: (n: ts.Node) => string;
276
+ export declare const refuse: (n: ts.Node, what: string) => never;
277
+ export declare const text: (n: ts.Node) => string;
266
278
  export declare const normalize: (path: string) => string;
267
279
  export declare const resolveIn: (files: Record<string, string>, from: string, spec: string) => string | undefined;
268
280
  export declare function program(code: string, file: string, extra?: Record<string, string>): {
@@ -311,6 +323,7 @@ export type Setup = {
311
323
  }>;
312
324
  names: Set<string>;
313
325
  };
326
+ effect?: (ex: Exec, e: ts.Expression, p: Path) => [V, Path] | undefined;
314
327
  };
315
328
  export declare class Exec {
316
329
  readonly s: Setup;
@@ -352,7 +365,7 @@ export declare class Exec {
352
365
  private bool;
353
366
  equal(a: V, b: V, at: ts.Node, loose?: boolean): B;
354
367
  ev(e: ts.Expression, p: Path): [V, Path];
355
- private joinValues;
368
+ joinValues(c: B, qa: Path, va: V, qb: Path, vb: V, at: ts.Node): [V, Path];
356
369
  private name;
357
370
  private prefix;
358
371
  private binary;
@@ -372,9 +385,10 @@ export declare class Exec {
372
385
  mapSet(id: string, key: K, v: V | undefined, at: ts.Node, p: Path, track?: boolean): Path;
373
386
  private cellValue;
374
387
  assign(target: ts.Expression, v: V, p: Path, setTime?: boolean): Path;
375
- private writeField;
388
+ writeField(b: V, f: string, v: V, q: Path, target: ts.Node): Path;
389
+ whole(v: V, q: Path, at: ts.Node): [V, Path];
376
390
  resolved(e: ts.Node): ts.Symbol | undefined;
377
- private args;
391
+ args(xs: readonly ts.Expression[], p: Path): [V[], Path];
378
392
  private call;
379
393
  fnField(x: ts.Expression): boolean;
380
394
  private outside;
@@ -383,9 +397,9 @@ export declare class Exec {
383
397
  private array;
384
398
  member(name: string, from?: number): ts.ClassElement | undefined;
385
399
  private math;
386
- private now;
400
+ now(e: ts.Node, p: Path): [V, Path];
387
401
  private newExpr;
388
- inline(f: Callable, args: V[], at: ts.Node, p: Path): [V, Path];
402
+ inline(f: Callable, args: V[], at: ts.Node, p: Path, locals?: Map<string, V>): [V, Path];
389
403
  }
390
404
  export declare const isDate: (t: ts.Type) => boolean;
391
405
  export declare function mergeWrites<V>(c: B, wa: Write<V> | undefined, wb: Write<V> | undefined, base: (key: K) => {