@jeffawe/understudy 0.3.0 → 0.5.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 (42) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +69 -160
  3. package/REASONER.md +76 -86
  4. package/dist/adapters/recorder/script.d.ts +25 -2
  5. package/dist/adapters/recorder/script.js +126 -31
  6. package/dist/core/outline.d.ts +43 -0
  7. package/dist/core/outline.js +121 -0
  8. package/dist/core/recording.d.ts +19 -1
  9. package/dist/core/recording.js +38 -2
  10. package/dist/core/replay.d.ts +62 -1
  11. package/dist/core/replay.js +162 -106
  12. package/dist/entry/cli.js +185 -30
  13. package/dist/entry/mcp.d.ts +2 -0
  14. package/dist/entry/mcp.js +128 -23
  15. package/dist/flows/destructive.js +1 -1
  16. package/dist/flows/distill.js +11 -6
  17. package/dist/flows/emit.d.ts +7 -0
  18. package/dist/flows/emit.js +26 -10
  19. package/dist/flows/execute.d.ts +12 -0
  20. package/dist/flows/execute.js +23 -16
  21. package/dist/flows/runs.d.ts +2 -0
  22. package/dist/flows/runs.js +7 -3
  23. package/dist/flows/save.d.ts +5 -2
  24. package/dist/flows/save.js +38 -23
  25. package/dist/flows/session.d.ts +176 -0
  26. package/dist/flows/session.js +383 -0
  27. package/dist/flows/variants.d.ts +81 -0
  28. package/dist/flows/variants.js +139 -0
  29. package/dist/memory/calibrate.d.ts +114 -0
  30. package/dist/memory/calibrate.js +260 -0
  31. package/dist/memory/pages.d.ts +34 -0
  32. package/dist/memory/pages.js +60 -0
  33. package/dist/memory/recall.d.ts +87 -25
  34. package/dist/memory/recall.js +242 -45
  35. package/dist/plan/planner.d.ts +11 -1
  36. package/dist/plan/planner.js +36 -19
  37. package/dist/store/app-settings.d.ts +26 -0
  38. package/dist/store/app-settings.js +49 -0
  39. package/dist/store/db.js +8 -1
  40. package/dist/store/reembed.js +18 -7
  41. package/dist/store/types.d.ts +50 -0
  42. package/package.json +3 -2
@@ -40,10 +40,15 @@ export type NameLookup = 'placeholder' | 'label' | 'title' | 'alt';
40
40
  * expect(locator).toHaveValue(x) → assert value
41
41
  * expect(locator).toBeChecked() / not.toBeChecked() → assert checked / unchecked
42
42
  * page.waitForSelector(css) → assert visible
43
+ * expect(locator).toBeEnabled() / toBeDisabled() → assert enabled / disabled
44
+ * expect(locator).toBeEditable() / toBeFocused() → assert editable / focused
45
+ *
46
+ * `{ timeout: n }` on any of them, or on a wait, becomes `hints.timeoutMs`:
47
+ * that one step may wait longer — the honest form of a sleep before it.
43
48
  */
44
- export declare const KEPT_ASSERTIONS: readonly ["toHaveURL", "toHaveTitle", "toBeVisible", "toBeHidden", "toHaveText", "toContainText", "toHaveValue", "toBeChecked", "waitForURL", "waitForSelector"];
49
+ export declare const KEPT_ASSERTIONS: readonly ["toHaveURL", "toHaveTitle", "toBeVisible", "toBeHidden", "toHaveText", "toContainText", "toHaveValue", "toBeChecked", "toBeEnabled", "toBeDisabled", "toBeEditable", "toBeFocused", "waitForURL", "waitForSelector"];
45
50
  /** What an `assert` step checks, in `hints.assert`. */
