@dudko.dev/baton-format 0.1.2 → 0.3.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,22 @@
1
+ import { FlowStep } from "./types.js";
2
+ /**
3
+ * The shape of a flow's graph (ADR-0008, ADR-0009), shared by the parser's
4
+ * checks and the engine. The Dart twin is `baton_core`'s `flow_graph.dart`.
5
+ */
6
+ /** An entry of `after`: the step it names and, out of an If, a Switch or a Loop, the port. */
7
+ export interface FlowEdgeRef {
8
+ step: string;
9
+ port?: string;
10
+ }
11
+ /** Splits `check.true` into the step and the port. Step ids hold no dot, so the first one splits. */
12
+ export declare function edgeRef(ref: string): FlowEdgeRef;
13
+ /** The output ports of a step; empty for the kinds that have one plain output. */
14
+ export declare function portsOf(step: FlowStep): string[];
15
+ /** The step ids a step waits for, without ports. */
16
+ export declare function parentsOf(step: FlowStep): string[];
17
+ /** Every step's ancestors, through any edge. The flow must be acyclic. */
18
+ export declare function ancestorsOf(steps: FlowStep[]): Map<string, Set<string>>;
19
+ /** The steps that follow `edge` (`loop.each`, say), directly or through other steps. */
20
+ export declare function descendantsThrough(steps: FlowStep[], edge: string): Set<string>;
21
+ /** Loop id → the steps in its body, the ones that follow its `each` port. */
22
+ export declare function loopBodies(steps: FlowStep[]): Map<string, Set<string>>;
@@ -0,0 +1,70 @@
1
+ /** Splits `check.true` into the step and the port. Step ids hold no dot, so the first one splits. */
2
+ export function edgeRef(ref) {
3
+ const dot = ref.indexOf(".");
4
+ return dot < 0 ? { step: ref } : { step: ref.slice(0, dot), port: ref.slice(dot + 1) };
5
+ }
6
+ /** The output ports of a step; empty for the kinds that have one plain output. */
7
+ export function portsOf(step) {
8
+ switch (step.kind) {
9
+ case "if":
10
+ return ["true", "false"];
11
+ case "switch":
12
+ return [...Object.keys(step.switch.cases), "default"];
13
+ case "loop":
14
+ return ["each", "done"];
15
+ default:
16
+ return [];
17
+ }
18
+ }
19
+ /** The step ids a step waits for, without ports. */
20
+ export function parentsOf(step) {
21
+ return step.after.map((ref) => edgeRef(ref).step);
22
+ }
23
+ /** Every step's ancestors, through any edge. The flow must be acyclic. */
24
+ export function ancestorsOf(steps) {
25
+ const byId = new Map(steps.map((step) => [step.id, step]));
26
+ const out = new Map();
27
+ const visit = (id) => {
28
+ const known = out.get(id);
29
+ if (known !== undefined)
30
+ return known;
31
+ const set = new Set();
32
+ out.set(id, set);
33
+ for (const parent of parentsOf(byId.get(id))) {
34
+ set.add(parent);
35
+ for (const grand of visit(parent))
36
+ set.add(grand);
37
+ }
38
+ return set;
39
+ };
40
+ for (const step of steps)
41
+ visit(step.id);
42
+ return out;
43
+ }
44
+ /** The steps that follow `edge` (`loop.each`, say), directly or through other steps. */
45
+ export function descendantsThrough(steps, edge) {
46
+ const out = new Set();
47
+ let grew = true;
48
+ while (grew) {
49
+ grew = false;
50
+ for (const step of steps) {
51
+ if (out.has(step.id))
52
+ continue;
53
+ if (step.after.some((ref) => ref === edge || out.has(edgeRef(ref).step))) {
54
+ out.add(step.id);
55
+ grew = true;
56
+ }
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+ /** Loop id → the steps in its body, the ones that follow its `each` port. */
62
+ export function loopBodies(steps) {
63
+ const out = new Map();
64
+ for (const step of steps) {
65
+ if (step.kind === "loop")
66
+ out.set(step.id, descendantsThrough(steps, `${step.id}.each`));
67
+ }
68
+ return out;
69
+ }
70
+ //# sourceMappingURL=flow_graph.js.map
@@ -0,0 +1,115 @@
1
+ import { FlowFile } from "./types.js";
2
+ /**
3
+ * The execution semantics of a flow (ADR-0008, ADR-0009), with no I/O: which
4
+ * request steps are ready, which steps are skipped and why, what each request
5
+ * starts with, and what every step leaves behind. Log, If, Switch, Loop, Get
6
+ * and Set settle here, as soon as what they wait for has; a driver sends only
7
+ * the request steps and reports back through `finish`. The Dart twin is
8
+ * `baton_core`'s `flow_run.dart`; both replay `spec/fixtures/flows/`.
9
+ */
10
+ export type FlowStepOutcome = "pending" | "ready" | "running" | "passed" | "failed" | "skipped";
11
+ export type FlowSkipReason = "upstream-failed" | "upstream-skipped" | "branch" | "condition";
12
+ /** A loop walks at most this many items; a longer list fails it. */
13
+ export declare const FLOW_LOOP_LIMIT = 1000;
14
+ /** What sending a step returned. */
15
+ export interface FlowStepResult<C = string> {
16
+ /** HTTP status; absent when there was no response. */
17
+ status?: number;
18
+ bodyText?: string;
19
+ /** Transport, resolution or script error. */
20
+ error?: string;
21
+ failedTests?: number;
22
+ /** `baton.env.set` / `baton.vars.set` values from the step's scripts. */
23
+ overlays?: Record<string, string>;
24
+ setCookies?: C[];
25
+ }
26
+ /** What a request step is started with. */
27
+ export interface FlowStepStart<C = string> {
28
+ /** Runtime overlays for the runner: the run's start plus the ancestors' outputs. */
29
+ runtime: Record<string, string>;
30
+ /** The ancestors' `Set-Cookie`s, in topological order. */
31
+ cookies: C[];
32
+ /** Inside a loop's body: which item, from 0. */
33
+ iteration?: number;
34
+ }
35
+ /** What a step did: its outcome and what its kind leaves to show. */
36
+ export interface FlowStepRecord {
37
+ outcome: FlowStepOutcome;
38
+ reason?: FlowSkipReason;
39
+ /** Request steps: the response status. */
40
+ status?: number;
41
+ /** Get and Set: the variables written. */
42
+ values?: Record<string, string>;
43
+ /** Log: the message. */
44
+ message?: string;
45
+ /** If and Switch: the port taken. */
46
+ branch?: string;
47
+ /** Loop: how many items were walked. */
48
+ count?: number;
49
+ /** Loop: why it failed before walking. */
50
+ error?: string;
51
+ }
52
+ export declare class FlowRun<C = string> {
53
+ private readonly options;
54
+ private readonly steps;
55
+ private readonly byId;
56
+ private readonly state;
57
+ /** Every step, in topological order with ties broken by id. */
58
+ private readonly order;
59
+ private readonly ancestors;
60
+ private readonly bodies;
61
+ private readonly loopOf;
62
+ /** Request steps a Get reads: only their bodies are kept. */
63
+ private readonly read;
64
+ private readonly iterations;
65
+ constructor(flow: FlowFile, options?: {
66
+ variables?: Record<string, string>;
67
+ runtime?: Record<string, string>;
68
+ });
69
+ /** Request steps to send now, in file order. */
70
+ ready(): string[];
71
+ /** Marks a ready request step running and returns what to send it with. */
72
+ start(id: string): FlowStepStart<C>;
73
+ /** Records a running step's result and settles whatever that decides. */
74
+ finish(id: string, result: FlowStepResult<C>): void;
75
+ outcome(id: string): FlowStepOutcome;
76
+ reason(id: string): FlowSkipReason | undefined;
77
+ /** What the step did — inside a loop's body, in the latest iteration. */
78
+ record(id: string): FlowStepRecord;
79
+ /** A body step's record for every iteration that has finished, in order. */
80
+ history(id: string): FlowStepRecord[];
81
+ /** A loop's place: the item being walked, from 0, and how many there are. */
82
+ progress(id: string): {
83
+ index: number;
84
+ count: number;
85
+ } | undefined;
86
+ get done(): boolean;
87
+ /** False when a step failed without `continueOnFailure`. */
88
+ get ok(): boolean;
89
+ /** What the run leaves for the session: overlays, then Get and Set values, in topological order. */
90
+ get runtime(): Record<string, string>;
91
+ private mustBe;
92
+ /** Settles steps and walks loops until nothing changes. */
93
+ private advance;
94
+ private skip;
95
+ /** Whether an edge carries the flow on, given where its source stands. */
96
+ private edgeState;
97
+ /** A step whose edges carry the flow to it: a request is ready, every other kind settles now. */
98
+ private settle;
99
+ /** An iteration has settled: keep its records, then walk the next item or end. */
100
+ private nextItem;
101
+ private scopeFor;
102
+ /** What a condition or a template reads: the environment's variables, then the step's scope. */
103
+ private templateScope;
104
+ private cookiesFor;
105
+ }
106
+ /** A driver called the run out of order: a bug in the caller, not in the flow. */
107
+ export declare class FlowRunError extends Error {
108
+ name: string;
109
+ }
110
+ /** `{{name}}` from the scope; unknown names and every secret read as empty. */
111
+ export declare function render(template: string, scope: Record<string, string>): string;
112
+ /** Evaluates a step condition against a variable scope (spec/fixtures/flows/README.md). */
113
+ export declare function evaluateWhen(condition: string, scope: Record<string, string>): boolean;
114
+ /** Takes each dotted path out of a JSON body; what is missing is left out. */
115
+ export declare function capture(paths: Record<string, string>, bodyText: string | undefined): Record<string, string>;
@@ -0,0 +1,465 @@
1
+ import { ancestorsOf, edgeRef, loopBodies, parentsOf } from "./flow_graph.js";
2
+ /** A loop walks at most this many items; a longer list fails it. */
3
+ export const FLOW_LOOP_LIMIT = 1000;
4
+ const TEMPLATE = /\{\{\s*([^{}]+?)\s*\}\}/g;
5
+ const FALSY = new Set(["", "false", "0", "null", "undefined"]);
6
+ function fresh() {
7
+ return { outcome: "pending", overlays: {}, values: {}, setCookies: [], itemVars: {} };
8
+ }
9
+ export class FlowRun {
10
+ options;
11
+ steps;
12
+ byId = new Map();
13
+ state = new Map();
14
+ /** Every step, in topological order with ties broken by id. */
15
+ order;
16
+ ancestors;
17
+ bodies;
18
+ loopOf = new Map();
19
+ /** Request steps a Get reads: only their bodies are kept. */
20
+ read = new Set();
21
+ iterations = new Map();
22
+ constructor(flow, options = {}) {
23
+ this.options = options;
24
+ this.steps = flow.steps;
25
+ for (const step of this.steps) {
26
+ this.byId.set(step.id, step);
27
+ this.state.set(step.id, fresh());
28
+ if (step.kind === "get")
29
+ this.read.add(step.get.from);
30
+ }
31
+ this.order = topologicalOrder(this.steps);
32
+ this.ancestors = ancestorsOf(this.steps);
33
+ this.bodies = loopBodies(this.steps);
34
+ for (const [loop, body] of this.bodies) {
35
+ for (const id of body) {
36
+ this.loopOf.set(id, loop);
37
+ this.iterations.set(id, []);
38
+ }
39
+ }
40
+ this.advance();
41
+ }
42
+ /** Request steps to send now, in file order. */
43
+ ready() {
44
+ return this.steps.filter((step) => this.state.get(step.id).outcome === "ready").map((step) => step.id);
45
+ }
46
+ /** Marks a ready request step running and returns what to send it with. */
47
+ start(id) {
48
+ const state = this.mustBe(id, "ready");
49
+ state.outcome = "running";
50
+ const loop = this.loopOf.get(id);
51
+ return {
52
+ runtime: this.scopeFor(id),
53
+ cookies: this.cookiesFor(id),
54
+ ...(loop !== undefined ? { iteration: this.state.get(loop).index } : {}),
55
+ };
56
+ }
57
+ /** Records a running step's result and settles whatever that decides. */
58
+ finish(id, result) {
59
+ const state = this.mustBe(id, "running");
60
+ const step = this.byId.get(id);
61
+ state.status = result.status;
62
+ if (this.read.has(id) && result.status !== undefined)
63
+ state.bodyText = result.bodyText ?? "";
64
+ state.overlays = { ...(result.overlays ?? {}) };
65
+ state.setCookies = [...(result.setCookies ?? [])];
66
+ const failed = result.error !== undefined ||
67
+ result.status === undefined ||
68
+ (result.failedTests ?? 0) > 0 ||
69
+ !accepts(step, result.status);
70
+ state.outcome = failed ? "failed" : "passed";
71
+ this.advance();
72
+ }
73
+ outcome(id) {
74
+ return this.state.get(id).outcome;
75
+ }
76
+ reason(id) {
77
+ return this.state.get(id).reason;
78
+ }
79
+ /** What the step did — inside a loop's body, in the latest iteration. */
80
+ record(id) {
81
+ const step = this.byId.get(id);
82
+ const state = this.state.get(id);
83
+ const out = { outcome: state.outcome };
84
+ if (state.outcome === "skipped") {
85
+ out.reason = state.reason;
86
+ return out;
87
+ }
88
+ switch (step.kind) {
89
+ case "request":
90
+ if (state.status !== undefined)
91
+ out.status = state.status;
92
+ break;
93
+ case "get":
94
+ case "set":
95
+ if (isSettled(state.outcome))
96
+ out.values = { ...state.values };
97
+ break;
98
+ case "log":
99
+ if (state.message !== undefined)
100
+ out.message = state.message;
101
+ break;
102
+ case "if":
103
+ case "switch":
104
+ if (state.branch !== undefined)
105
+ out.branch = state.branch;
106
+ break;
107
+ case "loop":
108
+ if (state.count !== undefined)
109
+ out.count = state.count;
110
+ if (state.error !== undefined)
111
+ out.error = state.error;
112
+ break;
113
+ }
114
+ return out;
115
+ }
116
+ /** A body step's record for every iteration that has finished, in order. */
117
+ history(id) {
118
+ return [...(this.iterations.get(id) ?? [])];
119
+ }
120
+ /** A loop's place: the item being walked, from 0, and how many there are. */
121
+ progress(id) {
122
+ const state = this.state.get(id);
123
+ if (state.items === undefined)
124
+ return undefined;
125
+ return { index: state.index ?? state.count ?? 0, count: state.items.length };
126
+ }
127
+ get done() {
128
+ return [...this.state.values()].every((s) => isSettled(s.outcome));
129
+ }
130
+ /** False when a step failed without `continueOnFailure`. */
131
+ get ok() {
132
+ return this.steps.every((step) => this.state.get(step.id).outcome !== "failed" || step.continueOnFailure);
133
+ }
134
+ /** What the run leaves for the session: overlays, then Get and Set values, in topological order. */
135
+ get runtime() {
136
+ const out = { ...(this.options.runtime ?? {}) };
137
+ for (const id of this.order) {
138
+ const state = this.state.get(id);
139
+ Object.assign(out, state.overlays, state.values);
140
+ }
141
+ return out;
142
+ }
143
+ // MARK: - Internals
144
+ mustBe(id, outcome) {
145
+ const state = this.state.get(id);
146
+ if (state === undefined)
147
+ throw new FlowRunError(`no step "${id}"`);
148
+ if (state.outcome !== outcome) {
149
+ throw new FlowRunError(`step "${id}" is ${state.outcome}, not ${outcome}`);
150
+ }
151
+ return state;
152
+ }
153
+ /** Settles steps and walks loops until nothing changes. */
154
+ advance() {
155
+ let changed = true;
156
+ while (changed) {
157
+ changed = false;
158
+ for (const step of this.steps) {
159
+ const state = this.state.get(step.id);
160
+ if (state.outcome !== "pending")
161
+ continue;
162
+ const edges = step.after.map((ref) => this.edgeState(ref));
163
+ if (edges.includes("pending"))
164
+ continue;
165
+ changed = true;
166
+ if (edges.includes("failed")) {
167
+ this.skip(state, "upstream-failed");
168
+ }
169
+ else if (edges.length > 0 && edges.every((e) => e === "dead" || e === "branch")) {
170
+ this.skip(state, edges.includes("branch") ? "branch" : "upstream-skipped");
171
+ }
172
+ else if (step.when !== undefined && !evaluateWhen(step.when, this.templateScope(step.id))) {
173
+ this.skip(state, "condition");
174
+ }
175
+ else {
176
+ this.settle(step, state);
177
+ }
178
+ }
179
+ for (const [loop, body] of this.bodies) {
180
+ const state = this.state.get(loop);
181
+ if (state.outcome !== "running")
182
+ continue;
183
+ if (![...body].every((id) => isSettled(this.state.get(id).outcome)))
184
+ continue;
185
+ this.nextItem(loop, body, state);
186
+ changed = true;
187
+ }
188
+ }
189
+ }
190
+ skip(state, reason) {
191
+ state.outcome = "skipped";
192
+ state.reason = reason;
193
+ }
194
+ /** Whether an edge carries the flow on, given where its source stands. */
195
+ edgeState(ref) {
196
+ const { step: id, port } = edgeRef(ref);
197
+ const source = this.byId.get(id);
198
+ const state = this.state.get(id);
199
+ switch (state.outcome) {
200
+ case "pending":
201
+ case "ready":
202
+ return "pending";
203
+ case "running":
204
+ return source.kind === "loop" && port === "each" && state.index !== undefined ? "live" : "pending";
205
+ case "skipped":
206
+ return "dead";
207
+ case "failed":
208
+ if (!source.continueOnFailure)
209
+ return "failed";
210
+ if (source.kind === "loop")
211
+ return port === "done" ? "live" : "branch";
212
+ return "live";
213
+ case "passed":
214
+ if (port === undefined)
215
+ return "live";
216
+ if (source.kind === "loop")
217
+ return port === "done" ? "live" : "branch";
218
+ return state.branch === port ? "live" : "branch";
219
+ }
220
+ }
221
+ /** A step whose edges carry the flow to it: a request is ready, every other kind settles now. */
222
+ settle(step, state) {
223
+ switch (step.kind) {
224
+ case "request":
225
+ state.outcome = "ready";
226
+ return;
227
+ case "log":
228
+ state.message = render(step.log, this.templateScope(step.id));
229
+ break;
230
+ case "set": {
231
+ const scope = this.templateScope(step.id);
232
+ state.values = Object.fromEntries(Object.entries(step.set).map(([name, template]) => [name, render(template, scope)]));
233
+ break;
234
+ }
235
+ case "get":
236
+ state.values = capture(step.get.values, this.state.get(step.get.from).bodyText);
237
+ break;
238
+ case "if":
239
+ state.branch = evaluateWhen(step.if, this.templateScope(step.id)) ? "true" : "false";
240
+ break;
241
+ case "switch": {
242
+ const scope = this.templateScope(step.id);
243
+ const value = render(step.switch.value, scope).trim();
244
+ const match = Object.entries(step.switch.cases).find(([, candidate]) => render(candidate, scope).trim() === value);
245
+ state.branch = match?.[0] ?? "default";
246
+ break;
247
+ }
248
+ case "loop": {
249
+ const text = render(step.loop.items, this.templateScope(step.id));
250
+ let items;
251
+ try {
252
+ items = JSON.parse(text);
253
+ }
254
+ catch {
255
+ items = undefined;
256
+ }
257
+ if (!Array.isArray(items)) {
258
+ state.error = "items is not a JSON list";
259
+ state.outcome = "failed";
260
+ return;
261
+ }
262
+ if (items.length > FLOW_LOOP_LIMIT) {
263
+ state.error = `${items.length} items; a loop walks at most ${FLOW_LOOP_LIMIT}`;
264
+ state.outcome = "failed";
265
+ return;
266
+ }
267
+ state.items = items;
268
+ state.count = 0;
269
+ if (items.length === 0)
270
+ break;
271
+ state.index = 0;
272
+ state.itemVars = itemVariables(items[0], 0);
273
+ state.outcome = "running";
274
+ return;
275
+ }
276
+ }
277
+ state.outcome = "passed";
278
+ }
279
+ /** An iteration has settled: keep its records, then walk the next item or end. */
280
+ nextItem(loop, body, state) {
281
+ for (const id of body)
282
+ this.iterations.get(id).push(this.record(id));
283
+ state.count = state.index + 1;
284
+ const failed = [...body].some((id) => this.state.get(id).outcome === "failed" && !this.byId.get(id).continueOnFailure);
285
+ const next = state.index + 1;
286
+ if (!failed && next < state.items.length) {
287
+ state.index = next;
288
+ state.itemVars = itemVariables(state.items[next], next);
289
+ for (const id of body)
290
+ this.state.set(id, fresh());
291
+ return;
292
+ }
293
+ state.index = undefined;
294
+ state.itemVars = {};
295
+ state.outcome = failed ? "failed" : "passed";
296
+ void loop;
297
+ }
298
+ scopeFor(id) {
299
+ const out = { ...(this.options.runtime ?? {}) };
300
+ const ancestors = this.ancestors.get(id);
301
+ for (const ancestor of this.order) {
302
+ if (!ancestors.has(ancestor))
303
+ continue;
304
+ const state = this.state.get(ancestor);
305
+ Object.assign(out, state.overlays, state.values, state.itemVars);
306
+ out[`steps.${ancestor}.status`] = state.status === undefined ? "" : String(state.status);
307
+ out[`steps.${ancestor}.outcome`] = state.outcome;
308
+ }
309
+ return out;
310
+ }
311
+ /** What a condition or a template reads: the environment's variables, then the step's scope. */
312
+ templateScope(id) {
313
+ return { ...(this.options.variables ?? {}), ...this.scopeFor(id) };
314
+ }
315
+ cookiesFor(id) {
316
+ const ancestors = this.ancestors.get(id);
317
+ return this.order
318
+ .filter((ancestor) => ancestors.has(ancestor))
319
+ .flatMap((ancestor) => this.state.get(ancestor).setCookies);
320
+ }
321
+ }
322
+ /** A driver called the run out of order: a bug in the caller, not in the flow. */
323
+ export class FlowRunError extends Error {
324
+ name = "FlowRunError";
325
+ }
326
+ function isSettled(outcome) {
327
+ return outcome === "passed" || outcome === "failed" || outcome === "skipped";
328
+ }
329
+ function accepts(step, status) {
330
+ const expected = step.expect?.status;
331
+ if (expected === undefined)
332
+ return status < 400;
333
+ if (typeof expected === "number")
334
+ return status === expected;
335
+ return `${Math.floor(status / 100)}xx` === expected;
336
+ }
337
+ /** Kahn's algorithm, always taking the smallest id among the ready ones. */
338
+ function topologicalOrder(steps) {
339
+ const parents = new Map(steps.map((step) => [step.id, parentsOf(step)]));
340
+ const waiting = new Map(steps.map((step) => [step.id, parents.get(step.id).length]));
341
+ const ready = steps.filter((step) => step.after.length === 0).map((step) => step.id);
342
+ const order = [];
343
+ while (ready.length > 0) {
344
+ ready.sort(compareIds);
345
+ const id = ready.shift();
346
+ order.push(id);
347
+ for (const step of steps) {
348
+ for (const parent of parents.get(step.id)) {
349
+ if (parent !== id)
350
+ continue;
351
+ const left = waiting.get(step.id) - 1;
352
+ waiting.set(step.id, left);
353
+ if (left === 0)
354
+ ready.push(step.id);
355
+ }
356
+ }
357
+ }
358
+ return order;
359
+ }
360
+ /** Code-unit order, which Dart's `compareTo` on strings also uses. */
361
+ function compareIds(a, b) {
362
+ return a < b ? -1 : a > b ? 1 : 0;
363
+ }
364
+ /** `{{name}}` from the scope; unknown names and every secret read as empty. */
365
+ export function render(template, scope) {
366
+ return template.replace(TEMPLATE, (_, name) => {
367
+ if (name.startsWith("secret:"))
368
+ return "";
369
+ return Object.prototype.hasOwnProperty.call(scope, name) ? scope[name] : "";
370
+ });
371
+ }
372
+ /** `item`, every `item.<path>` into it, and `index`. */
373
+ function itemVariables(item, index) {
374
+ const out = { index: String(index) };
375
+ const put = (name, value) => {
376
+ if (value === undefined || value === null)
377
+ return;
378
+ out[name] = typeof value === "string" ? value : canonicalJson(value);
379
+ if (typeof value === "object") {
380
+ for (const [key, inner] of Object.entries(value))
381
+ put(`${name}.${key}`, inner);
382
+ }
383
+ };
384
+ put("item", item);
385
+ return out;
386
+ }
387
+ // MARK: - `when`
388
+ /** Evaluates a step condition against a variable scope (spec/fixtures/flows/README.md). */
389
+ export function evaluateWhen(condition, scope) {
390
+ const text = condition.trim();
391
+ const equals = text.indexOf(" == ");
392
+ const differs = text.indexOf(" != ");
393
+ const at = [equals, differs].filter((i) => i >= 0).sort((a, b) => a - b)[0];
394
+ if (at !== undefined) {
395
+ const left = operand(text.slice(0, at), scope);
396
+ const right = operand(text.slice(at + 4), scope);
397
+ return at === equals ? left === right : left !== right;
398
+ }
399
+ if (text.startsWith("!"))
400
+ return !truthy(operand(text.slice(1), scope));
401
+ return truthy(operand(text, scope));
402
+ }
403
+ function operand(raw, scope) {
404
+ let text = raw.trim();
405
+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"'))
406
+ text = text.slice(1, -1);
407
+ return render(text, scope);
408
+ }
409
+ function truthy(value) {
410
+ return !FALSY.has(value.trim());
411
+ }
412
+ // MARK: - Captures
413
+ /** Takes each dotted path out of a JSON body; what is missing is left out. */
414
+ export function capture(paths, bodyText) {
415
+ const out = {};
416
+ if (Object.keys(paths).length === 0 || bodyText === undefined)
417
+ return out;
418
+ let body;
419
+ try {
420
+ body = JSON.parse(bodyText);
421
+ }
422
+ catch {
423
+ return out;
424
+ }
425
+ for (const [name, path] of Object.entries(paths)) {
426
+ const value = walk(body, path.split("."));
427
+ if (value === undefined || value === null)
428
+ continue;
429
+ out[name] = typeof value === "string" ? value : canonicalJson(value);
430
+ }
431
+ return out;
432
+ }
433
+ function walk(value, segments) {
434
+ let current = value;
435
+ for (const segment of segments) {
436
+ if (Array.isArray(current)) {
437
+ if (!/^(0|[1-9]\d*)$/.test(segment))
438
+ return undefined;
439
+ current = current[Number(segment)];
440
+ }
441
+ else if (current !== null && typeof current === "object") {
442
+ if (!Object.prototype.hasOwnProperty.call(current, segment))
443
+ return undefined;
444
+ current = current[segment];
445
+ }
446
+ else {
447
+ return undefined;
448
+ }
449
+ }
450
+ return current;
451
+ }
452
+ /** Compact JSON with one number rule both languages can keep: a whole number has no fraction. */
453
+ function canonicalJson(value) {
454
+ if (typeof value === "number")
455
+ return String(value);
456
+ if (Array.isArray(value))
457
+ return `[${value.map(canonicalJson).join(",")}]`;
458
+ if (value !== null && typeof value === "object") {
459
+ return `{${Object.entries(value)
460
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`)
461
+ .join(",")}}`;
462
+ }
463
+ return JSON.stringify(value);
464
+ }
465
+ //# sourceMappingURL=flow_run.js.map
@@ -1,4 +1,7 @@
1
1
  export * from "./types.js";
2
2
  export { FormatError, type FormatErrorCode } from "./errors.js";
3
- export { parseRequestFile, parseCollectionFile, parseEnvironmentFile, parseWorkspaceManifest, parseSchedulesFile, } from "./parse.js";
4
- export { serializeRequestFile, serializeCollectionFile, serializeEnvironmentFile, serializeWorkspaceManifest, serializeSchedulesFile, } from "./serialize.js";
3
+ export { parseRequestFile, parseCollectionFile, parseEnvironmentFile, parseWorkspaceManifest, parseSchedulesFile, parseExamplesFile, parseMockFile, parseFlowFile, } from "./parse.js";
4
+ export { serializeRequestFile, serializeCollectionFile, serializeEnvironmentFile, serializeWorkspaceManifest, serializeSchedulesFile, serializeExamplesFile, serializeMockFile, serializeFlowFile, } from "./serialize.js";
5
+ export { parseVaultRef, formatVaultRef, type VaultRef } from "./vault.js";
6
+ export { FLOW_LOOP_LIMIT, FlowRun, FlowRunError, capture, evaluateWhen, render, type FlowSkipReason, type FlowStepOutcome, type FlowStepRecord, type FlowStepResult, type FlowStepStart, } from "./flow_run.js";
7
+ export { ancestorsOf, edgeRef, loopBodies, parentsOf, portsOf, type FlowEdgeRef } from "./flow_graph.js";