@ontemper/sdk 0.10.4 → 0.12.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 (62) hide show
  1. package/README.md +134 -12
  2. package/dist/Contract/Manifest.d.ts +3 -2
  3. package/dist/Contract/Manifest.d.ts.map +1 -1
  4. package/dist/Contract/Manifest.js +2 -0
  5. package/dist/Contract/Manifest.js.map +1 -1
  6. package/dist/Contract/StaticGraph.d.ts +96 -0
  7. package/dist/Contract/StaticGraph.d.ts.map +1 -0
  8. package/dist/Contract/StaticGraph.js +92 -0
  9. package/dist/Contract/StaticGraph.js.map +1 -0
  10. package/dist/Contract/index.d.ts +1 -0
  11. package/dist/Contract/index.d.ts.map +1 -1
  12. package/dist/Contract/index.js +1 -0
  13. package/dist/Contract/index.js.map +1 -1
  14. package/dist/Manifest.d.ts +1 -1
  15. package/dist/Manifest.d.ts.map +1 -1
  16. package/dist/Manifest.js +17 -75
  17. package/dist/Manifest.js.map +1 -1
  18. package/dist/StaticGraph.d.ts +87 -0
  19. package/dist/StaticGraph.d.ts.map +1 -0
  20. package/dist/StaticGraph.js +237 -0
  21. package/dist/StaticGraph.js.map +1 -0
  22. package/dist/StaticGraphAnalyzer.d.ts +7 -0
  23. package/dist/StaticGraphAnalyzer.d.ts.map +1 -0
  24. package/dist/StaticGraphAnalyzer.js +162 -0
  25. package/dist/StaticGraphAnalyzer.js.map +1 -0
  26. package/dist/StaticGraphCalls.d.ts +15 -0
  27. package/dist/StaticGraphCalls.d.ts.map +1 -0
  28. package/dist/StaticGraphCalls.js +1028 -0
  29. package/dist/StaticGraphCalls.js.map +1 -0
  30. package/dist/StaticGraphDeclarations.d.ts +43 -0
  31. package/dist/StaticGraphDeclarations.d.ts.map +1 -0
  32. package/dist/StaticGraphDeclarations.js +443 -0
  33. package/dist/StaticGraphDeclarations.js.map +1 -0
  34. package/dist/StaticGraphProcess.d.ts +2 -0
  35. package/dist/StaticGraphProcess.d.ts.map +1 -0
  36. package/dist/StaticGraphProcess.js +55 -0
  37. package/dist/StaticGraphProcess.js.map +1 -0
  38. package/dist/StaticGraphProject.d.ts +65 -0
  39. package/dist/StaticGraphProject.d.ts.map +1 -0
  40. package/dist/StaticGraphProject.js +303 -0
  41. package/dist/StaticGraphProject.js.map +1 -0
  42. package/dist/StaticGraphProtocol.d.ts +82 -0
  43. package/dist/StaticGraphProtocol.d.ts.map +1 -0
  44. package/dist/StaticGraphProtocol.js +36 -0
  45. package/dist/StaticGraphProtocol.js.map +1 -0
  46. package/dist/StaticGraphRuntime.d.ts +25 -0
  47. package/dist/StaticGraphRuntime.d.ts.map +1 -0
  48. package/dist/StaticGraphRuntime.js +60 -0
  49. package/dist/StaticGraphRuntime.js.map +1 -0
  50. package/dist/StaticGraphValues.d.ts +243 -0
  51. package/dist/StaticGraphValues.d.ts.map +1 -0
  52. package/dist/StaticGraphValues.js +845 -0
  53. package/dist/StaticGraphValues.js.map +1 -0
  54. package/dist/StepCatalogRules.d.ts +33 -0
  55. package/dist/StepCatalogRules.d.ts.map +1 -0
  56. package/dist/StepCatalogRules.js +64 -0
  57. package/dist/StepCatalogRules.js.map +1 -0
  58. package/dist/cli.d.ts +1 -1
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js +67 -9
  61. package/dist/cli.js.map +1 -1
  62. package/package.json +13 -4