46
- export type AssertKind = 'visible' | 'hidden' | 'text' | 'contains' | 'value' | 'checked' | 'unchecked' | 'title';
51
+ export type AssertKind = 'visible' | 'hidden' | 'text' | 'contains' | 'value' | 'checked' | 'unchecked' | 'title' | 'enabled' | 'disabled' | 'editable' | 'focused';
47
52
  export interface ParsedScript {
48
53
  recording: RawRecording;
49
54
  /** Calls that looked like Playwright actions but could not be mapped. */
@@ -62,9 +67,27 @@ export interface ParsedScript {
62
67
  * first is a substring match, the second is anchored — so the regex-ness has to
63
68
  * survive into the IR rather than being flattened to its source text.
64
69
  */
70
+ /**
71
+ * `role=button[name="Book"]` (Playwright's role selector, which Playwright MCP
72
+ * prints when it was given a selector rather than an element ref) → the same
73
+ * role and name `getByRole` would have. Stored as CSS it had no name — so a
74
+ * commit button written this way wasn't seen as one, and saving pressed it.
75
+ * `[name="…"s]` is an exact match; `i` or nothing is Playwright's default.
76
+ */
77
+ export declare function roleSelector(selector: string): {
78
+ role: string;
79
+ name?: TextMatch;
80
+ exact?: boolean;
81
+ } | undefined;
65
82
  export interface TextMatch {
66
83
  source: string;
67
84
  regex: boolean;
68
85
  flags: string;
69
86
  }
70
87
  export declare function parseScript(filePath: string, appSlug: string, fallbackUrl?: string): Promise<ParsedScript>;
88
+ /**
89
+ * Read Playwright code handed over as text — the lines Playwright MCP printed
90
+ * as an agent explored, pasted together, no test wrapper needed. `filePath`
91
+ * names where it came from, and is where upload paths are looked up from.
92
+ */
93
+ export declare function parseScriptSource(source: string, filePath: string, appSlug: string, fallbackUrl?: string): ParsedScript;
@@ -49,10 +49,16 @@ const NAME_LOOKUPS = {
49
49
  * expect(locator).toHaveValue(x) → assert value
50
50
  * expect(locator).toBeChecked() / not.toBeChecked() → assert checked / unchecked
51
51
  * page.waitForSelector(css) → assert visible
52
+ * expect(locator).toBeEnabled() / toBeDisabled() → assert enabled / disabled
53
+ * expect(locator).toBeEditable() / toBeFocused() → assert editable / focused
54
+ *
55
+ * `{ timeout: n }` on any of them, or on a wait, becomes `hints.timeoutMs`:
56
+ * that one step may wait longer — the honest form of a sleep before it.
52
57
  */
53
58
  export const KEPT_ASSERTIONS = [
54
59
  'toHaveURL', 'toHaveTitle', 'toBeVisible', 'toBeHidden', 'toHaveText',
55
- 'toContainText', 'toHaveValue', 'toBeChecked', 'waitForURL', 'waitForSelector',
60
+ 'toContainText', 'toHaveValue', 'toBeChecked', 'toBeEnabled', 'toBeDisabled',
61
+ 'toBeEditable', 'toBeFocused', 'waitForURL', 'waitForSelector',
56
62
  ];
57
63
  /** Waits that need nothing kept: replay already settles the page after every step. */
58
64
  const SETTLING_WAITS = new Set(['waitForLoadState', 'waitForNavigation']);
@@ -168,6 +174,30 @@ function resolveFixture(value, specPath) {
168
174
  // asked for rather than a path this function invented.
169
175
  return value;
170
176
  }
177
+ /**
178
+ * A text constraint, which Playwright lets you write either way.
179
+ *
180
+ * `{ name: 'Sign in' }` and `{ name: /^Sign in$/ }` mean different things — the
181
+ * first is a substring match, the second is anchored — so the regex-ness has to
182
+ * survive into the IR rather than being flattened to its source text.
183
+ */
184
+ /**
185
+ * `role=button[name="Book"]` (Playwright's role selector, which Playwright MCP
186
+ * prints when it was given a selector rather than an element ref) → the same
187
+ * role and name `getByRole` would have. Stored as CSS it had no name — so a
188
+ * commit button written this way wasn't seen as one, and saving pressed it.
189
+ * `[name="…"s]` is an exact match; `i` or nothing is Playwright's default.
190
+ */
191
+ export function roleSelector(selector) {
192
+ const m = selector.trim().match(/^(?:internal:)?role=([a-z]+)(?:\[name=(["'])((?:\\.|(?!\2).)*)\2([is])?\])?$/);
193
+ if (!m)
194
+ return undefined;
195
+ const [, role, , rawName, flag] = m;
196
+ if (rawName === undefined)
197
+ return { role: role };
198
+ const name = rawName.replace(/\\(.)/g, '$1');
199
+ return { role: role, name: { source: name, regex: false, flags: '' }, ...(flag === 's' ? { exact: true } : {}) };
200
+ }
171
201
  function textMatch(node) {
172
202
  if (!node)
173
203
  return undefined;
@@ -263,7 +293,9 @@ function locatorBit(method, args) {
263
293
  }
264
294
  case 'locator': {
265
295
  const css = first ? text(first) : undefined;
266
- return css !== undefined ? { css } : undefined;
296
+ if (css === undefined)
297
+ return undefined;
298
+ return roleSelector(css) ?? { css };
267
299
  }
268
300
  case 'frameLocator': {
269
301
  const frame = first ? text(first) : undefined;
@@ -531,7 +563,14 @@ const isWaitCall = (e) => {
531
563
  return ts.isCallExpression(x) && ts.isPropertyAccessExpression(x.expression) && WAIT_METHODS.has(x.expression.name.text);
532
564
  };
533
565
  export async function parseScript(filePath, appSlug, fallbackUrl) {
534
- const source = await readFile(filePath, 'utf8');
566
+ return parseScriptSource(await readFile(filePath, 'utf8'), filePath, appSlug, fallbackUrl);
567
+ }
568
+ /**
569
+ * Read Playwright code handed over as text — the lines Playwright MCP printed
570
+ * as an agent explored, pasted together, no test wrapper needed. `filePath`
571
+ * names where it came from, and is where upload paths are looked up from.
572
+ */
573
+ export function parseScriptSource(source, filePath, appSlug, fallbackUrl) {
535
574
  const sourceFile = ts.createSourceFile(basename(filePath), source, ts.ScriptTarget.Latest,
536
575
  /* setParentNodes */ true, filePath.endsWith('.js') ? ts.ScriptKind.JS : ts.ScriptKind.TS);
537
576
  const events = [];
@@ -545,11 +584,17 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
545
584
  let startUrl = fallbackUrl ?? '';
546
585
  const snippet = (node) => node.getText().replace(/\s+/g, ' ').slice(0, 80);
547
586
  const drop = (why, node) => dropped.push(`${why}: ${snippet(node)}`);
587
+ /**
588
+ * A WAIT that can't be kept refuses the save. Dropping a check only makes the
589
+ * flow check less; dropping a wait makes the next step run too early, and a
590
+ * login that hasn't finished yet then fails somewhere that says nothing about it.
591
+ */
592
+ const refuse = (why, node) => warnings.push(`${why}: ${snippet(node)}`);
548
593
  /** A URL wait, from `waitForURL(x)` or `expect(page).toHaveURL(x)`. */
549
- const pushWaitUrl = (arg, node) => {
594
+ const pushWaitUrl = (arg, node, more = {}) => {
550
595
  const match = textMatch(arg);
551
596
  if (!match)
552
- return drop('URL wait with a non-literal URL, not kept', node);
597
+ return refuse('URL wait with a non-literal URL — write it as a string, glob or /regex/', node);
553
598
  events.push({
554
599
  seq: events.length,
555
600
  ts: events.length,
@@ -557,7 +602,7 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
557
602
  value: match.source,
558
603
  url: currentUrl,
559
604
  resolution: 'script-literal',
560
- ...(match.regex ? { hints: { urlRegex: true, urlFlags: match.flags } } : {}),
605
+ ...(match.regex || Object.keys(more).length ? { hints: { ...(match.regex ? { urlRegex: true, urlFlags: match.flags } : {}), ...more } } : {}),
561
606
  });
562
607
  // A wait for a plain address says which page the steps after it are on —
563
608
  // the best a static read can do. A regex or a glob names no single page.
@@ -570,11 +615,12 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
570
615
  currentUrl = absolute(match.source, fallbackUrl);
571
616
  };
572
617
  /** A `wait_response` step from what waitForResponse() was given. */
573
- const pushWaitResponse = (arg, node) => {
618
+ const pushWaitResponse = (arg, node, more = {}) => {
574
619
  const { check, why } = responseWaitFrom(arg);
575
620
  if (!check)
576
- return drop(`${why ?? 'waitForResponse()'}, not kept`, node);
577
- const { url, ...rest } = check;
621
+ return refuse(why ?? 'waitForResponse() it could not read', node);
622
+ const { url, ...found } = check;
623
+ const rest = { ...found, ...more };
578
624
  events.push({
579
625
  seq: events.length, ts: events.length, action: 'wait_response', value: url,
580
626
  url: currentUrl, resolution: 'script-literal', ...(Object.keys(rest).length ? { hints: rest } : {}),
@@ -585,10 +631,10 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
585
631
  // is AWAITED — after the click — not where it was set up.
586
632
  const deferred = new Map();
587
633
  /** An `assert` step on an element (or, for `title`, the page). */
588
- const pushAssert = (t, kind, arg, node) => {
634
+ const pushAssert = (t, kind, arg, node, more = {}) => {
589
635
  const needsValue = kind === 'text' || kind === 'contains' || kind === 'value' || kind === 'title';
590
636
  let valued = {};
591
- const extra = { assert: kind };
637
+ const extra = { assert: kind, ...more };
592
638
  if (needsValue) {
593
639
  const match = textMatch(arg);
594
640
  if (match) {
@@ -634,11 +680,14 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
634
680
  }
635
681
  const arg = node.arguments[0];
636
682
  const { matcher, negated } = ex;
683
+ // `{ timeout }` comes after the expected value, or first when there is none.
684
+ const valued = ['toHaveURL', 'toHaveTitle', 'toHaveText', 'toContainText', 'toHaveValue'].includes(matcher);
685
+ const more = timeoutHint(node.arguments[valued ? 1 : 0]);
637
686
  if (t.bare) {
638
687
  if (matcher === 'toHaveURL' && !negated)
639
- return pushWaitUrl(arg, node);
688
+ return pushWaitUrl(arg, node, more);
640
689
  if (matcher === 'toHaveTitle' && !negated)
641
- return pushAssert(t, 'title', arg, node);
690
+ return pushAssert(t, 'title', arg, node, more);
642
691
  return drop(`page assertion ${negated ? 'not.' : ''}${matcher}() is not kept`, node);
643
692
  }
644
693
  if (!addresses(t.merged))
@@ -648,14 +697,18 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
648
697
  const kind = matcher === 'toBeVisible' ? (negated ? 'hidden' : 'visible')
649
698
  : matcher === 'toBeHidden' ? (negated ? 'visible' : 'hidden')
650
699
  : matcher === 'toBeChecked' ? (negated ? 'unchecked' : 'checked')
651
- : negated ? undefined
652
- : matcher === 'toHaveText' ? 'text'
653
- : matcher === 'toContainText' ? 'contains'
654
- : matcher === 'toHaveValue' ? 'value'
655
- : undefined;
700
+ : matcher === 'toBeEnabled' ? (negated ? 'disabled' : 'enabled')
701
+ : matcher === 'toBeDisabled' ? (negated ? 'enabled' : 'disabled')
702
+ : negated ? undefined
703
+ : matcher === 'toBeEditable' ? 'editable'
704
+ : matcher === 'toBeFocused' ? 'focused'
705
+ : matcher === 'toHaveText' ? 'text'
706
+ : matcher === 'toContainText' ? 'contains'
707
+ : matcher === 'toHaveValue' ? 'value'
708
+ : undefined;
656
709
  if (!kind)
657
710
  return drop(`assertion ${negated ? 'not.' : ''}${matcher}() is not kept`, node);
658
- pushAssert(t, kind, arg, node);
711
+ pushAssert(t, kind, arg, node, more);
659
712
  };
660
713
  const visit = (node) => {
661
714
  if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && ts.isCallExpression(node.initializer)
@@ -666,7 +719,7 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
666
719
  if (ts.isAwaitExpression(node) && ts.isIdentifier(node.expression) && deferred.has(node.expression.text)) {
667
720
  const call = deferred.get(node.expression.text);
668
721
  deferred.delete(node.expression.text);
669
- pushWaitResponse(call.arguments[0], call);
722
+ pushWaitResponse(call.arguments[0], call, timeoutHint(call.arguments[1]));
670
723
  return;
671
724
  }
672
725
  // `Promise.all([page.waitForURL(x), page.click(y)])` — the wait is written
@@ -781,25 +834,43 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
781
834
  if (!action && WAIT_METHODS.has(method) && readTarget(node.expression.expression).rooted) {
782
835
  const arg = node.arguments[0];
783
836
  if (method === 'waitForURL')
784
- pushWaitUrl(arg, node);
837
+ pushWaitUrl(arg, node, timeoutHint(node.arguments[1]));
785
838
  else if (method === 'waitForSelector') {
786
839
  const css = arg ? text(arg) : undefined;
787
840
  if (css === undefined)
788
- drop('waitForSelector with a non-literal selector, not kept', node);
841
+ refuse('waitForSelector with a non-literal selector', node);
789
842
  else {
790
843
  const state = readState(node.arguments[1]);
791
844
  const kind = state === 'hidden' || state === 'detached' ? 'hidden' : 'visible';
792
- pushAssert({ rooted: true, bare: false, merged: { css } }, kind, undefined, node);
845
+ pushAssert({ rooted: true, bare: false, merged: { css } }, kind, undefined, node, timeoutHint(node.arguments[1]));
793
846
  }
794
847
  }
795
848
  else if (method === 'waitForResponse') {
796
- pushWaitResponse(node.arguments[0], node);
849
+ pushWaitResponse(node.arguments[0], node, timeoutHint(node.arguments[1]));
797
850
  }
798
851
  else if (!SETTLING_WAITS.has(method)) {
799
- drop(`${method}() is not kept (replay can't wait on network events)`, node);
852
+ refuse(`${method}() can't be replayed — wait for what it leads to (waitForResponse, waitForURL, or a locator's waitFor())`, node);
853
+ }
854
+ else if (method === 'waitForLoadState' && arg && text(arg) === 'networkidle') {
855
+ // Replay settles after every step, but not on a quiet network. Not
856
+ // refused: most scripts use it as a habit, not because it's needed.
857
+ drop("waitForLoadState('networkidle') is not kept — replay doesn't wait for a quiet network; if a step needs a response first, waitForResponse it", node);
800
858
  }
801
859
  // waitForLoadState / waitForNavigation: replay settles after every step anyway.
802
860
  }
861
+ // `page.getByRole('heading', …).waitFor()` — a wait for an element. Kept
862
+ // as a check that it's there, which replay retries until it is.
863
+ if (!action && method === 'waitFor') {
864
+ const t = readTarget(node.expression.expression);
865
+ if (!t.rooted)
866
+ refuse('waitFor() on a locator held in a variable — write the locator inline, e.g. page.getByRole(...).waitFor()', node);
867
+ else if (t.bare || !addresses(t.merged))
868
+ refuse('waitFor() on something with no usable locator', node);
869
+ else {
870
+ const state = readState(node.arguments[0]);
871
+ pushAssert(t, state === 'hidden' || state === 'detached' ? 'hidden' : 'visible', undefined, node, timeoutHint(node.arguments[0]));
872
+ }
873
+ }
803
874
  if (action) {
804
875
  const t = readTarget(node.expression.expression);
805
876
  if (t.rooted) {
@@ -859,11 +930,16 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
859
930
  // corpus. A valueRef is already a reference and passes through.
860
931
  // An upload's argument is a PATH, not a value to redact — and it
861
932
  // needs resolving against the spec's own repo before it can be read.
933
+ // A press's argument is a KEY: `press('Enter')` in the password box
934
+ // is how a login is submitted, and redacting it made replay press
935
+ // the password instead.
862
936
  const valued = action === 'upload' && raw.value !== undefined
863
937
  ? { value: resolveFixture(raw.value, filePath) }
864
- : raw.value !== undefined
865
- ? redactValue(fieldHint, raw.value, undefined, secretSignal)
866
- : raw;
938
+ : action === 'press'
939
+ ? raw
940
+ : raw.value !== undefined
941
+ ? redactValue(fieldHint, raw.value, undefined, secretSignal)
942
+ : raw;
867
943
  events.push({
868
944
  seq: events.length,
869
945
  ts: events.length,
@@ -883,7 +959,7 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
883
959
  };
884
960
  visit(sourceFile);
885
961
  for (const [name, call] of deferred)
886
- drop(`waitForResponse() kept in "${name}" but never awaited, not kept`, call);
962
+ refuse(`waitForResponse() kept in "${name}" but never awaited`, call);
887
963
  return {
888
964
  recording: buildRecording({ source: 'script', origin: filePath, appSlug, startUrl }, events.map((e, i) => ({ ...e, seq: i }))),
889
965
  warnings,
@@ -902,8 +978,11 @@ function responseWaitFrom(arg) {
902
978
  const literal = text(arg);
903
979
  if (literal)
904
980
  return { check: { url: literal } };
905
- if (ts.isRegularExpressionLiteral(arg))
906
- return { why: 'waitForResponse(/regex/) — write the address as a string or glob' };
981
+ if (ts.isRegularExpressionLiteral(arg)) {
982
+ const match = textMatch(arg);
983
+ if (match?.regex)
984
+ return { check: { url: match.source, urlRegex: true, urlFlags: match.flags } };
985
+ }
907
986
  if (!ts.isArrowFunction(arg) && !ts.isFunctionExpression(arg))
908
987
  return { why: 'waitForResponse() with a predicate held in a variable' };
909
988
  const body = arg.body.getText();
@@ -950,6 +1029,22 @@ function readUntil(node) {
950
1029
  }
951
1030
  return out;
952
1031
  }
1032
+ /**
1033
+ * `{ timeout: 15000 }` in a call's options → `{ timeoutMs: 15000 }`, the hint
1034
+ * replay reads to let this one step wait longer than the rest.
1035
+ */
1036
+ function timeoutHint(node) {
1037
+ if (!node || !ts.isObjectLiteralExpression(node))
1038
+ return {};
1039
+ for (const prop of node.properties) {
1040
+ if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'timeout' && ts.isNumericLiteral(prop.initializer)) {
1041
+ const ms = Number(prop.initializer.text.replace(/_/g, ''));
1042
+ if (ms > 0)
1043
+ return { timeoutMs: ms };
1044
+ }
1045
+ }
1046
+ return {};
1047
+ }
953
1048
  /** `{ state: 'hidden' }` → 'hidden'. */
954
1049
  function readState(node) {
955
1050
  if (!node || !ts.isObjectLiteralExpression(node))
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A page's controls, as an agent exploring it needs them: what it can click,
3
+ * fill or pick, what state each is in, and what the page says (headings,
4
+ * status messages) — read from the accessibility tree, so it is what a person
5
+ * would see, not markup. What a DOM dump was used for, in a few hundred tokens.
6
+ *
7
+ * NEVER FIELD VALUES. A text box's contents are whatever someone typed — a
8
+ * name, an address, a code — so they are dropped. Options in a list are the
9
+ * app's own words and are kept.
10
+ *
11
+ * `diffOutline` is what makes exploring cheap: after a step, only what
12
+ * appeared, went, or changed state ("a follow-up question appeared") instead
13
+ * of the whole page again.
14
+ */
15
+ import type { Page } from 'playwright';
16
+ export interface Control {
17
+ role: string;
18
+ name?: string;
19
+ /** The radio group, group or list it sits in — usually the question it answers. */
20
+ group?: string;
21
+ /** checked, disabled, expanded, selected, pressed… */
22
+ state?: string[];
23
+ /** A list's or select's options, in order; a selected one is marked `*`. */
24
+ options?: string[];
25
+ /** What a heading, status or alert says, when it has no name. */
26
+ text?: string;
27
+ }
28
+ /** Cap on what one outline returns — a page with 2,000 links is not explored by reading all of them. */
29
+ export declare const OUTLINE_MAX = 150;
30
+ /** Pure: Playwright's aria snapshot as controls. Exported for tests. */
31
+ export declare function parseOutline(snapshot: string): Control[];
32
+ /** The page's controls, at most OUTLINE_MAX. */
33
+ export declare function outlineOf(page: Page, timeoutMs?: number): Promise<Control[]>;
34
+ /** `radio "No" in "Do you have a bundle?" [checked]` — one line per control. */
35
+ export declare function describeControl(c: Control): string;
36
+ export interface OutlineDiff {
37
+ appeared: string[];
38
+ gone: string[];
39
+ /** Same control, new state or options: `checkbox "Terms": now [checked]`. */
40
+ changed: string[];
41
+ }
42
+ /** Pure: what a step did to the page's controls. Lists are capped; the page outline has the rest. */
43
+ export declare function diffOutline(before: Control[], after: Control[], max?: number): OutlineDiff;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * A page's controls, as an agent exploring it needs them: what it can click,
3
+ * fill or pick, what state each is in, and what the page says (headings,
4
+ * status messages) — read from the accessibility tree, so it is what a person
5
+ * would see, not markup. What a DOM dump was used for, in a few hundred tokens.
6
+ *
7
+ * NEVER FIELD VALUES. A text box's contents are whatever someone typed — a
8
+ * name, an address, a code — so they are dropped. Options in a list are the
9
+ * app's own words and are kept.
10
+ *
11
+ * `diffOutline` is what makes exploring cheap: after a step, only what
12
+ * appeared, went, or changed state ("a follow-up question appeared") instead
13
+ * of the whole page again.
14
+ */
15
+ /** Roles an agent acts on, or reads to know where it is. */
16
+ const KEPT = new Set([
17
+ 'button', 'link', 'textbox', 'searchbox', 'checkbox', 'radio', 'combobox', 'listbox', 'switch',
18
+ 'slider', 'spinbutton', 'tab', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'treeitem',
19
+ 'heading', 'alert', 'status', 'dialog', 'alertdialog',
20
+ ]);
21
+ /** Their text after the colon is someone's input, never kept. */
22
+ const INPUT = new Set(['textbox', 'searchbox', 'spinbutton', 'combobox', 'slider']);
23
+ /** Containers whose name says what the controls in them are about. */
24
+ const GROUPS = new Set(['radiogroup', 'group', 'listbox', 'combobox', 'menu', 'tablist', 'dialog', 'alertdialog']);
25
+ /** States worth an agent knowing. `level` etc. are left out. */
26
+ const STATES = new Set(['checked', 'disabled', 'expanded', 'selected', 'pressed', 'required', 'invalid', 'mixed']);
27
+ /** Cap on what one outline returns — a page with 2,000 links is not explored by reading all of them. */
28
+ export const OUTLINE_MAX = 150;
29
+ const unquote = (s) => (s.startsWith('"') ? s.slice(1, -1).replace(/\\(.)/g, '$1') : s.slice(1, -1).replace(/''/g, "'"));
30
+ /** Pure: Playwright's aria snapshot as controls. Exported for tests. */
31
+ export function parseOutline(snapshot) {
32
+ const out = [];
33
+ const stack = [];
34
+ for (const line of snapshot.split('\n')) {
35
+ const m = line.match(/^(\s*)- ([a-z]+)(?: ("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'))?((?: \[[^\]]*\])*)(?::\s*(.*))?$/);
36
+ if (!m)
37
+ continue;
38
+ const [, pad = '', role = '', rawName, flags = '', after] = m;
39
+ const indent = pad.length;
40
+ while (stack.length && stack.at(-1).indent >= indent)
41
+ stack.pop();
42
+ const name = rawName ? unquote(rawName) : undefined;
43
+ const state = [...flags.matchAll(/\[([a-z]+)(?:=([^\]]*))?\]/g)]
44
+ .filter(([, k, v]) => STATES.has(k) && v !== 'false')
45
+ .map(([, k, v]) => (v && v !== 'true' ? `${k}=${v}` : k));
46
+ if (role === 'option') {
47
+ const owner = [...stack].reverse().find((s) => s.control && (s.role === 'combobox' || s.role === 'listbox'))?.control;
48
+ const label = name ?? after?.trim();
49
+ if (owner && label)
50
+ (owner.options ??= []).push(state.includes('selected') ? `${label}*` : label);
51
+ continue;
52
+ }
53
+ let control;
54
+ if (KEPT.has(role)) {
55
+ const group = [...stack].reverse().find((s) => GROUPS.has(s.role) && s.name)?.name;
56
+ const text = !INPUT.has(role) && !name && after?.trim() ? after.trim().slice(0, 200) : undefined;
57
+ if (name || text || role === 'button' || role === 'textbox') {
58
+ control = {
59
+ role, ...(name ? { name } : {}), ...(group && group !== name ? { group } : {}),
60
+ ...(state.length ? { state } : {}), ...(text ? { text } : {}),
61
+ };
62
+ out.push(control);
63
+ }
64
+ }
65
+ stack.push({ indent, role, ...(name ? { name } : {}), ...(control ? { control } : {}) });
66
+ }
67
+ return out;
68
+ }
69
+ /** The page's controls, at most OUTLINE_MAX. */
70
+ export async function outlineOf(page, timeoutMs = 3000) {
71
+ const tree = await page.locator('body').ariaSnapshot({ timeout: timeoutMs }).catch(() => '');
72
+ return parseOutline(tree).slice(0, OUTLINE_MAX);
73
+ }
74
+ /** `radio "No" in "Do you have a bundle?" [checked]` — one line per control. */
75
+ export function describeControl(c) {
76
+ return [
77
+ c.role,
78
+ c.name !== undefined && JSON.stringify(c.name),
79
+ c.text !== undefined && JSON.stringify(c.text),
80
+ c.group && `in ${JSON.stringify(c.group)}`,
81
+ c.state?.length && `[${c.state.join(', ')}]`,
82
+ c.options?.length && `options: ${c.options.map((o) => JSON.stringify(o)).join(', ')}`,
83
+ ].filter(Boolean).join(' ');
84
+ }
85
+ /** What tells two controls apart, so the same one is matched before and after. */
86
+ const keyOf = (c) => [c.role, c.group ?? '', c.name ?? c.text ?? ''].join('\u0000');
87
+ /** Pure: what a step did to the page's controls. Lists are capped; the page outline has the rest. */
88
+ export function diffOutline(before, after, max = 40) {
89
+ const count = (list) => {
90
+ const m = new Map();
91
+ for (const c of list)
92
+ m.set(keyOf(c), [...(m.get(keyOf(c)) ?? []), c]);
93
+ return m;
94
+ };
95
+ const was = count(before);
96
+ const now = count(after);
97
+ const appeared = [];
98
+ const gone = [];
99
+ const changed = [];
100
+ for (const [key, list] of now) {
101
+ const old = was.get(key) ?? [];
102
+ list.forEach((c, i) => {
103
+ const o = old[i];
104
+ if (!o)
105
+ appeared.push(describeControl(c));
106
+ else {
107
+ const s = (c.state ?? []).join(', ');
108
+ const os = (o.state ?? []).join(', ');
109
+ const opts = (c.options ?? []).join('|');
110
+ if (s !== os || opts !== (o.options ?? []).join('|')) {
111
+ changed.push(`${describeControl({ ...c, state: [], options: [] }).trim()}: now ${s ? `[${s}]` : 'no state'}${opts !== (o.options ?? []).join('|') ? `, options: ${(c.options ?? []).join(', ')}` : ''}`);
112
+ }
113
+ }
114
+ });
115
+ }
116
+ for (const [key, list] of was) {
117
+ const left = now.get(key) ?? [];
118
+ list.slice(left.length).forEach((c) => gone.push(describeControl(c)));
119
+ }
120
+ return { appeared: appeared.slice(0, max), gone: gone.slice(0, max), changed: changed.slice(0, max) };
121
+ }
@@ -192,6 +192,15 @@ export declare function redactValue(fieldHint: string, value: string, inputType?
192
192
  * then demanded a login value by that name, stopping the run before it began.
193
193
  */
194
194
  export declare function valueRefsOf(events: ReadonlyArray<Pick<RawEvent, 'action' | 'valueRef'>>): string[];
195
+ /**
196
+ * The option an old `select` step chose, from before script import read
197
+ * `selectOption({ label: 'Large' })`: it stored the source text as a valueRef,
198
+ * so a run asked for a login value called "{ label: 'Large' }". Read as the
199
+ * literal it always was, so those flows need no re-saving.
200
+ */
201
+ export declare function legacyOption(event: Pick<RawEvent, 'action' | 'valueRef'>): string | undefined;
202
+ /** The literal a step types, picks or checks for — its value, or an old select's option. */
203
+ export declare const literalValue: (event: Pick<RawEvent, "action" | "value" | "valueRef">) => string | undefined;
195
204
  /**
196
205
  * Should this step skip Playwright's actionability checks — `click({ force: true })`?
197
206
  *
@@ -206,8 +215,10 @@ export declare function forced(event: Pick<RawEvent, 'action' | 'valueRef' | 'hi
206
215
  * `commission.amount` is above 0.
207
216
  */
208
217
  export interface ResponseCheck {
209
- /** Address: a substring, or a glob (`**\/api/visits`). */
218
+ /** Address: a substring, or a glob (`**\/api/visits`) — or, with `regexFlags`, a regex's source. */
210
219
  url: string;
220
+ /** Set when `url` is a regex: its flags ('' for none). */
221
+ regexFlags?: string;
211
222
  method?: string;
212
223
  status?: number;
213
224
  /** A dot path into the JSON body, e.g. "commission.amount" or "items.0.id". */
@@ -231,3 +242,10 @@ export interface HumanUntil {
231
242
  response?: ResponseCheck;
232
243
  }
233
244
  export declare const humanUntil: (event: Pick<RawEvent, "hints">) => HumanUntil | undefined;
245
+ /**
246
+ * The same recording, against the app at another address: a branch's preview
247
+ * deploy, staging. Every address on the recording's own origin moves to
248
+ * `baseUrl`'s; anything elsewhere (a payment provider, a sign-in service) stays.
249
+ * Page fingerprints use the path only, so they still compare.
250
+ */
251
+ export declare function rebase(recording: RawRecording, baseUrl: string): RawRecording;
@@ -112,9 +112,22 @@ const VALUELESS_ACTIONS = new Set(['click', 'dispatch_click', 'check', 'uncheck'
112
112
  * then demanded a login value by that name, stopping the run before it began.
113
113
  */
114
114
  export function valueRefsOf(events) {
115
- const refs = events.filter((e) => e.valueRef && !VALUELESS_ACTIONS.has(e.action)).map((e) => e.valueRef);
115
+ const refs = events.filter((e) => e.valueRef && !VALUELESS_ACTIONS.has(e.action) && legacyOption(e) === undefined).map((e) => e.valueRef);
116
116
  return [...new Set(refs)];
117
117
  }
118
+ /**
119
+ * The option an old `select` step chose, from before script import read
120
+ * `selectOption({ label: 'Large' })`: it stored the source text as a valueRef,
121
+ * so a run asked for a login value called "{ label: 'Large' }". Read as the
122
+ * literal it always was, so those flows need no re-saving.
123
+ */
124
+ export function legacyOption(event) {
125
+ if (event.action !== 'select' || !event.valueRef)
126
+ return undefined;
127
+ return event.valueRef.match(/^\{\s*(?:label|value)\s*:\s*(['"`])(.*)\1\s*,?\s*\}$/s)?.[2];
128
+ }
129
+ /** The literal a step types, picks or checks for — its value, or an old select's option. */
130
+ export const literalValue = (event) => event.value ?? legacyOption(event);
118
131
  /**
119
132
  * Should this step skip Playwright's actionability checks — `click({ force: true })`?
120
133
  *
@@ -136,6 +149,7 @@ export function responseCheckOf(url, hints) {
136
149
  const eq = h.equals;
137
150
  return {
138
151
  url,
152
+ ...(h.urlRegex ? { regexFlags: String(h.urlFlags ?? '') } : {}),
139
153
  ...(typeof h.method === 'string' ? { method: h.method.toUpperCase() } : {}),
140
154
  ...(typeof h.status === 'number' ? { status: h.status } : {}),
141
155
  ...(typeof h.field === 'string' ? { field: h.field } : {}),
@@ -146,7 +160,7 @@ export function responseCheckOf(url, hints) {
146
160
  /** `POST /api/visits → 201, commission.amount > 0` */
147
161
  export function describeResponse(c) {
148
162
  const field = c.field ? `, ${c.field}${c.equals !== undefined ? ` = ${JSON.stringify(c.equals)}` : c.above !== undefined ? ` > ${c.above}` : ' present'}` : '';
149
- return `${c.method ? `${c.method} ` : ''}${c.url}${c.status !== undefined ? ` → ${c.status}` : ''}${field}`;
163
+ return `${c.method ? `${c.method} ` : ''}${c.regexFlags !== undefined ? `/${c.url}/${c.regexFlags}` : c.url}${c.status !== undefined ? ` → ${c.status}` : ''}${field}`;
150
164
  }
151
165
  export const humanUntil = (event) => {
152
166
  const url = typeof event.hints?.untilUrl === 'string' ? event.hints.untilUrl : undefined;
@@ -158,3 +172,25 @@ export const humanUntil = (event) => {
158
172
  : raw && typeof raw === 'object' ? responseCheckOf(raw.url, raw) : undefined;
159
173
  return url || text || response ? { ...(url ? { url } : {}), ...(text ? { text } : {}), ...(response ? { response } : {}) } : undefined;
160
174
  };
175
+ /**
176
+ * The same recording, against the app at another address: a branch's preview
177
+ * deploy, staging. Every address on the recording's own origin moves to
178
+ * `baseUrl`'s; anything elsewhere (a payment provider, a sign-in service) stays.
179
+ * Page fingerprints use the path only, so they still compare.
180
+ */
181
+ export function rebase(recording, baseUrl) {
182
+ const from = new URL(recording.startUrl).origin;
183
+ const to = new URL(baseUrl).origin;
184
+ if (from === to)
185
+ return recording;
186
+ const move = (u) => (u && u.startsWith(from) && (u.length === from.length || '/?#'.includes(u[from.length])) ? to + u.slice(from.length) : u);
187
+ return {
188
+ ...recording,
189
+ startUrl: move(recording.startUrl),
190
+ events: recording.events.map((e) => ({
191
+ ...e,
192
+ url: move(e.url),
193
+ ...(e.value !== undefined && ['goto', 'wait_url'].includes(e.action) ? { value: move(e.value) } : {}),
194
+ })),
195
+ };
196
+ }