@jeffawe/understudy 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,43 @@
2
2
 
3
3
  What changed in each release of `@jeffawe/understudy`. Newest first.
4
4
 
5
+ ## 0.6.0 — 2026-12-01
6
+
7
+ **Upgrade every machine that shares a database.** Steps get ids the first time
8
+ a newer version opens it, and flows can carry `vars` and `extends`, which
9
+ older versions ignore.
10
+
11
+ ### Added
12
+ - **Step edits.** `understudy_save { flow, edit }` (and `understudy edit --at
13
+ … --set '{…}' | --remove`) changes a saved step's fields or removes it, so a
14
+ repair is one call. Steps are named by index or by id; a flow is replayed
15
+ straight after, and is unproven until a run passes.
16
+ - **Step ids.** Every step has a short `id` (recall shows it) that stays with
17
+ it when steps around it change, and when the flow is saved again.
18
+ - **Variables.** A step's `name` or `value` can hold `{{bundle}}`, with the
19
+ flow's default in `vars` (the value it was proven with). A run passes
20
+ `values: {"bundle": "Starter"}` to use another. Runs with other values are
21
+ kept apart in history, don't prove the flow, and a failure says which values
22
+ it used. `understudy_save { flow, vars }` / `--var bundle=Family` sets them.
23
+ - **Flows that extend another.** Saving with `extends: "<flow>"` keeps that
24
+ flow's steps by reference and adds the recording's own between them. When
25
+ that flow changes, every flow extending it is rebuilt and must be proven
26
+ again; one whose own steps lost their place says so instead of guessing.
27
+ One level only, and only adding. Segments cut from it follow the rebuild.
28
+ - **Variables in scripts.** Script import reads `` `${bundle} bundle` `` and a
29
+ bare `bundle` as a variable, defaulting to the script's own
30
+ `const bundle = 'Family'`. `emit` writes them back the same way, so an
31
+ exported test reads back as the same flow.
32
+
33
+ ### Changed
34
+ - A run with other values than the defaults doesn't expect the flow's
35
+ recorded pages from the first step those values change, so it doesn't
36
+ report pages it was never going to see.
37
+ - A run says which `values` no step used (`ignoredValues`), usually a misspelt
38
+ variable.
39
+ - Shorter descriptions on `understudy_calibrate`, `understudy_findings` and
40
+ `understudy_session` to make room under the tool size limit.
41
+
5
42
  ## 0.5.1 — 2026-12-01
6
43
 
7
44
  ### Fixed
package/REASONER.md CHANGED
@@ -6,9 +6,12 @@ remembers. It calls no model: you answer its questions.
6
6
  ## Rules
7
7
 
8
8
  - **Recall first.** `understudy_recall` is free and runs nothing. It returns a
9
- flow's steps, the login values they need (`needs`), and whether it's
10
- **stale** (last run failed, or passed on a path nobody accepted; `why`,
11
- `pagesChanged`). Check a stale step before trusting it.
9
+ flow's steps (each with an `id`), the login values they need (`needs`), its
10
+ `{{variables}}` and their defaults (`vars`), and whether it's **stale** (last
11
+ run failed, or passed on a path nobody accepted; `why`, `pagesChanged`).
12
+ Check a stale step before trusting it.
13
+ - **Another value?** Pass it in `values` (`{"bundle": "Starter"}`); unpassed
14
+ variables use their defaults. One run per value.
12
15
  - **Reach the goal however works** (`understudy_run` or your own browser) and
13
16
  **say which you used**. Never imply Understudy ran what you drove.
14
17
  - **Never ask for a password in chat.** Steps name `SECRET.password`; the value
@@ -55,7 +58,10 @@ Save what the user would test again; a one-off is enough as facts.
55
58
 
56
59
  | To | Call |
57
60
  | --- | --- |
61
+ | Fix a step you know is wrong | `understudy_save { flow, edit: [{ at, set }] }` (`at`: index or id; `null` clears a field) or `{ at, remove: true }`; it replays at once |
58
62
  | Repair a stale one | `understudy_session { flow }` stops at the failing step; fix it, save under the same name |