@@ -0,0 +1,1028 @@
1
+ // LARGE_FILE: One mutually recursive walk; a split of expressions, combinators, and statements needs an import cycle.
2
+ // The possible Step calls of workflow code (FLOW-10): what an effect runs, in code order, through pipes, Effect
3
+ // combinators, calls of workflow functions, branches, and loops. Node runs the analyzer modules as written (.ts imports).
4
+ import ts from 'typescript';
5
+ import { LimitReached, MAX_LABEL_LENGTH } from './StaticGraphProject.js';
6
+ import { DEFERRED, FUNCTION_BUILDERS, LIB_VALUE, UNKNOWN, apiOf, argumentBindings, bindArguments, declaredName, effectName, evaluate, functionValue, isEffectApi, isGenerator, isPipeFunction, lastFunction, literalOf, markDependent, member, propertyExpression, propertyName, resultExpression, resultOf, textOf, tick, unwrap, within, words, } from './StaticGraphValues.js';
7
+ const NO_JUMPS = new Set();
8
+ const runsOn = (nodes) => ({ nodes, falls: true, jumps: NO_JUMPS });
9
+ const leavesBy = (jump, nodes = []) => ({ nodes, falls: false, jumps: new Set([jump]) });
10
+ const EMPTY_FLOW = runsOn([]);
11
+ const labelJump = (label) => `label:${label.text}`;
12
+ const jumpsOf = (flows) => new Set(flows.flatMap((flow) => [...flow.jumps]));
13
+ // `jumps` without the jumps that end at the statement around them, such as a `break` at its loop.
14
+ const jumpsPast = (jumps, ended) => new Set([...jumps].filter((jump) => !ended.includes(jump)));
15
+ export const unresolved = (reason, label) => label === undefined
16
+ ? { kind: 'unresolved', reason }
17
+ : { kind: 'unresolved', reason, label: label.slice(0, MAX_LABEL_LENGTH) };
18
+ // A call into `target`, which the analyzer is inside of: the graph marks the recursion and does not unroll it (FLOW-10).
19
+ const recursionInto = (ctx, target) => {
20
+ markDependent(ctx, target, false);
21
+ const mark = unresolved('recursion', declaredName(target));
22
+ ctx.recursions.set(mark, target);
23
+ return mark;
24
+ };
25
+ const armOf = (label, nodes) => label === undefined ? { nodes } : { label, nodes };
26
+ // A branch of `arms` when one of them holds a call; the arms without one become a single empty arm, which skips.
27
+ const branchOf = (arms) => {
28
+ const filled = arms.filter((candidate) => candidate.nodes.length > 0);
29
+ if (filled.length === 0)
30
+ return [];
31
+ return [{ kind: 'branch', arms: filled.length === arms.length ? filled : [...filled, { nodes: [] }] }];
32
+ };
33
+ const loopOf = (body, concurrency) => {
34
+ if (body.length === 0)
35
+ return [];
36
+ return [concurrency === undefined ? { kind: 'loop', body } : { kind: 'loop', body, concurrency }];
37
+ };
38
+ // Lanes that run at one time; fewer than two lanes with a call are no parallel work.
39
+ const parallelOf = (lanes) => {
40
+ const filled = lanes.filter((lane) => lane.length > 0);
41
+ return filled.length < 2 ? filled.flat() : [{ kind: 'parallel', lanes: filled }];
42
+ };
43
+ // A step node, or a dynamic call for a step the catalog does not hold, such as one made inside a function.
44
+ const stepNodes = (id, body) => id === null ? [unresolved('dynamic-call', 'Step.make')] : [{ kind: 'step', stepId: id, body }];
45
+ // The dotted name of a callee, such as `order.process`; a computed callee has none.
46
+ const labelOf = (expression) => {
47
+ const node = unwrap(expression);
48
+ if (ts.isIdentifier(node))
49
+ return node.text;
50
+ if (node.kind === ts.SyntaxKind.ThisKeyword)
51
+ return 'this';
52
+ // `table[key](…)`: the label names the table, never the key.
53
+ if (ts.isElementAccessExpression(node))
54
+ return labelOf(node.expression);
55
+ if (!ts.isPropertyAccessExpression(node))
56
+ return undefined;
57
+ const base = labelOf(node.expression);
58
+ return base === undefined ? undefined : `${base}.${node.name.text}`;
59
+ };
60
+ const isShortCircuit = (kind) => kind === ts.SyntaxKind.AmpersandAmpersandToken ||
61
+ kind === ts.SyntaxKind.BarBarToken ||
62
+ kind === ts.SyntaxKind.QuestionQuestionToken;
63
+ // `nodes` without the recursion marks into `target`. A function that runs itself and no step, such as a
64
+ // recursive mapper, adds nothing to the graph; a mark into a function around it stays.
65
+ const withoutRecursionInto = (ctx, nodes, target) => nodes.flatMap((node) => nodeWithoutRecursionInto(ctx, node, target));
66
+ function nodeWithoutRecursionInto(ctx, node, target) {
67
+ switch (node.kind) {
68
+ case 'unresolved':
69
+ return node.reason === 'recursion' && ctx.recursions.get(node) === target ? [] : [node];
70
+ case 'step':
71
+ return [node];
72
+ case 'loop':
73
+ return loopOf(withoutRecursionInto(ctx, node.body, target), node.concurrency);
74
+ case 'branch':
75
+ return branchOf(node.arms.map((arm) => armOf(arm.label, withoutRecursionInto(ctx, arm.nodes, target))));
76
+ case 'parallel':
77
+ return parallelOf(node.lanes.map((lane) => withoutRecursionInto(ctx, lane, target)));
78
+ }
79
+ }
80
+ // Whether a walk found a step or a call it could not resolve; a recursion mark alone says nothing.
81
+ const hasCalls = (nodes) => nodes.some(isCall);
82
+ function isCall(node) {
83
+ switch (node.kind) {
84
+ case 'step':
85
+ return true;
86
+ case 'unresolved':
87
+ return node.reason !== 'recursion';
88
+ case 'branch':
89
+ return node.arms.some((candidate) => hasCalls(candidate.nodes));
90
+ case 'loop':
91
+ return hasCalls(node.body);
92
+ case 'parallel':
93
+ return node.lanes.some(hasCalls);
94
+ }
95
+ }
96
+ const RUNNERS = ['runPromise', 'runPromiseExit', 'runSync', 'runSyncExit', 'runFork', 'runCallback'];
97
+ // Array methods that run their callback once for each item.
98
+ const ARRAY_ITERATIONS = [
99
+ 'forEach',
100
+ 'map',
101
+ 'flatMap',
102
+ 'filter',
103
+ 'reduce',
104
+ 'reduceRight',
105
+ 'some',
106
+ 'every',
107
+ 'find',
108
+ 'findIndex',
109
+ ];
110
+ // Effect modules whose functions run a callback once for each element they process.
111
+ const ELEMENT_MODULES = ['Stream', 'Sink', 'Channel', 'Array', 'Chunk', 'Iterable', 'Record'];
112
+ // What a call runs when the code only evaluates it: a plain workflow function runs its body, and `Effect.run*` runs its effect.
113
+ const evaluatedCall = (ctx, call, env) => {
114
+ const callee = evaluate(ctx, call.expression, env);
115
+ if (callee.t === 'function')
116
+ return callFunction(ctx, callee, argumentBindings(call.arguments, env), 'evaluate');
117
+ const first = call.arguments[0];
118
+ if (isEffectApi(callee, 'Effect', RUNNERS))
119
+ return first === undefined ? [] : walkEffect(ctx, first, env, true);
120
+ // A package call owns its callbacks: where the code yields the call, the walk of that effect reads them.
121
+ if (callee.t !== 'unknown')
122
+ return [];
123
+ // A method the source does not name, such as `items.forEach`, runs the plain callbacks it receives.
124
+ const target = unwrap(call.expression);
125
+ const method = ts.isPropertyAccessExpression(target) ? target.name.text : '';
126
+ const body = call.arguments.flatMap((argument) => {
127
+ const literal = unwrap(argument);
128
+ const callback = ts.isArrowFunction(literal) || ts.isFunctionExpression(literal) ? functionValue(literal, env) : undefined;
129
+ return callback === undefined ? [] : callFunction(ctx, callback, [], 'evaluate');
130
+ });
131
+ return ARRAY_ITERATIONS.includes(method) ? loopOf(body, undefined) : body;
132
+ };
133
+ // The calls that evaluating `node` makes, in evaluation order: each `yield*` runs its effect. An Effect that
134
+ // the code builds and does not yield or return runs nothing, and a function inside `node` is not entered.
135
+ function scan(ctx, node, env) {
136
+ const out = [];
137
+ const visit = (current) => {
138
+ tick(ctx);
139
+ if (ts.isFunctionLike(current) || ts.isClassLike(current))
140
+ return;
141
+ if (ts.isYieldExpression(current)) {
142
+ if (current.expression === undefined)
143
+ return;
144
+ if (current.asteriskToken === undefined)
145
+ visit(current.expression);
146
+ else
147
+ out.push(...walkEffect(ctx, current.expression, env, true));
148
+ }
149
+ else if (ts.isConditionalExpression(current)) {
150
+ visit(current.condition);
151
+ const then = armOf('then', scan(ctx, current.whenTrue, env));
152
+ out.push(...branchOf([then, armOf('else', scan(ctx, current.whenFalse, env))]));
153
+ }
154
+ else if (ts.isBinaryExpression(current) && isShortCircuit(current.operatorToken.kind)) {
155
+ visit(current.left);
156
+ out.push(...branchOf([armOf(undefined, scan(ctx, current.right, env)), armOf(undefined, [])]));
157
+ }
158
+ else if (ts.isCallExpression(current)) {
159
+ visit(current.expression);
160
+ for (const argument of current.arguments)
161
+ visit(argument);
162
+ out.push(...evaluatedCall(ctx, current, env));
163
+ }
164
+ else {
165
+ ts.forEachChild(current, visit);
166
+ }
167
+ };
168
+ visit(node);
169
+ return out;
170
+ }
171
+ // The calls an effect makes when it runs. `strict` says the expression is known to run as an effect.
172
+ function walkEffect(ctx, expression, env, strict) {
173
+ tick(ctx);
174
+ const node = unwrap(expression);
175
+ if (ts.isCallExpression(node))
176
+ return walkCall(ctx, node, env, strict);
177
+ if (ts.isConditionalExpression(node)) {
178
+ const out = scan(ctx, node.condition, env);
179
+ const then = armOf('then', walkEffect(ctx, node.whenTrue, env, strict));
180
+ out.push(...branchOf([then, armOf('else', walkEffect(ctx, node.whenFalse, env, strict))]));
181
+ return out;
182
+ }
183
+ if (ts.isBinaryExpression(node) && isShortCircuit(node.operatorToken.kind)) {
184
+ // `flag && effect` runs the effect or nothing. `a ?? b` and `a || b` run the effect on one of their two sides.
185
+ const guards = node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken;
186
+ const out = guards ? scan(ctx, node.left, env) : [];
187
+ const left = armOf(undefined, guards ? [] : walkEffect(ctx, node.left, env, strict));
188
+ out.push(...branchOf([left, armOf(undefined, walkEffect(ctx, node.right, env, strict))]));
189
+ return out;
190
+ }
191
+ if (ts.isElementAccessExpression(node)) {
192
+ // The key is evaluated before the effect that the member holds runs, as in `table[yield* key]`.
193
+ const out = scan(ctx, node, env);
194
+ out.push(...runValue(ctx, evaluate(ctx, node, env), node, strict));
195
+ return out;
196
+ }
197
+ if (!ts.isIdentifier(node) && !ts.isPropertyAccessExpression(node))
198
+ return scan(ctx, node, env);
199
+ return runValue(ctx, evaluate(ctx, node, env), node, strict);
200
+ }
201
+ // The calls of an effect that a name holds, such as a `const` or a member of a service.
202
+ function runValue(ctx, value, node, strict) {
203
+ switch (value.t) {
204
+ case 'expression':
205
+ return value.node === node ? [] : walkNamed(ctx, value, strict);
206
+ case 'walked':
207
+ return [...value.nodes];
208
+ // Where the value may be plain data, such as a field of a service, reading it marks nothing.
209
+ case 'ambiguous':
210
+ return strict ? [unresolved('ambiguous-layer', value.label)] : [];
211
+ case 'external':
212
+ return strict ? [unresolved('external-module', value.module)] : [];
213
+ case 'choice':
214
+ return branchOf(value.options.map((option) => armOf(undefined, runValue(ctx, option, node, strict))));
215
+ // An effect that the source does not name, such as a parameter, `this.job`, or `table[key]`, can run any step.
216
+ case 'unknown':
217
+ return strict ? [unresolved('dynamic-call', labelOf(node))] : [];
218
+ default:
219
+ return [];
220
+ }
221
+ }
222
+ // An effect that a `const` holds, walked where it runs; one that runs itself is a recursion.
223
+ const walkNamed = (ctx, value, strict) => {
224
+ if (ctx.stack.includes(value.node))
225
+ return [recursionInto(ctx, value.node)];
226
+ const nodes = within(ctx, value.node, () => walkEffect(ctx, value.node, value.env, strict));
227
+ return hasCalls(nodes) ? nodes : withoutRecursionInto(ctx, nodes, value.node);
228
+ };
229
+ function walkCall(ctx, call, env, strict) {
230
+ const callee = unwrap(call.expression);
231
+ const value = evaluate(ctx, callee, env);
232
+ const [first, ...rest] = call.arguments;
233
+ // Read before the `.pipe` method: `Function.pipe(base, step)` is the function, and `Function` is no base.
234
+ if (isPipeFunction(value) && first !== undefined)
235
+ return walkPipe(ctx, first, rest, env, strict);
236
+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'pipe') {
237
+ return walkPipe(ctx, callee.expression, call.arguments, env, strict);
238
+ }
239
+ // Arguments are evaluated before the call runs, so what they run comes first.
240
+ const out = scan(ctx, callee, env);
241
+ for (const argument of call.arguments)
242
+ out.push(...scan(ctx, argument, env));
243
+ out.push(...callValue(ctx, value, call, env, strict));
244
+ return out;
245
+ }
246
+ // The calls of `call` when its callee is `value`.
247
+ function callValue(ctx, value, call, env, strict) {
248
+ const [first] = call.arguments;
249
+ switch (value.t) {
250
+ case 'stepRun':
251
+ return stepNodes(value.id, first === undefined ? [] : walkEffect(ctx, first, env, true));
252
+ case 'function':
253
+ return callFunction(ctx, value, argumentBindings(call.arguments, env), strict ? 'strict' : 'lenient');
254
+ case 'lib':
255
+ return walkLibrary(ctx, value, call.arguments, env, undefined, strict);
256
+ case 'libValue':
257
+ return walkArguments(ctx, call.arguments, env, true);
258
+ case 'external':
259
+ return [unresolved('external-module', value.module)];
260
+ case 'ambiguous':
261
+ return [unresolved('ambiguous-layer', value.label)];
262
+ case 'choice':
263
+ return branchOf(value.options.map((option) => armOf(undefined, callValue(ctx, option, call, env, strict))));
264
+ case 'builder':
265
+ case 'stepFn':
266
+ // `Effect.fn(name)(body)` and `step.fn(body)` build a function; nothing runs.
267
+ return [];
268
+ case 'expression':
269
+ if (value.lib)
270
+ return walkArguments(ctx, call.arguments, env, true);
271
+ break;
272
+ default:
273
+ break;
274
+ }
275
+ // A callee that the source does not name, such as a method of a value that an Effect combinator made, can run any step.
276
+ return strict ? [unresolved('dynamic-call', labelOf(call.expression))] : [];
277
+ }
278
+ // `base.pipe(a, b)`: the base effect, then each step applied to what came before it.
279
+ const walkPipe = (ctx, base, steps, env, strict) => {
280
+ const evaluated = [];
281
+ let nodes = walkEffect(ctx, base, env, strict);
282
+ let flowing = resultOf(ctx, evaluate(ctx, base, env));
283
+ for (const step of steps) {
284
+ evaluated.push(...scan(ctx, step, env));
285
+ nodes = applyPipe(ctx, { nodes, value: flowing }, step, env);
286
+ flowing = UNKNOWN;
287
+ }
288
+ evaluated.push(...nodes);
289
+ return evaluated;
290
+ };
291
+ // One pipe step: `step.run` wraps what came before, an Effect combinator extends it, and a workflow function receives
292
+ // it. A step that is a call, such as `Effect.map(f)`, is read by its callee; a bare one, such as `Effect.orDie`, by itself.
293
+ function applyPipe(ctx, piped, step, env) {
294
+ const value = evaluate(ctx, step, env);
295
+ const call = value.t === 'expression' && ts.isCallExpression(value.node) ? value.node : undefined;
296
+ const callEnv = value.t === 'expression' ? value.env : env;
297
+ const applied = call === undefined ? value : evaluate(ctx, call.expression, callEnv);
298
+ const given = call === undefined ? [] : call.arguments;
299
+ const out = [...piped.nodes];
300
+ switch (applied.t) {
301
+ case 'stepRun':
302
+ return stepNodes(applied.id, out);
303
+ case 'function':
304
+ if (call === undefined)
305
+ return callFunction(ctx, applied, [{ value: { t: 'walked', nodes: out } }], 'strict');
306
+ break;
307
+ case 'lib':
308
+ return walkLibrary(ctx, applied, given, callEnv, piped, true);
309
+ case 'external':
310
+ return [...out, unresolved('external-module', applied.module)];
311
+ case 'ambiguous':
312
+ return [...out, unresolved('ambiguous-layer', applied.label)];
313
+ case 'libValue':
314
+ return [...out, ...walkArguments(ctx, given, callEnv, true)];
315
+ case 'expression':
316
+ if (applied.lib)
317
+ return [...out, ...walkArguments(ctx, given, callEnv, true)];
318
+ break;
319
+ default:
320
+ break;
321
+ }
322
+ return [...out, unresolved('dynamic-call', labelOf(call?.expression ?? step))];
323
+ }
324
+ // A package call: an `Effect` combinator by its meaning, any other call by the callbacks and effects it receives.
325
+ function walkLibrary(ctx, lib, given, env, piped, strict) {
326
+ const name = effectName(lib);
327
+ if (name !== undefined)
328
+ return walkEffectApi(ctx, name, given, env, piped, strict);
329
+ const api = apiOf(lib);
330
+ const out = piped === undefined ? [] : [...piped.nodes];
331
+ const received = walkArguments(ctx, given, env, !api.effect);
332
+ if (api.effect && ELEMENT_MODULES.includes(api.ns))
333
+ out.push(...loopOf(received, undefined));
334
+ else
335
+ out.push(...received);
336
+ return out;
337
+ }
338
+ const walkArguments = (ctx, expressions, env, supplied) => expressions.flatMap((expression) => walkArgument(ctx, expression, env, supplied));
339
+ const RESOLVED_CALLEES = ['function', 'lib', 'libValue', 'stepRun', 'external', 'ambiguous'];
340
+ // The arguments a package gives a callback when the package makes them itself, such as an open session.
341
+ const suppliedBindings = (fn, supplied) => supplied ? fn.node.parameters.map(() => ({ value: LIB_VALUE })) : [];
342
+ // What an argument of a package call can run: a callback, an effect, or a list or record of them. The call may
343
+ // take plain data too, so a callee the source does not name is not marked here. `supplied` says the package
344
+ // makes the arguments of a callback itself; an Effect combinator passes on values of the workflow instead.
345
+ function walkArgument(ctx, expression, env, supplied) {
346
+ tick(ctx);
347
+ const node = unwrap(expression);
348
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
349
+ const literal = functionValue(node, env);
350
+ return callFunction(ctx, literal, suppliedBindings(literal, supplied), 'lenient');
351
+ }
352
+ if (ts.isObjectLiteralExpression(node)) {
353
+ // A record of callbacks is a match: one of them runs.
354
+ const arms = [];
355
+ for (const property of node.properties) {
356
+ const name = propertyName(property.name);
357
+ if (ts.isPropertyAssignment(property))
358
+ arms.push(armOf(name, walkArgument(ctx, property.initializer, env, supplied)));
359
+ else if (ts.isShorthandPropertyAssignment(property))
360
+ arms.push(armOf(name, walkArgument(ctx, property.name, env, supplied)));
361
+ else if (ts.isMethodDeclaration(property)) {
362
+ const method = functionValue(property, env);
363
+ arms.push(armOf(name, callFunction(ctx, method, suppliedBindings(method, supplied), 'lenient')));
364
+ }
365
+ else if (ts.isSpreadAssignment(property))
366
+ arms.push(armOf(undefined, walkArgument(ctx, property.expression, env, supplied)));
367
+ }
368
+ return branchOf(arms);
369
+ }
370
+ if (ts.isArrayLiteralExpression(node)) {
371
+ return node.elements.flatMap((element) => walkArgument(ctx, ts.isSpreadElement(element) ? element.expression : element, env, supplied));
372
+ }
373
+ if (ts.isConditionalExpression(node)) {
374
+ const then = armOf('then', walkArgument(ctx, node.whenTrue, env, supplied));
375
+ return branchOf([then, armOf('else', walkArgument(ctx, node.whenFalse, env, supplied))]);
376
+ }
377
+ const value = evaluate(ctx, node, env);
378
+ switch (value.t) {
379
+ case 'function':
380
+ return callFunction(ctx, value, suppliedBindings(value, supplied), 'lenient');
381
+ case 'walked':
382
+ return [...value.nodes];
383
+ case 'expression': {
384
+ if (!ts.isCallExpression(node))
385
+ return value.node === node ? [] : walkNamed(ctx, value, false);
386
+ const callee = evaluate(ctx, node.expression, env);
387
+ const resolved = RESOLVED_CALLEES.includes(callee.t) || (callee.t === 'expression' && callee.lib);
388
+ return resolved ? walkEffect(ctx, node, env, false) : [];
389
+ }
390
+ default:
391
+ return [];
392
+ }
393
+ }
394
+ // The calls of a callback that a combinator runs as an effect; one that the source does not name is a dynamic call.
395
+ function runCallback(ctx, value, label, bindings) {
396
+ switch (value.t) {
397
+ case 'function':
398
+ return callFunction(ctx, value, bindings, 'strict');
399
+ case 'ambiguous':
400
+ return [unresolved('ambiguous-layer', value.label)];
401
+ case 'external':
402
+ return [unresolved('external-module', value.module)];
403
+ case 'choice':
404
+ return branchOf(value.options.map((option) => armOf(undefined, runCallback(ctx, option, label, bindings))));
405
+ // A function of a package, such as `Effect.die`, runs no step.
406
+ case 'lib':
407
+ case 'libValue':
408
+ return [];
409
+ default:
410
+ if (value.t === 'expression' && value.lib)
411
+ return walkArgument(ctx, value.node, value.env, false);
412
+ return [unresolved('dynamic-call', label)];
413
+ }
414
+ }
415
+ const walkCallback = (ctx, expression, env, bindings) => expression === undefined ? [] : runCallback(ctx, evaluate(ctx, expression, env), labelOf(expression), bindings);
416
+ // An effect, or a callback that makes one, that a combinator runs after the effect before it.
417
+ const walkOperand = (ctx, expression, env, bindings) => {
418
+ if (expression === undefined)
419
+ return [];
420
+ return evaluate(ctx, expression, env).t === 'function'
421
+ ? walkCallback(ctx, expression, env, bindings)
422
+ : walkEffect(ctx, expression, env, true);
423
+ };
424
+ // The names below are exports of `effect@4.0.6`. A name in no list is one that the analyzer does not model.
425
+ // Functions that hold their arguments or read the fiber: an Effect among the arguments is a value, and it does not run.
426
+ const INERT = words(`succeed succeedSome succeedNone fail failCause die interrupt log logTrace logDebug logInfo logWarning
427
+ logError logFatal sleep yieldNow annotateCurrentSpan annotateLogsScoped context service serviceOption fromNullishOr
428
+ fromOption fromResult makeSpan makeSpanScoped cachedInvalidateWithTTL`);
429
+ // Combinators that run the effect before them once and nothing else: their callbacks compute plain values.
430
+ const PURE = words(`map mapEager mapError mapErrorEager mapBoth mapBothEager as asVoid asSome let bindTo head orDie
431
+ orElseSucceed catchNoSuchElement unwrapReason withSpan withSpanScoped withParentSpan linkSpans withLogSpan withLogger
432
+ withTracer withTracerEnabled withTracerTiming withErrorReporting annotateLogs annotateSpans provide provideContext
433
+ provideService updateService updateServiceScoped updateContext setContext delay timeout timeoutOption interruptible
434
+ uninterruptible scoped acquireDisposable exit result option isSuccess isFailure filterOrFail flip ignore ignoreCause
435
+ sandbox timed track trackDefects trackDuration trackErrors trackSuccesses match matchEager matchCause
436
+ matchCauseEager forkChild forkDetach forkIn forkScoped awaitAllChildren`);
437
+ // Constructors whose callbacks are plain code: they run when the effect runs, and return no effect.
438
+ const EVALUATED = words('sync promise try tryPromise callback failSync failCauseSync withFiberSucceed');
439
+ // Combinators that run the effect before them again.
440
+ const REPEATS = words('retry repeat forever schedule eventually replicateEffect');
441
+ // Combinators whose last argument handles the failure or the interruption of the effect before them.
442
+ const HANDLERS = words('catch catchCause catchDefect catchEager tapError tapCause tapDefect onError onInterrupt');
443
+ // Combinators that take `(filter, handler, orElse?)`: one handler for a failure that matches, one for any other.
444
+ const FILTERED_HANDLERS = words('catchIf catchFilter catchCauseIf catchCauseFilter tapCauseIf tapCauseFilter onErrorIf onErrorFilter');
445
+ // Combinators that run an effect, or the effect a callback makes from the value before it, after the effect before them.
446
+ const SEQUENCES = words('andThen tap flatMap flatMapEager acquireRelease acquireUseRelease');
447
+ // Combinators that run a second effect, or a callback that takes another value, after the effect before them, by the
448
+ // place of that argument after the effect.
449
+ const FOLLOWERS = new Map([
450
+ ...[...words('zip zipWith ensuring onExit onExitPrimitive')].map((name) => [name, 0]),
451
+ ...[...words('bind onExitIf onExitFilter')].map((name) => [name, 1]),
452
+ ]);
453
+ const MATCHES = words('matchEffect matchCauseEffect matchCauseEffectEager');
454
+ // Constructors that run the effect that their last argument, a callback, returns.
455
+ const CALLBACKS = words('suspend clockWith contextWith scopedWith withFiber useSpan addFinalizer uninterruptibleMask interruptibleMask');
456
+ // Constructors that run a callback once for each element: `(elements, callback, options?)`.
457
+ const ITERATIONS = words('forEach validate partition filter findFirst findFirstFilter');
458
+ // The `concurrency` an options argument states: absent or 1 is sequential, and a computed value is `dynamic`.
459
+ const concurrencyOf = (ctx, options, env) => {
460
+ if (options === undefined)
461
+ return undefined;
462
+ const value = evaluate(ctx, options, env);
463
+ if (value.t !== 'object')
464
+ return 'dynamic';
465
+ const written = propertyExpression(value.node, 'concurrency');
466
+ if (written === undefined)
467
+ return value.node.properties.some(ts.isSpreadAssignment) ? 'dynamic' : undefined;
468
+ const concurrency = evaluate(ctx, written, value.env);
469
+ if (concurrency.t === 'text')
470
+ return concurrency.value === 'unbounded' ? 'unbounded' : 'dynamic';
471
+ if (concurrency.t !== 'number' || concurrency.value < 1)
472
+ return 'dynamic';
473
+ return concurrency.value === 1 ? undefined : concurrency.value;
474
+ };
475
+ // The calls of the callback `name` in an options record, such as `{ onSuccess, onFailure }`. A record or a callback
476
+ // that the source does not name is a dynamic call.
477
+ const optionCallback = (ctx, expression, env, name) => {
478
+ const options = expression === undefined ? UNKNOWN : evaluate(ctx, expression, env);
479
+ const record = expression === undefined ? undefined : labelOf(expression);
480
+ const label = record === undefined ? name : `${record}.${name}`;
481
+ return runCallback(ctx, options.t === 'object' ? member(ctx, options, name) : UNKNOWN, label, []);
482
+ };
483
+ // The handlers of a `catchTags` record, one arm each. A record or a spread that the source does not name holds
484
+ // handlers that the analyzer cannot read, so it is one dynamic call.
485
+ const caseArms = (ctx, expression, env) => {
486
+ const cases = expression === undefined ? UNKNOWN : evaluate(ctx, expression, env);
487
+ if (cases.t !== 'object') {
488
+ const label = expression === undefined ? undefined : labelOf(expression);
489
+ return [armOf('catch', [unresolved('dynamic-call', label)])];
490
+ }
491
+ return cases.node.properties.flatMap((property) => {
492
+ const label = `catch:${propertyName(property.name) ?? ''}`;
493
+ if (ts.isSpreadAssignment(property))
494
+ return caseArms(ctx, property.expression, cases.env);
495
+ if (ts.isPropertyAssignment(property))
496
+ return [armOf(label, walkCallback(ctx, property.initializer, cases.env, []))];
497
+ if (ts.isShorthandPropertyAssignment(property))
498
+ return [armOf(label, walkCallback(ctx, property.name, cases.env, []))];
499
+ if (ts.isMethodDeclaration(property)) {
500
+ return [armOf(label, callFunction(ctx, functionValue(property, cases.env), [], 'strict'))];
501
+ }
502
+ return [armOf(label, [unresolved('dynamic-call', propertyName(property.name))])];
503
+ });
504
+ };
505
+ // Names and calls followed from one collection to the list or record it holds.
506
+ const MAX_COLLECTION_HOPS = 16;
507
+ const laneOf = (nodes) => [{ nodes }];
508
+ const namesOf = (lane) => (lane.key === undefined ? (lane.names ?? []) : [lane.key]);
509
+ // The calls of a collection: its lanes in turn, or at one time when a stated concurrency above 1 proves that.
510
+ const joinLanes = (lanes, concurrency) => {
511
+ const all = lanes.map((lane) => lane.nodes);
512
+ return concurrency === undefined || concurrency === 'dynamic' ? all.flat() : parallelOf(all);
513
+ };
514
+ // One lane for a collection that the code chooses: one arm runs, with the lanes of that arm.
515
+ const chosenLane = (arms, concurrency) => ({
516
+ names: arms.flatMap((arm) => arm.lanes.flatMap(namesOf)),
517
+ nodes: branchOf(arms.map((arm) => armOf(arm.label, joinLanes(arm.lanes, concurrency)))),
518
+ });
519
+ // The callback of `items.map(f)` or `items.flatMap(f)`, which makes one effect for each item.
520
+ const mapperOf = (call) => {
521
+ const callee = unwrap(call.expression);
522
+ const maps = ts.isPropertyAccessExpression(callee) && (callee.name.text === 'map' || callee.name.text === 'flatMap');
523
+ return maps ? call.arguments.at(-1) : undefined;
524
+ };
525
+ // The lanes of a record: one for each property, and the lanes of each list or record it spreads. A later property
526
+ // replaces an earlier one with the same name.
527
+ const recordLanes = (ctx, node, env, concurrency, hops) => {
528
+ const lanes = [];
529
+ const add = (lane) => {
530
+ // A name on one arm of a chosen collection replaces an effect of that name on that arm only, or is replaced
531
+ // there. No lane says that, so the effects of the name are one dynamic call: the graph invents no path (FLOW-10).
532
+ const clashedNames = new Set();
533
+ for (const [at, known] of lanes.entries()) {
534
+ const chosen = known.names !== undefined || lane.names !== undefined;
535
+ const shared = chosen ? namesOf(known).filter((candidate) => namesOf(lane).includes(candidate)) : [];
536
+ if (shared.length === 0)
537
+ continue;
538
+ for (const name of shared)
539
+ clashedNames.add(name);
540
+ const keepKnown = known.names !== undefined && known.names.some((candidate) => !shared.includes(candidate));
541
+ lanes[at] = {
542
+ nodes: [...shared.map((name) => unresolved('dynamic-call', name)), ...(keepKnown ? known.nodes : [])],
543
+ };
544
+ }
545
+ if (clashedNames.size > 0 && lane.names !== undefined) {
546
+ if (lane.names.some((candidate) => !clashedNames.has(candidate)))
547
+ lanes.push({ nodes: lane.nodes });
548
+ return;
549
+ }
550
+ const own = lane.key === undefined ? -1 : lanes.findIndex((known) => known.key === lane.key);
551
+ if (own === -1)
552
+ lanes.push(lane);
553
+ else
554
+ lanes[own] = lane;
555
+ };
556
+ for (const property of node.properties) {
557
+ const key = propertyName(property.name);
558
+ if (ts.isPropertyAssignment(property))
559
+ add({ key, nodes: walkEffect(ctx, property.initializer, env, true) });
560
+ else if (ts.isShorthandPropertyAssignment(property))
561
+ add({ key, nodes: walkEffect(ctx, property.name, env, true) });
562
+ else if (ts.isSpreadAssignment(property))
563
+ for (const lane of collectionLanes(ctx, property.expression, env, concurrency, hops))
564
+ add(lane);
565
+ // A method or an accessor holds no effect that the source names.
566
+ else
567
+ add({ key, nodes: [unresolved('dynamic-call', key)] });
568
+ }
569
+ return lanes;
570
+ };
571
+ // The lanes of the collection that a call of a workflow function returns, or `undefined` when the source does not say.
572
+ const returnedLanes = (ctx, call, env, concurrency, hops) => {
573
+ const callee = evaluate(ctx, call.expression, env);
574
+ if (callee.t !== 'function' || callee.lazy || isGenerator(callee.node))
575
+ return undefined;
576
+ const result = resultExpression(callee.node);
577
+ if (result === undefined || ctx.stack.includes(callee.node))
578
+ return undefined;
579
+ const callEnv = bindArguments(callee, argumentBindings(call.arguments, env));
580
+ return within(ctx, callee.node, () => collectionLanes(ctx, result, callEnv, concurrency, hops + 1));
581
+ };
582
+ // The lanes of a collection that is no literal: what a name, a call, or a member of a service holds.
583
+ function heldLanes(ctx, value, node, env, concurrency, hops) {
584
+ const follows = hops < MAX_COLLECTION_HOPS;
585
+ switch (value.t) {
586
+ case 'array':
587
+ case 'object':
588
+ case 'expression': {
589
+ if (value.node !== node && follows)
590
+ return collectionLanes(ctx, value.node, value.env, concurrency, hops + 1);
591
+ // The result of a package call holds what its callbacks make, and the walk of the call reads them.
592
+ if (value.t === 'expression' && value.lib)
593
+ return laneOf(walkArgument(ctx, node, env, false));
594
+ const returned = ts.isCallExpression(node) && follows ? returnedLanes(ctx, node, env, concurrency, hops) : undefined;
595
+ if (returned !== undefined)
596
+ return returned;
597
+ break;
598
+ }
599
+ case 'walked':
600
+ return laneOf([...value.nodes]);
601
+ case 'lib':
602
+ case 'libValue':
603
+ return [];
604
+ case 'ambiguous':
605
+ return laneOf([unresolved('ambiguous-layer', value.label)]);
606
+ case 'external':
607
+ return laneOf([unresolved('external-module', value.module)]);
608
+ case 'choice': {
609
+ const arm = (option) => ({
610
+ label: undefined,
611
+ lanes: heldLanes(ctx, option, node, env, concurrency, hops),
612
+ });
613
+ return [chosenLane(value.options.map(arm), concurrency)];
614
+ }
615
+ default:
616
+ break;
617
+ }
618
+ return laneOf([unresolved('dynamic-call', labelOf(node))]);
619
+ }
620
+ // The effects of an `Effect.all` collection, one lane each: the members of a list or a record, with the lists and
621
+ // records it spreads in their place, or one effect for each item of `items.map(f)`. `Effect.all` runs every
622
+ // member, so a collection or a spread that the source does not name is one dynamic call, never no call (FLOW-10).
623
+ function collectionLanes(ctx, expression, env, concurrency, hops) {
624
+ tick(ctx);
625
+ const node = unwrap(expression);
626
+ if (ts.isArrayLiteralExpression(node)) {
627
+ // Each member runs as an effect, so a call that the source does not name is marked, as a `yield*` of it is.
628
+ return node.elements.flatMap((element) => ts.isSpreadElement(element)
629
+ ? collectionLanes(ctx, element.expression, env, concurrency, hops)
630
+ : laneOf(walkEffect(ctx, element, env, true)));
631
+ }
632
+ if (ts.isObjectLiteralExpression(node))
633
+ return recordLanes(ctx, node, env, concurrency, hops);
634
+ if (ts.isConditionalExpression(node)) {
635
+ const arm = (label, chosen) => ({
636
+ label,
637
+ lanes: collectionLanes(ctx, chosen, env, concurrency, hops),
638
+ });
639
+ return [chosenLane([arm('then', node.whenTrue), arm('else', node.whenFalse)], concurrency)];
640
+ }
641
+ const mapper = ts.isCallExpression(node) ? mapperOf(node) : undefined;
642
+ if (mapper !== undefined)
643
+ return laneOf(loopOf(walkCallback(ctx, mapper, env, []), concurrency));
644
+ return heldLanes(ctx, evaluate(ctx, node, env), node, env, concurrency, hops);
645
+ }
646
+ // `Effect.all`: the effects of its list or record, at one time only with a stated concurrency above 1.
647
+ const walkAll = (ctx, collection, options, env) => {
648
+ if (collection === undefined)
649
+ return [];
650
+ const concurrency = concurrencyOf(ctx, options, env);
651
+ return joinLanes(collectionLanes(ctx, collection, env, concurrency, 0), concurrency);
652
+ };
653
+ // The label of a `catchTag` arm: `catch:` and the tags the code names.
654
+ const catchLabel = (ctx, tag, env) => {
655
+ const literal = tag === undefined ? undefined : literalOf(ctx, tag, env, 0);
656
+ const value = literal?.value;
657
+ const tags = Array.isArray(value) ? value.map(String) : [];
658
+ const text = tag === undefined ? undefined : textOf(ctx, tag, env);
659
+ if (text !== undefined)
660
+ return `catch:${text}`;
661
+ return tags.length === 0 ? 'catch' : `catch:${tags.join('|')}`;
662
+ };
663
+ // Effect makes the `restore` function that a mask callback receives: a call of it runs its argument once, as
664
+ // `Effect.interruptible` does.
665
+ const RESTORE = { value: { t: 'lib', module: 'effect', path: ['Effect', 'interruptible'] } };
666
+ // The functions among the arguments of a constructor such as `Effect.try`, also as the members of its options record.
667
+ const plainCallbacks = (ctx, argument, env) => {
668
+ const value = evaluate(ctx, argument, env);
669
+ if (value.t !== 'object')
670
+ return [value];
671
+ return value.node.properties.map((property) => {
672
+ if (ts.isMethodDeclaration(property))
673
+ return functionValue(property, value.env);
674
+ return ts.isPropertyAssignment(property) ? evaluate(ctx, property.initializer, value.env) : UNKNOWN;
675
+ });
676
+ };
677
+ // The arms of the handlers of a failure, or `undefined` for a combinator that handles none. `rest` holds the
678
+ // arguments after the effect: a tag or a filter, the handler, and a handler for every other failure.
679
+ const handlerArms = (ctx, name, rest, env) => {
680
+ const tagged = name === 'catchTag' || name === 'tapErrorTag' || name === 'catchReason';
681
+ const handlerAt = HANDLERS.has(name)
682
+ ? 0
683
+ : name === 'catchReason'
684
+ ? 2
685
+ : tagged || FILTERED_HANDLERS.has(name)
686
+ ? 1
687
+ : -1;
688
+ const casesAt = name === 'catchTags' ? 0 : name === 'catchReasons' ? 1 : -1;
689
+ if (handlerAt === -1 && casesAt === -1)
690
+ return undefined;
691
+ const arms = casesAt === -1
692
+ ? [armOf(tagged ? catchLabel(ctx, rest[0], env) : 'catch', walkCallback(ctx, rest[handlerAt], env, []))]
693
+ : caseArms(ctx, rest[casesAt], env);
694
+ const orElse = HANDLERS.has(name) ? undefined : rest[Math.max(handlerAt, casesAt) + 1];
695
+ if (orElse !== undefined)
696
+ arms.push(armOf('catch', walkCallback(ctx, orElse, env, [])));
697
+ return arms;
698
+ };
699
+ // The calls of one export of the `Effect` module. In a pipe, `piped` is the effect before it; in a direct call the
700
+ // first argument is. An export that no list names is one dynamic call beside what its arguments run (FLOW-10).
701
+ function walkEffectApi(ctx, name, all, env, piped, strict) {
702
+ const [first] = all;
703
+ const rest = piped === undefined ? all.slice(1) : all;
704
+ const self = () => piped !== undefined ? [...piped.nodes] : first === undefined ? [] : walkEffect(ctx, first, env, strict);
705
+ const succeeded = () => ({
706
+ value: piped !== undefined ? piped.value : first === undefined ? UNKNOWN : resultOf(ctx, evaluate(ctx, first, env)),
707
+ });
708
+ const effect = (expression) => expression === undefined ? [] : walkEffect(ctx, expression, env, true);
709
+ // `Effect.cached(effect)` only makes the effect that runs `effect`: the walk of a yield of its result reads it.
710
+ if (DEFERRED.includes(name))
711
+ return [];
712
+ if (PURE.has(name))
713
+ return self();
714
+ if (REPEATS.has(name))
715
+ return loopOf(self(), undefined);
716
+ if (name === 'when')
717
+ return [...effect(rest[0]), ...branchOf([armOf(undefined, self()), armOf(undefined, [])])];
718
+ // The effect that makes the service runs before the effect that reads it.
719
+ if (name === 'provideServiceEffect')
720
+ return [...effect(rest[1]), ...self()];
721
+ if (name === 'race' || name === 'raceFirst')
722
+ return parallelOf([self(), effect(rest[0])]);
723
+ const follower = FOLLOWERS.get(name);
724
+ if (SEQUENCES.has(name) || follower !== undefined) {
725
+ const bound = follower === undefined ? [succeeded()] : [];
726
+ const nodes = [...self(), ...walkOperand(ctx, rest[follower ?? 0], env, bound)];
727
+ if (name === 'acquireUseRelease')
728
+ nodes.push(...walkCallback(ctx, rest[1], env, bound));
729
+ return nodes;
730
+ }
731
+ if (MATCHES.has(name)) {
732
+ const success = armOf('success', optionCallback(ctx, rest[0], env, 'onSuccess'));
733
+ return [...self(), ...branchOf([success, armOf('failure', optionCallback(ctx, rest[0], env, 'onFailure'))])];
734
+ }
735
+ const handlers = handlerArms(ctx, name, rest, env);
736
+ // The handlers run only when the effect fails, so an empty arm stands for the run without a failure.
737
+ if (handlers !== undefined)
738
+ return [...self(), ...branchOf([...handlers, armOf(undefined, [])])];
739
+ // Every export below is a constructor, which takes no effect before it.
740
+ const out = piped === undefined ? [] : [...piped.nodes];
741
+ if (name === 'gen') {
742
+ const generator = lastFunction(ctx, all, env);
743
+ // A body that the source does not name can run any step.
744
+ if (generator === undefined)
745
+ out.push(unresolved('dynamic-call', 'Effect.gen'));
746
+ else
747
+ out.push(...callFunction(ctx, generator, [], 'strict'));
748
+ }
749
+ else if (CALLBACKS.has(name)) {
750
+ out.push(...walkCallback(ctx, all.at(-1), env, name.endsWith('Mask') ? [RESTORE] : []));
751
+ }
752
+ else if (EVALUATED.has(name)) {
753
+ for (const callback of all.flatMap((argument) => plainCallbacks(ctx, argument, env))) {
754
+ if (callback.t === 'function')
755
+ out.push(...callFunction(ctx, callback, [], 'evaluate'));
756
+ }
757
+ }
758
+ else if (RUNNERS.includes(name)) {
759
+ out.push(...effect(first));
760
+ }
761
+ else if (ITERATIONS.has(name)) {
762
+ out.push(...loopOf(walkCallback(ctx, rest[0], env, []), concurrencyOf(ctx, rest[1], env)));
763
+ }
764
+ else if (name === 'all') {
765
+ out.push(...walkAll(ctx, first, all[1], env));
766
+ }
767
+ else if (name === 'raceAll' || name === 'raceAllFirst') {
768
+ // The members race at one time; a list that is no literal is read as `Effect.all` reads it.
769
+ const lanes = first === undefined ? [] : collectionLanes(ctx, first, env, 'unbounded', 0);
770
+ out.push(...parallelOf(lanes.map((lane) => lane.nodes)));
771
+ }
772
+ else if (name === 'whileLoop') {
773
+ out.push(...loopOf(optionCallback(ctx, first, env, 'body'), undefined));
774
+ }
775
+ else if (!FUNCTION_BUILDERS.includes(name) && !INERT.has(name)) {
776
+ out.push(...walkArguments(ctx, all, env, false), unresolved('dynamic-call', `Effect.${name}`));
777
+ }
778
+ return out;
779
+ }
780
+ export const countNodes = (nodes) => {
781
+ let count = nodes.length;
782
+ for (const node of nodes) {
783
+ if (node.kind === 'step' || node.kind === 'loop')
784
+ count += countNodes(node.body);
785
+ else if (node.kind === 'branch')
786
+ for (const candidate of node.arms)
787
+ count += countNodes(candidate.nodes);
788
+ else if (node.kind === 'parallel')
789
+ for (const lane of node.lanes)
790
+ count += countNodes(lane);
791
+ }
792
+ return count;
793
+ };
794
+ /** Past the node budget the graph is withheld whole, never cut (FLOW-10). */
795
+ export const assertNodeBudget = (ctx, count) => {
796
+ if (count > ctx.limits.maxNodes)
797
+ throw new LimitReached(`the endpoints hold more than ${ctx.limits.maxNodes} calls`);
798
+ };
799
+ // Kept walks of one way to call a function: the variant, the step that wraps it, and the pipes after its body.
800
+ const memoOf = (ctx, fn, variant) => {
801
+ const step = fn.step === undefined ? '' : String(fn.step);
802
+ const key = `${variant}|${step}|${fn.pipes.map((pipe) => pipe.pos).join(',')}`;
803
+ const known = ctx.memo.get(key);
804
+ if (known !== undefined)
805
+ return known;
806
+ const created = new Map();
807
+ ctx.memo.set(key, created);
808
+ return created;
809
+ };
810
+ const functionBody = (ctx, fn, env, variant) => {
811
+ const body = fn.node.body;
812
+ if (body === undefined)
813
+ return [];
814
+ if (variant === 'evaluate') {
815
+ // A generator, or a function that Effect.fn or step.fn built, only builds its effect: nothing runs until that is yielded.
816
+ if (fn.lazy || isGenerator(fn.node))
817
+ return [];
818
+ return ts.isBlock(body) ? walkStatements(ctx, body.statements, env, 'evaluate', false).nodes : scan(ctx, body, env);
819
+ }
820
+ const strict = variant === 'strict';
821
+ if (!ts.isBlock(body))
822
+ return walkEffect(ctx, body, env, strict);
823
+ return walkStatements(ctx, body.statements, env, isGenerator(fn.node) ? 'generator' : 'plain', strict).nodes;
824
+ };
825
+ /**
826
+ * The calls of one call of a workflow function, with its body in place of the call. A function already
827
+ * being walked is a recursion: the graph marks it and does not unroll it (FLOW-10).
828
+ */
829
+ export function callFunction(ctx, fn, bindings, variant) {
830
+ tick(ctx);
831
+ if (ctx.stack.includes(fn.node))
832
+ return variant === 'evaluate' ? [] : [recursionInto(ctx, fn.node)];
833
+ const memo = memoOf(ctx, fn, variant);
834
+ const known = memo.get(fn.node);
835
+ if (known !== undefined)
836
+ return [...known];
837
+ const nodes = within(ctx, fn.node, () => {
838
+ const body = functionBody(ctx, fn, bindArguments(fn, bindings), variant);
839
+ if (variant === 'evaluate')
840
+ return body;
841
+ // The pipes after the body and the step around it belong to the function, so a recursion inside them is one too.
842
+ let piped = body;
843
+ for (const pipe of fn.pipes)
844
+ piped = applyPipe(ctx, { nodes: piped, value: UNKNOWN }, pipe, fn.pipesEnv);
845
+ const wrapped = fn.step === undefined ? piped : stepNodes(fn.step, piped);
846
+ return hasCalls(wrapped) ? wrapped : withoutRecursionInto(ctx, wrapped, fn.node);
847
+ });
848
+ // Checked for each function, so code that doubles its calls at every level stops before its lists grow.
849
+ assertNodeBudget(ctx, countNodes(nodes));
850
+ if (!ctx.lastDependent)
851
+ memo.set(fn.node, nodes);
852
+ return nodes;
853
+ }
854
+ // `default`, or `case:` and the text or number the clause tests for; a computed test is `case`.
855
+ const caseLabel = (ctx, clause, env) => {
856
+ if (ts.isDefaultClause(clause))
857
+ return 'default';
858
+ const tested = evaluate(ctx, clause.expression, env);
859
+ return tested.t === 'text' || tested.t === 'number' ? `case:${tested.value}` : 'case';
860
+ };
861
+ // `flow` as the statement that `jump` ends at: a path that leaves by it runs on to the statements after.
862
+ const endedAt = (flow, jump) => flow.jumps.has(jump) ? { nodes: flow.nodes, falls: true, jumps: jumpsPast(flow.jumps, [jump]) } : flow;
863
+ // `first`, then `second` on the paths of `first` that run on. Where a path of `first` can also leave, the paths are
864
+ // not kept apart: `second` is one arm beside an empty arm, so the graph can show a path that no Run takes.
865
+ const inOrder = (first, second) => {
866
+ if (!first.falls)
867
+ return first;
868
+ const skips = first.jumps.size > 0;
869
+ const after = skips ? branchOf([armOf(undefined, second.nodes), armOf(undefined, [])]) : second.nodes;
870
+ return { nodes: [...first.nodes, ...after], falls: second.falls, jumps: jumpsOf([first, second]) };
871
+ };
872
+ // `if` and `switch` as arms; `before` receives what the condition itself runs. Any other statement is `undefined`.
873
+ const branchArms = (ctx, statement, env, mode, strict, before) => {
874
+ if (ts.isIfStatement(statement)) {
875
+ before.push(...scan(ctx, statement.expression, env));
876
+ const then = walkStatements(ctx, [statement.thenStatement], env, mode, strict);
877
+ const otherwise = statement.elseStatement === undefined
878
+ ? EMPTY_FLOW
879
+ : walkStatements(ctx, [statement.elseStatement], env, mode, strict);
880
+ return [
881
+ { label: 'then', ...then },
882
+ { label: 'else', ...otherwise },
883
+ ];
884
+ }
885
+ if (!ts.isSwitchStatement(statement))
886
+ return undefined;
887
+ before.push(...scan(ctx, statement.expression, env));
888
+ const arms = [];
889
+ let next = EMPTY_FLOW;
890
+ for (const clause of statement.caseBlock.clauses.toReversed()) {
891
+ // A clause that does not leave runs on into the clause after it.
892
+ next = inOrder(walkStatements(ctx, clause.statements, env, mode, strict), next);
893
+ // `break` ends at the switch, so the code after the switch still runs. `continue` leaves the loop pass around it.
894
+ arms.unshift({ label: caseLabel(ctx, clause, env), ...endedAt(next, 'break') });
895
+ }
896
+ if (!statement.caseBlock.clauses.some(ts.isDefaultClause))
897
+ arms.push({ label: undefined, ...EMPTY_FLOW });
898
+ return arms;
899
+ };
900
+ const toArm = (flow) => armOf(flow.label, flow.nodes);
901
+ // The arms of an `if` or `switch` in which each arm either leaves or runs on, with `after`, the calls of the
902
+ // statements after it, in the arms that run on. The calls after a guard such as `if (skip) return;` are one arm.
903
+ const joinArms = (arms, after) => {
904
+ const staying = arms.filter((arm) => arm.falls);
905
+ const [only] = staying;
906
+ const merged = only !== undefined && staying.length === 1
907
+ ? armOf(only.label, [...only.nodes, ...after])
908
+ : armOf(undefined, [...branchOf(staying.map(toArm)), ...after]);
909
+ return branchOf(arms.flatMap((arm) => (!arm.falls ? [toArm(arm)] : arm === only ? [merged] : [])));
910
+ };
911
+ const walkLoop = (ctx, statement, env, mode, strict) => {
912
+ const out = [];
913
+ const body = [];
914
+ let jumps = NO_JUMPS;
915
+ const inner = () => {
916
+ const pass = walkStatements(ctx, [statement.statement], env, mode, strict);
917
+ // `break` and `continue` end at the loop. A `return` in a pass also skips the statements after the loop.
918
+ jumps = jumpsPast(pass.jumps, ['break', 'continue']);
919
+ return pass.nodes;
920
+ };
921
+ if (ts.isForStatement(statement)) {
922
+ if (statement.initializer !== undefined)
923
+ out.push(...scan(ctx, statement.initializer, env));
924
+ if (statement.condition !== undefined)
925
+ body.push(...scan(ctx, statement.condition, env));
926
+ body.push(...inner());
927
+ if (statement.incrementor !== undefined)
928
+ body.push(...scan(ctx, statement.incrementor, env));
929
+ }
930
+ else if (ts.isForOfStatement(statement) || ts.isForInStatement(statement)) {
931
+ out.push(...scan(ctx, statement.expression, env));
932
+ body.push(...inner());
933
+ }
934
+ else if (ts.isWhileStatement(statement)) {
935
+ body.push(...scan(ctx, statement.expression, env), ...inner());
936
+ }
937
+ else if (ts.isDoStatement(statement)) {
938
+ body.push(...inner(), ...scan(ctx, statement.expression, env));
939
+ }
940
+ out.push(...loopOf(body, undefined));
941
+ return { nodes: out, falls: true, jumps };
942
+ };
943
+ const walkTry = (ctx, statement, env, mode, strict) => {
944
+ const attempt = walkStatements(ctx, statement.tryBlock.statements, env, mode, strict);
945
+ const handler = statement.catchClause === undefined
946
+ ? undefined
947
+ : walkStatements(ctx, statement.catchClause.block.statements, env, mode, strict);
948
+ const last = statement.finallyBlock === undefined
949
+ ? undefined
950
+ : walkStatements(ctx, statement.finallyBlock.statements, env, mode, strict);
951
+ const nodes = [...attempt.nodes];
952
+ if (handler !== undefined)
953
+ nodes.push(...branchOf([armOf('catch', handler.nodes), armOf(undefined, [])]));
954
+ if (last !== undefined)
955
+ nodes.push(...last.nodes);
956
+ // A `finally` block that leaves on every path decides how the statement ends.
957
+ if (last !== undefined && !last.falls)
958
+ return { nodes, falls: false, jumps: last.jumps };
959
+ const blocks = [attempt, handler, last].filter((block) => block !== undefined);
960
+ return { nodes, falls: attempt.falls || handler?.falls === true, jumps: jumpsOf(blocks) };
961
+ };
962
+ // `Effect` constructors whose effect never succeeds.
963
+ const FAILURES = ['fail', 'failCause', 'failSync', 'failCauseSync', 'die'];
964
+ // Whether `expression` is a `yield*` of an effect that never succeeds, such as `yield* Effect.fail(error)`.
965
+ const neverSucceeds = (ctx, expression, env) => {
966
+ const node = unwrap(expression);
967
+ if (!ts.isYieldExpression(node) || node.asteriskToken === undefined || node.expression === undefined)
968
+ return false;
969
+ const effect = unwrap(node.expression);
970
+ return ts.isCallExpression(effect) && isEffectApi(evaluate(ctx, effect.expression, env), 'Effect', FAILURES);
971
+ };
972
+ const walkStatement = (ctx, statement, env, mode, strict) => {
973
+ tick(ctx);
974
+ if (ts.isBlock(statement))
975
+ return walkStatements(ctx, statement.statements, env, mode, strict);
976
+ if (ts.isLabeledStatement(statement)) {
977
+ // A jump to the label ends at the labeled statement, so the statements after it run.
978
+ return endedAt(walkStatements(ctx, [statement.statement], env, mode, strict), labelJump(statement.label));
979
+ }
980
+ if (ts.isVariableStatement(statement))
981
+ return runsOn(scan(ctx, statement.declarationList, env));
982
+ if (ts.isExpressionStatement(statement)) {
983
+ const nodes = scan(ctx, statement.expression, env);
984
+ // `yield* Effect.fail(error)` ends a generator as `return` does: the statements after it never run.
985
+ return neverSucceeds(ctx, statement.expression, env) ? leavesBy('function', nodes) : runsOn(nodes);
986
+ }
987
+ if (ts.isReturnStatement(statement)) {
988
+ const returned = statement.expression;
989
+ if (returned === undefined)
990
+ return leavesBy('function');
991
+ // A plain function returns the effect its caller runs; a generator returns a value.
992
+ return leavesBy('function', mode === 'plain' ? walkEffect(ctx, returned, env, strict) : scan(ctx, returned, env));
993
+ }
994
+ if (ts.isThrowStatement(statement))
995
+ return leavesBy('function', scan(ctx, statement.expression, env));
996
+ if (ts.isBreakStatement(statement) || ts.isContinueStatement(statement)) {
997
+ if (statement.label !== undefined)
998
+ return leavesBy(labelJump(statement.label));
999
+ return leavesBy(ts.isBreakStatement(statement) ? 'break' : 'continue');
1000
+ }
1001
+ if (ts.isTryStatement(statement))
1002
+ return walkTry(ctx, statement, env, mode, strict);
1003
+ if (ts.isIterationStatement(statement, false))
1004
+ return walkLoop(ctx, statement, env, mode, strict);
1005
+ return EMPTY_FLOW;
1006
+ };
1007
+ function walkStatements(ctx, statements, env, mode, strict) {
1008
+ const nodes = [];
1009
+ for (const [index, statement] of statements.entries()) {
1010
+ const arms = branchArms(ctx, statement, env, mode, strict, nodes);
1011
+ const flow = arms === undefined
1012
+ ? walkStatement(ctx, statement, env, mode, strict)
1013
+ : { nodes: branchOf(arms.map(toArm)), falls: arms.some((arm) => arm.falls), jumps: jumpsOf(arms) };
1014
+ if (flow.falls && flow.jumps.size === 0) {
1015
+ nodes.push(...flow.nodes);
1016
+ continue;
1017
+ }
1018
+ // A path of the statement left by a jump, so the statements after it run on its other paths only.
1019
+ const rest = flow.falls ? walkStatements(ctx, statements.slice(index + 1), env, mode, strict) : EMPTY_FLOW;
1020
+ const exact = arms !== undefined && arms.every((arm) => !arm.falls || arm.jumps.size === 0);
1021
+ const joined = exact
1022
+ ? { nodes: joinArms(arms, rest.nodes), falls: flow.falls && rest.falls, jumps: jumpsOf([flow, rest]) }
1023
+ : inOrder(flow, rest);
1024
+ return inOrder(runsOn(nodes), joined);
1025
+ }
1026
+ return runsOn(nodes);
1027
+ }
1028
+ //# sourceMappingURL=StaticGraphCalls.js.map