63
+ | Make a value a variable | `edit` the step's `name` or `value` to `"{{bundle}}"` and pass `vars: {"bundle": "Family"}`, the value it was recorded with |
64
+ | Make a follow-up of a flow | save the whole path with `extends: "<flow>"`: it keeps that flow's steps by reference, and adds only its own (one level; never removes). Steps marked `from` are that flow's: change them there |
59
65
  | Add a wait, check or person's step | `understudy_save { flow, add }` |
60
66
  | Prove it as it stands | `understudy_save { flow }` |
61
67
  | Keep a branch's version | any save with `variant`; when merged, `promote: true`; `drop: true` deletes the copy |
@@ -75,7 +81,8 @@ Runs and seam answers add history and page links on their own.
75
81
  ## Traps
76
82
 
77
83
  - **File uploads can't be recorded**: write a script.
78
- - **In a script**, a person's step is `human('what they do', { untilText |
84
+ - **In a script**, `` `${bundle} bundle` `` with `const bundle = 'Family'` is
85
+ a variable defaulting to Family. A person's step is `human('what they do', { untilText |
79
86
  untilUrl | untilResponse })`; a server-only result is `page.waitForResponse`
80
87
  (or a `wait_response` step with `field` and `equals` / `above`).
81
88
  - **Irreversible but the words don't say so?** It would run when saved: first
@@ -26,6 +26,7 @@ import { readFile } from 'node:fs/promises';
26
26
  import { existsSync } from 'node:fs';
27
27
  import { basename, dirname, isAbsolute, join } from 'node:path';
28
28
  import ts from 'typescript';
29
+ import { VAR_NAME, varsOf } from '../../core/vars.js';
29
30
  import { buildRecording, redactValue, } from '../../core/recording.js';
30
31
  const NAME_LOOKUPS = {
31
32
  getByPlaceholder: 'placeholder',
@@ -137,6 +138,35 @@ function scrollContainerFrom(node) {
137
138
  return undefined;
138
139
  }
139
140
  const text = (node) => ts.isStringLiteralLike(node) ? node.text : undefined;
141
+ /**
142
+ * `` `${bundle} bundle` `` → `{{bundle}} bundle`: a flow variable (core/vars.ts),
143
+ * when every `${…}` is a plain name. Its default comes from the script's own
144
+ * `const bundle = 'Family'` (see literalConsts). Anything cleverer is not read.
145
+ */
146
+ function templateText(node) {
147
+ if (!ts.isTemplateExpression(node))
148
+ return undefined;
149
+ let out = node.head.text;
150
+ for (const span of node.templateSpans) {
151
+ if (!ts.isIdentifier(span.expression) || !VAR_NAME.test(span.expression.text))
152
+ return undefined;
153
+ out += `{{${span.expression.text}}}${span.literal.text}`;
154
+ }
155
+ return out;
156
+ }
157
+ /** `const bundle = 'Family'` anywhere in the script: names with a literal value, the defaults of its variables. */
158
+ function literalConsts(file) {
159
+ const out = new Map();
160
+ const visit = (node) => {
161
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && ts.isStringLiteralLike(node.initializer)
162
+ && ts.isVariableDeclarationList(node.parent) && (node.parent.flags & ts.NodeFlags.Const)) {
163
+ out.set(node.name.text, node.initializer.text);
164
+ }
165
+ ts.forEachChild(node, visit);
166
+ };
167
+ visit(file);
168
+ return out;
169
+ }
140
170
  /** Join a possibly-relative spec URL onto the app's base URL. */
141
171
  function absolute(url, base) {
142
172
  try {
@@ -203,6 +233,9 @@ function textMatch(node) {
203
233
  return undefined;
204
234
  if (ts.isStringLiteralLike(node))
205
235
  return { source: node.text, regex: false, flags: '' };
236
+ const templated = templateText(node);
237
+ if (templated !== undefined)
238
+ return { source: templated, regex: false, flags: '' };
206
239
  if (ts.isRegularExpressionLiteral(node)) {
207
240
  // getText() is the literal as written, e.g. `/^No$/i`.
208
241
  const raw = node.getText();
@@ -334,12 +367,15 @@ function locatorBit(method, args) {
334
367
  * `fill(MEMBER.email)` → valueRef 'MEMBER.email' ← already the IR shape
335
368
  * `fill(process.env.SHOP_PASSWORD!)` → valueRef 'ENV.SHOP_PASSWORD'
336
369
  */
337
- function readArgument(arg) {
370
+ function readArgument(arg, consts = new Map()) {
338
371
  if (!arg)
339
372
  return {};
340
- const literal = text(arg);
373
+ const literal = text(arg) ?? templateText(arg);
341
374
  if (literal !== undefined)
342
375
  return { value: literal };
376
+ // `fill(member)` with `const member = 'Ada'` in the script: a variable, defaulting to that.
377
+ if (ts.isIdentifier(arg) && consts.has(arg.text) && VAR_NAME.test(arg.text))
378
+ return { value: `{{${arg.text}}}` };
343
379
  // A script reading its own environment — what an agent's script usually
344
380
  // does for a password. Every spelling of it becomes ENV.<NAME>, whose value
345
381
  // is then found under that same variable at replay (store/settings.ts).
@@ -408,7 +444,7 @@ function selectedOption(arg) {
408
444
  return undefined;
409
445
  if (prop.name.text !== 'label' && prop.name.text !== 'value')
410
446
  return undefined;
411
- return text(prop.initializer);
447
+ return text(prop.initializer) ?? templateText(prop.initializer);
412
448
  }
413
449
  /** `process.env.X`, `process.env.X!`, `process.env['X']`, `process.env.X ?? ''` → 'X'. */
414
450
  function envVariable(arg) {
@@ -576,6 +612,7 @@ export function parseScriptSource(source, filePath, appSlug, fallbackUrl) {
576
612
  const events = [];
577
613
  const warnings = [];
578
614
  const dropped = [];
615
+ const consts = literalConsts(sourceFile);
579
616
  // A static read cannot know which page it is on, so the last goto (or literal
580
617
  // URL wait) stands in. Anything before the first goto is attributed to the
581
618
  // fallback URL. It is a guess: the first replay that passes replaces it with
@@ -648,7 +685,7 @@ export function parseScriptSource(source, filePath, appSlug, fallbackUrl) {
648
685
  }
649
686
  }
650
687
  else if (arg && !ts.isArrayLiteralExpression(arg)) {
651
- valued = readArgument(arg);
688
+ valued = readArgument(arg, consts);
652
689
  }
653
690
  else {
654
691
  return drop(`${kind} check with no single expected value, not kept`, node);
@@ -922,7 +959,7 @@ export function parseScriptSource(source, filePath, appSlug, fallbackUrl) {
922
959
  warnings.push(`${method}() with ${ts.isArrayLiteralExpression(first) ? 'several values' : 'an options object'} cannot be represented: ${snippet(node)}`);
923
960
  }
924
961
  else
925
- raw = readArgument(first);
962
+ raw = readArgument(first, consts);
926
963
  }
927
964
  const fieldHint = merged.name?.source || merged.testId || merged.css || 'field';
928
965
  const secretSignal = [merged.name?.source, merged.css, merged.testId].filter(Boolean).join(' ');
@@ -960,8 +997,15 @@ export function parseScriptSource(source, filePath, appSlug, fallbackUrl) {
960
997
  visit(sourceFile);
961
998
  for (const [name, call] of deferred)
962
999
  refuse(`waitForResponse() kept in "${name}" but never awaited`, call);
1000
+ // A variable is filled in a step's own name or value only — not in a locator it's scoped by.
1001
+ for (const e of events) {
1002
+ if (e.hints && JSON.stringify(e.hints).includes('{{'))
1003
+ warnings.push(`a \${…} in a filter or an outer locator can't be a variable — only in the element's own name, or a value: ${e.action} ${e.name ?? ''}`.trim());
1004
+ }
1005
+ // Defaults for its variables: the script's own literal consts. One with none is asked for when saved.
1006
+ const used = varsOf(events).filter((v) => consts.has(v));
963
1007
  return {
964
- recording: buildRecording({ source: 'script', origin: filePath, appSlug, startUrl }, events.map((e, i) => ({ ...e, seq: i }))),
1008
+ recording: buildRecording({ source: 'script', origin: filePath, appSlug, startUrl, ...(used.length ? { vars: Object.fromEntries(used.map((v) => [v, consts.get(v)])) } : {}) }, events.map((e, i) => ({ ...e, seq: i }))),
965
1009
  warnings,
966
1010
  dropped,
967
1011
  };
@@ -37,6 +37,12 @@ export interface RawEvent {
37
37
  /** Milliseconds since recording start. Excluded from the hash. */
38
38
  ts: number;
39
39
  action: RecordedAction;
40
+ /**
41
+ * The step's id within its flow, e.g. `k3f9`: stays with the step when steps
42
+ * around it are added or removed, so an edit, or a flow that `extends` this
43
+ * one, can name it. Not part of the hash. See core/step-ids.ts.
44
+ */
45
+ id?: string;
40
46
  role?: string;
41
47
  name?: string;
42
48
  /** Exact-match intent for the name, as codegen emits `{ exact: true }`. */
@@ -136,6 +142,8 @@ export interface RawRecording {
136
142
  hash: string;
137
143
  /** Absent for a recording that starts from a blank browser at `startUrl`. */
138
144
  entry?: RecordingEntry;
145
+ /** Defaults for the `{{variables}}` its steps use (core/vars.ts). A run's values override them. */
146
+ vars?: Record<string, string>;
139
147
  events: RawEvent[];
140
148
  }
141
149
  /**
@@ -177,7 +177,8 @@ export interface EndCheck {
177
177
  }
178
178
  export interface ReplayOptions {
179
179
  /**
180
- * Values for `valueRef` steps, e.g. `{ 'SECRET.password': 'hunter2' }`.
180
+ * Values for `valueRef` steps, e.g. `{ 'SECRET.password': 'hunter2' }`, and
181
+ * for the `{{variables}}` in steps (`{ bundle: 'Family' }`, see vars.ts).
181
182
  *
182
183
  * Recordings deliberately never store credentials, so a recording containing
183
184
  * a password CANNOT replay without them. That is the tradeoff working as
@@ -453,7 +454,7 @@ export declare class Stepper {
453
454
  */
454
455
  constructor(lease: BrowserLease, opts?: ReplayOptions, events?: RawEvent[], keepBody?: (url: string) => boolean);
455
456
  /** Run one step: lessons first, then the step, retried while it is safe to. */
456
- run(event: RawEvent, ctx?: StepContext): Promise<StepOutcome>;
457
+ run(template: RawEvent, ctx?: StepContext): Promise<StepOutcome>;
457
458
  }
458
459
  export declare function replay(recording: RawRecording, opts?: ReplayOptions): Promise<ReplayResult>;
459
460
  export {};
@@ -21,6 +21,7 @@
21
21
  * sig(), compare, capture. This is not scaffolding for the recorder; it is the
22
22
  * first half of the thing that runs tests.
23
23
  */
24
+ import { bindStep } from './vars.js';
24
25
  import { parseOutline, OUTLINE_MAX } from './outline.js';
25
26
  import {} from 'playwright';
26
27
  import { openLease } from './browser.js';
@@ -529,9 +530,17 @@ export class Stepper {
529
530
  });
530
531
  }
531
532
  /** Run one step: lessons first, then the step, retried while it is safe to. */
532
- async run(event, ctx = {}) {
533
+ async run(template, ctx = {}) {
533
534
  const { page, responses, sigSequence, escalations, visualChecks } = this;
534
535
  const { values = {}, visualCheck, onDecision, lessonsFor, onHuman } = this.opts;
536
+ // `{{bundle}}` → the value this run uses: from here on, the step is what it does.
537
+ let event;
538
+ try {
539
+ event = bindStep(template, values);
540
+ }
541
+ catch (e) {
542
+ return { seq: template.seq, action: template.action, ok: false, durationMs: 0, error: e.message };
543
+ }
535
544
  // A step may say it needs longer than the rest (`hints.timeoutMs`): the
536
545
  // login that takes 15 s to become usable, without slowing every other step.
537
546
  const own = event.hints?.timeoutMs;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Step ids: a short name for each step of a flow (`k3f9`) that stays with it.
3
+ *
4
+ * An index moves whenever a step is added or removed before it, so anything
5
+ * that points at a step by number points at the wrong one after an edit —
6
+ * silently. Ids don't move. A flow that `extends` another says "my steps go
7
+ * after its step k3f9", and an edit can name the step it changes.
8
+ *
9
+ * Re-saving a flow (a repair, a re-recording) makes new steps from scratch, so
10
+ * ids are carried over from the version it replaces: steps that do the same
11
+ * thing, lined up in order, keep the old step's id. Only genuinely new steps
12
+ * get new ones — which is what keeps a flow that extends this one attached.
13
+ */
14
+ import type { RawEvent } from './recording.js';
15
+ type Identified = Pick<RawEvent, 'id' | 'action' | 'role' | 'name' | 'exact' | 'value' | 'valueRef' | 'css' | 'testId' | 'frameHint' | 'hints'>;
16
+ /** Reserved: "before the first step" when something is placed after an id. */
17
+ export declare const START = "start";
18
+ /** A new id, not one of `taken`. */
19
+ export declare function newStepId(taken: Set<string>): string;
20
+ /** What a step does and to which element — not where or when it was seen. Two steps with one key are the same step. */
21
+ export declare const stepKey: (s: Identified) => string;
22
+ /**
23
+ * Pure: every step with an id. A step that has one keeps it; the rest take the
24
+ * id of the step they match in `previous` (lined up by longest common run, so
25
+ * order counts and one inserted step doesn't shift the others), else a new one.
26
+ * No id is used twice.
27
+ */
28
+ export declare function withIds<T extends Identified>(steps: T[], previous?: ReadonlyArray<Identified>): T[];
29
+ export {};
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Step ids: a short name for each step of a flow (`k3f9`) that stays with it.
3
+ *
4
+ * An index moves whenever a step is added or removed before it, so anything
5
+ * that points at a step by number points at the wrong one after an edit —
6
+ * silently. Ids don't move. A flow that `extends` another says "my steps go
7
+ * after its step k3f9", and an edit can name the step it changes.
8
+ *
9
+ * Re-saving a flow (a repair, a re-recording) makes new steps from scratch, so
10
+ * ids are carried over from the version it replaces: steps that do the same
11
+ * thing, lined up in order, keep the old step's id. Only genuinely new steps
12
+ * get new ones — which is what keeps a flow that extends this one attached.
13
+ */
14
+ import { randomBytes } from 'node:crypto';
15
+ /** Reserved: "before the first step" when something is placed after an id. */
16
+ export const START = 'start';
17
+ /** A new id, not one of `taken`. */
18
+ export function newStepId(taken) {
19
+ for (;;) {
20
+ const id = randomBytes(3).readUIntBE(0, 3).toString(36).padStart(4, '0').slice(-4);
21
+ if (!taken.has(id) && id !== START)
22
+ return id;
23
+ }
24
+ }
25
+ /** What a step does and to which element — not where or when it was seen. Two steps with one key are the same step. */
26
+ export const stepKey = (s) => JSON.stringify([s.action, s.role ?? '', s.name ?? '', Boolean(s.exact), s.value ?? '', s.valueRef ?? '', s.css ?? '', s.testId ?? '', s.frameHint ?? '', s.hints?.nth ?? '']);
27
+ /**
28
+ * Pure: every step with an id. A step that has one keeps it; the rest take the
29
+ * id of the step they match in `previous` (lined up by longest common run, so
30
+ * order counts and one inserted step doesn't shift the others), else a new one.
31
+ * No id is used twice.
32
+ */
33
+ export function withIds(steps, previous = []) {
34
+ const a = previous.map(stepKey);
35
+ const b = steps.map(stepKey);
36
+ const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
37
+ for (let i = a.length - 1; i >= 0; i--)
38
+ for (let j = b.length - 1; j >= 0; j--) {
39
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
40
+ }
41
+ const carried = new Map();
42
+ for (let i = 0, j = 0; i < a.length && j < b.length;) {
43
+ if (a[i] === b[j]) {
44
+ if (previous[i].id)
45
+ carried.set(j, previous[i].id);
46
+ i++;
47
+ j++;
48
+ }
49
+ else if (lcs[i + 1][j] >= lcs[i][j + 1])
50
+ i++;
51
+ else
52
+ j++;
53
+ }
54
+ const taken = new Set();
55
+ const out = steps.map((s, j) => {
56
+ const id = s.id ?? carried.get(j);
57
+ if (!id || taken.has(id))
58
+ return { ...s, id: undefined };
59
+ taken.add(id);
60
+ return s.id === id ? s : { ...s, id };
61
+ });
62
+ for (const s of out) {
63
+ if (s.id)
64
+ continue;
65
+ s.id = newStepId(taken);
66
+ taken.add(s.id);
67
+ }
68
+ return out;
69
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Variables in a flow: `{{bundle}}` in a step's `value` or `name`, with the
3
+ * flow's default for it in `flow.vars`.
4
+ *
5
+ * One flow can then pick any bundle, type any member's name, or check for any
6
+ * heading ("Welcome, {{member}}"), instead of one recording per value. The
7
+ * default is the value the flow was proven with, so a save or a plain run
8
+ * still replays exactly what worked; a run passes `values` to try another.
9
+ *
10
+ * Only `value` and `name` take variables: they say WHAT is typed, picked or
11
+ * read. `role`, `css` and `testId` say which element a step means, and a step
12
+ * that could mean any element isn't a step anyone has proven.
13
+ *
14
+ * A variable is never a secret. Passwords stay `valueRef`s, read from the
15
+ * user's env file; a variable's default is stored in the flow.
16
+ */
17
+ import type { RawEvent } from './recording.js';
18
+ /** `bundle`, `member_2`: a letter first, then letters, digits or _. No dots — `SECRET.password` is a login value. */
19
+ export declare const VAR_NAME: RegExp;
20
+ /** The step fields a variable may appear in. */
21
+ export declare const VAR_FIELDS: readonly ["value", "name"];
22
+ type Templated = Pick<RawEvent, 'value' | 'name'>;
23
+ /** The variables one string uses, in order. */
24
+ export declare const varsInText: (text: string | undefined) => string[];
25
+ /** The variables a list of steps uses, each once, in order of first use. */
26
+ export declare function varsOf(steps: ReadonlyArray<Templated>): string[];
27
+ /** Fill a string's variables. Throws naming the first one with no value, unless `lenient`. */
28
+ export declare function fillText(text: string, values: Record<string, string>, lenient?: boolean): string;
29
+ /** A step with its variables filled in. The same object when it has none. */
30
+ export declare function bindStep<T extends Templated>(step: T, values: Record<string, string>, lenient?: boolean): T;
31
+ /** Steps with their defaults filled in — what the flow does when nobody passes a value. Missing ones stay as written. */
32
+ export declare const withDefaults: <T extends Templated>(steps: T[], vars: Record<string, string> | undefined) => T[];
33
+ /**
34
+ * Pure: does `text` fit `template`, and with what values? `"{{bundle}} bundle"`
35
+ * against `"Family bundle"` → `{ bundle: "Family" }`; no fit → null. A
36
+ * variable used twice must take the same value both times.
37
+ */
38
+ export declare function matchTemplate(template: string, text: string): Record<string, string> | null;
39
+ /**
40
+ * The values a run used that differ from the flow's defaults, keys sorted —
41
+ * so two runs with the same picks compare equal, and a run that changed
42
+ * nothing has none. Only the flow's own variables: never a login value.
43
+ */
44
+ export declare function overridesOf(used: string[], defaults: Record<string, string> | undefined, values: Record<string, string>): Record<string, string>;
45
+ export {};
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Variables in a flow: `{{bundle}}` in a step's `value` or `name`, with the
3
+ * flow's default for it in `flow.vars`.
4
+ *
5
+ * One flow can then pick any bundle, type any member's name, or check for any
6
+ * heading ("Welcome, {{member}}"), instead of one recording per value. The
7
+ * default is the value the flow was proven with, so a save or a plain run
8
+ * still replays exactly what worked; a run passes `values` to try another.
9
+ *
10
+ * Only `value` and `name` take variables: they say WHAT is typed, picked or
11
+ * read. `role`, `css` and `testId` say which element a step means, and a step
12
+ * that could mean any element isn't a step anyone has proven.
13
+ *
14
+ * A variable is never a secret. Passwords stay `valueRef`s, read from the
15
+ * user's env file; a variable's default is stored in the flow.
16
+ */
17
+ /** `bundle`, `member_2`: a letter first, then letters, digits or _. No dots — `SECRET.password` is a login value. */
18
+ export const VAR_NAME = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
19
+ const VAR = /\{\{\s*([A-Za-z][A-Za-z0-9_]{0,39})\s*\}\}/g;
20
+ /** The step fields a variable may appear in. */
21
+ export const VAR_FIELDS = ['value', 'name'];
22
+ /** The variables one string uses, in order. */
23
+ export const varsInText = (text) => text ? [...text.matchAll(VAR)].map((m) => m[1]) : [];
24
+ /** The variables a list of steps uses, each once, in order of first use. */
25
+ export function varsOf(steps) {
26
+ const out = new Set();
27
+ for (const s of steps)
28
+ for (const f of VAR_FIELDS)
29
+ for (const v of varsInText(s[f]))
30
+ out.add(v);
31
+ return [...out];
32
+ }
33
+ /** Fill a string's variables. Throws naming the first one with no value, unless `lenient`. */
34
+ export function fillText(text, values, lenient = false) {
35
+ return text.replace(VAR, (whole, name) => {
36
+ const v = values[name];
37
+ if (v !== undefined)
38
+ return v;
39
+ if (lenient)
40
+ return whole;
41
+ throw new Error(`no value for {{${name}}} — the flow has no default for it, and none was passed in values`);
42
+ });
43
+ }
44
+ /** A step with its variables filled in. The same object when it has none. */
45
+ export function bindStep(step, values, lenient = false) {
46
+ if (!VAR_FIELDS.some((f) => step[f]?.includes('{{')))
47
+ return step;
48
+ const out = { ...step };
49
+ for (const f of VAR_FIELDS)
50
+ if (out[f] !== undefined)
51
+ out[f] = fillText(out[f], values, lenient);
52
+ return out;
53
+ }
54
+ /** Steps with their defaults filled in — what the flow does when nobody passes a value. Missing ones stay as written. */
55
+ export const withDefaults = (steps, vars) => vars && Object.keys(vars).length ? steps.map((s) => bindStep(s, vars, true)) : steps;
56
+ /**
57
+ * Pure: does `text` fit `template`, and with what values? `"{{bundle}} bundle"`
58
+ * against `"Family bundle"` → `{ bundle: "Family" }`; no fit → null. A
59
+ * variable used twice must take the same value both times.
60
+ */
61
+ export function matchTemplate(template, text) {
62
+ const names = varsInText(template);
63
+ if (!names.length)
64
+ return template === text ? {} : null;
65
+ const seen = new Set();
66
+ let source = '';
67
+ let last = 0;
68
+ for (const m of template.matchAll(VAR)) {
69
+ source += escapeRegex(template.slice(last, m.index));
70
+ const name = m[1];
71
+ source += seen.has(name) ? `\\k<${name}>` : `(?<${name}>.+?)`;
72
+ seen.add(name);
73
+ last = m.index + m[0].length;
74
+ }
75
+ source += escapeRegex(template.slice(last));
76
+ const hit = new RegExp(`^${source}$`, 's').exec(text);
77
+ return hit ? { ...hit.groups } : null;
78
+ }
79
+ const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
80
+ /**
81
+ * The values a run used that differ from the flow's defaults, keys sorted —
82
+ * so two runs with the same picks compare equal, and a run that changed
83
+ * nothing has none. Only the flow's own variables: never a login value.
84
+ */
85
+ export function overridesOf(used, defaults, values) {
86
+ const out = {};
87
+ for (const name of [...used].sort()) {
88
+ const v = values[name];
89
+ if (v !== undefined && v !== defaults?.[name])
90
+ out[name] = v;
91
+ }
92
+ return out;
93
+ }