@jeffawe/understudy 0.2.1 → 0.2.3

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/README.md CHANGED
@@ -61,6 +61,17 @@ To record, install the [Understudy recorder](https://chromewebstore.google.com/d
61
61
  Not using Chrome or another Chromium browser? See
62
62
  [extension/README.md](extension/README.md).
63
63
 
64
+ **On Safari, or prefer a fresh browser over your own?** Record in a browser
65
+ Understudy opens instead. It needs one extra download, the full Chromium
66
+ browser (about 350 MB, once):
67
+
68
+ ```bash
69
+ npx playwright install chromium
70
+ understudy record myapp --new-browser --url https://your-app.example
71
+ ```
72
+
73
+ Click through the flow in the window that opens, then close it to stop.
74
+
64
75
  | Setting | What it's for |
65
76
  |---|---|
66
77
  | `MONGODB_URI` | your Atlas `mongodb+srv://…` string, or local Community |
@@ -95,34 +106,33 @@ understudy save <hash> "log in as a member" # prove it by replaying, then keep i
95
106
  understudy flows myapp # what it knows how to do
96
107
  understudy replay myapp log-in-as-a-member # run one flow
97
108
  understudy run myapp "sign in" # find the flow for a goal, and run it
98
- understudy findings myapp # what looked broken
109
+ understudy import myapp login.spec.ts # turn a Playwright script into a recording, then save it
110
+ understudy findings myapp # what looked broken, most severe first
99
111
  understudy emit myapp log-in-as-a-member # print it as a Playwright (or Cypress) test
100
112
  understudy app myapp --placeholder email # keep email addresses out of memory (moves them to your env file)
101
113
  ```
102
114
 
115
+ An imported script keeps its checks — `expect(...).toBeVisible()`,
116
+ `toHaveText`, `toHaveURL`, `waitForURL` and the like — so a replay fails when
117
+ the page is wrong, not just when a button is missing. A check it can't replay is
118
+ listed when you import, never dropped silently.
119
+
103
120
  An unproven flow is marked as such in `flows` and recall; the first run of
104
- it that passes proves it. `understudy --help` lists everything. A flow that commits something real — a
121
+ it that passes proves it. `understudy --help` lists everything, and
122
+ `understudy --version` says which one you have. A flow that commits something real — a
105
123
  purchase, a deletion — is marked destructive and refused unless you pass
106
124
  `--allow-purchases`.
107
125
 
108
- **On Safari, or prefer a fresh browser over your own?** Record in a browser
109
- Understudy opens instead. It needs one extra download, the full Chromium
110
- browser (about 350 MB, once):
111
-
112
- ```bash
113
- npx playwright install chromium
114
- understudy record myapp --new-browser --url https://your-app.example
115
- ```
116
-
117
- Click through the flow in the window that opens, then close it to stop.
118
-
119
126
  ## Where your data goes
120
127
 
121
128
  Everything stays with you. Understudy has no server, no account and no
122
129
  telemetry.
123
130
 
124
- - **Recordings** are files on your machine. The Chrome extension sends what it
125
- records only to Understudy on `127.0.0.1`.
131
+ - **Recordings** are files on your machine, in `~/.understudy` (or
132
+ `UNDERSTUDY_HOME`) — the same place whichever folder you, or your agent, run
133
+ it from. The Chrome extension sends what it records only to Understudy on
134
+ `127.0.0.1`. Before 0.2.2 they went in a `.understudy` folder wherever it ran;
135
+ those still load.
126
136
  - **Saved flows, notes and findings** go to the MongoDB you configured.
127
137
  - **Your embedding model** (Voyage by default, if you set a key) receives only
128
138
  the short texts used for search — flow names and descriptions, facts and
@@ -22,13 +22,14 @@ import {} from 'playwright';
22
22
  import { createHash } from 'node:crypto';
23
23
  import { existsSync } from 'node:fs';
24
24
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
25
- import { basename, join, relative, resolve } from 'node:path';
25
+ import { basename, join } from 'node:path';
26
26
  import { openLease } from '../../core/browser.js';
27
27
  import { computeSig, parseAria } from '../../core/sig.js';
28
28
  import { buildRecording, } from '../../core/recording.js';
29
29
  import { INJECTED_LISTENER, STAMP_ATTR } from './injected.js';
30
30
  import { ACCNAME_BUNDLE } from './accname-bundle.js';
31
31
  import { toRawEvent } from './wire.js';
32
+ import { HOME } from '../../store/settings.js';
32
33
  /**
33
34
  * Ask Playwright what the stamped element actually is.
34
35
  *
@@ -53,7 +54,7 @@ async function resolveStamped(page, stamp) {
53
54
  // Read per call, not once at import. A module-level constant would freeze the
54
55
  // override before any caller could set it, which is a footgun for anything that
55
56
  // wants its own directory — a check, or a run recording into a scratch corpus.
56
- const fixturesDir = () => process.env.UNDERSTUDY_FIXTURES_DIR ?? resolve('.understudy/fixtures');
57
+ const fixturesDir = () => process.env.UNDERSTUDY_FIXTURES_DIR ?? join(HOME, 'fixtures');
57
58
  /**
58
59
  * One CDP session per page, reused.
59
60
  *
@@ -135,9 +136,9 @@ async function stashFixture(absolute) {
135
136
  await mkdir(dir, { recursive: true });
136
137
  if (!existsSync(target))
137
138
  await writeFile(target, bytes);
138
- // Relative, so the value means the same thing from the repo root whoever
139
- // replays it.
140
- return relative(process.cwd(), target);
139
+ // Absolute: the fixtures folder is under ~/.understudy, so the path means
140
+ // the same thing whichever folder replays it.
141
+ return target;
141
142
  }
142
143
  export async function recordLive(opts) {
143
144
  const { appSlug, startUrl, maxMinutes = 30, drive, storageState, armWhen, beforeArm, preludeSlugs, onArmed,
@@ -23,10 +23,37 @@
23
23
  * the IR wants, arrived at for free.
24
24
  */
25
25
  import { type RawRecording } from '../../core/recording.js';
26
+ /** The name-based lookups other than text, as stored in `hints.by`. */
27
+ export type NameLookup = 'placeholder' | 'label' | 'title' | 'alt';
28
+ /**
29
+ * Playwright's assertions and waits that a recording keeps, and what each
30
+ * becomes. They are the point of an end-to-end test — without them a flow only
31
+ * checks that what it clicks exists — so they used to be dropped in silence,
32
+ * which was the worst outcome. One the IR can't express is now reported.
33
+ *
34
+ * expect(page).toHaveURL(x) / page.waitForURL(x) → wait_url
35
+ * expect(page).toHaveTitle(x) → assert title
36
+ * expect(locator).toBeVisible() → assert visible
37
+ * expect(locator).toBeHidden() / not.toBeVisible() → assert hidden
38
+ * expect(locator).toHaveText(x) → assert text (whole text)
39
+ * expect(locator).toContainText(x) → assert contains
40
+ * expect(locator).toHaveValue(x) → assert value
41
+ * expect(locator).toBeChecked() / not.toBeChecked() → assert checked / unchecked
42
+ * page.waitForSelector(css) → assert visible
43
+ */
44
+ export declare const KEPT_ASSERTIONS: readonly ["toHaveURL", "toHaveTitle", "toBeVisible", "toBeHidden", "toHaveText", "toContainText", "toHaveValue", "toBeChecked", "waitForURL", "waitForSelector"];
45
+ /** What an `assert` step checks, in `hints.assert`. */
46
+ export type AssertKind = 'visible' | 'hidden' | 'text' | 'contains' | 'value' | 'checked' | 'unchecked' | 'title';
26
47
  export interface ParsedScript {
27
48
  recording: RawRecording;
28
49
  /** Calls that looked like Playwright actions but could not be mapped. */
29
50
  warnings: string[];
51
+ /**
52
+ * Assertions and waits that were NOT kept. Not fatal — the flow still
53
+ * replays — but the flow checks less than the script did, and the caller
54
+ * must be told so rather than find out by opening the recording.
55
+ */
56
+ dropped: string[];
30
57
  }
31
58
  /**
32
59
  * A text constraint, which Playwright lets you write either way.
@@ -27,6 +27,35 @@ import { existsSync } from 'node:fs';
27
27
  import { basename, dirname, isAbsolute, join } from 'node:path';
28
28
  import ts from 'typescript';
29
29
  import { buildRecording, redactValue, } from '../../core/recording.js';
30
+ const NAME_LOOKUPS = {
31
+ getByPlaceholder: 'placeholder',
32
+ getByLabel: 'label',
33
+ getByTitle: 'title',
34
+ getByAltText: 'alt',
35
+ getByText: undefined,
36
+ };
37
+ /**
38
+ * Playwright's assertions and waits that a recording keeps, and what each
39
+ * becomes. They are the point of an end-to-end test — without them a flow only
40
+ * checks that what it clicks exists — so they used to be dropped in silence,
41
+ * which was the worst outcome. One the IR can't express is now reported.
42
+ *
43
+ * expect(page).toHaveURL(x) / page.waitForURL(x) → wait_url
44
+ * expect(page).toHaveTitle(x) → assert title
45
+ * expect(locator).toBeVisible() → assert visible
46
+ * expect(locator).toBeHidden() / not.toBeVisible() → assert hidden
47
+ * expect(locator).toHaveText(x) → assert text (whole text)
48
+ * expect(locator).toContainText(x) → assert contains
49
+ * expect(locator).toHaveValue(x) → assert value
50
+ * expect(locator).toBeChecked() / not.toBeChecked() → assert checked / unchecked
51
+ * page.waitForSelector(css) → assert visible
52
+ */
53
+ export const KEPT_ASSERTIONS = [
54
+ 'toHaveURL', 'toHaveTitle', 'toBeVisible', 'toBeHidden', 'toHaveText',
55
+ 'toContainText', 'toHaveValue', 'toBeChecked', 'waitForURL', 'waitForSelector',
56
+ ];
57
+ /** Waits that need nothing kept: replay already settles the page after every step. */
58
+ const SETTLING_WAITS = new Set(['waitForLoadState', 'waitForNavigation']);
30
59
  /** Terminal calls that are actions rather than refinements. */
31
60
  const ACTIONS = {
32
61
  click: 'click',
@@ -215,8 +244,9 @@ function locatorBit(method, args) {
215
244
  const { name, exact } = readOptions(args[1]);
216
245
  return role ? { role, ...(name !== undefined ? { name } : {}), ...(exact ? { exact } : {}) } : undefined;
217
246
  }
218
- // Playwright's accname falls back to the placeholder, so a placeholder
219
- // lookup and an accessible name are the same thing to us.
247
+ // The lookup is KEPT, not flattened to text: `getByPlaceholder('Email')`
248
+ // replayed as `getByText('Email')` can never match an input, which has no
249
+ // text. See LocatorBit.by.
220
250
  case 'getByPlaceholder':
221
251
  case 'getByLabel':
222
252
  case 'getByText':
@@ -224,7 +254,8 @@ function locatorBit(method, args) {
224
254
  case 'getByAltText': {
225
255
  const name = textMatch(first);
226
256
  const { exact } = readOptions(args[1]);
227
- return name !== undefined ? { name, ...(exact ? { exact } : {}) } : undefined;
257
+ const by = NAME_LOOKUPS[method];
258
+ return name !== undefined ? { name, ...(exact ? { exact } : {}), ...(by ? { by } : {}) } : undefined;
228
259
  }
229
260
  case 'getByTestId': {
230
261
  const id = first ? text(first) : undefined;
@@ -308,17 +339,257 @@ function envVariable(arg) {
308
339
  return e.argumentExpression.text;
309
340
  return undefined;
310
341
  }
342
+ /** Does this bit say WHICH element, rather than only narrowing one? */
343
+ const addresses = (b) => b.role !== undefined || b.name !== undefined || b.css !== undefined || b.testId !== undefined;
344
+ /**
345
+ * Unwind `page.getByRole('navigation').getByText('Login').nth(1)` into one
346
+ * element. Shared by actions and assertions, which address the same way.
347
+ */
348
+ function readTarget(expr) {
349
+ const bits = [];
350
+ let cursor = expr;
351
+ let unknown;
352
+ while (ts.isCallExpression(cursor) && ts.isPropertyAccessExpression(cursor.expression)) {
353
+ const bit = locatorBit(cursor.expression.name.text, cursor.arguments);
354
+ if (!bit)
355
+ unknown ??= cursor.expression.name.text;
356
+ else
357
+ bits.unshift(bit);
358
+ cursor = cursor.expression.expression;
359
+ }
360
+ // The root must be something page-like. `page`, `frame`, a page object's
361
+ // `this.page` — but NOT `expect(...)`, which is an assertion.
362
+ const rootText = cursor.getText();
363
+ const rooted = /(^|\.)page$|^frame$|^context$/.test(rootText);
364
+ // A CHAIN IS SCOPE + TARGET, NOT ONE MERGED ELEMENT.
365
+ //
366
+ // `page.getByRole('navigation').getByText('Login')` addresses the text
367
+ // "Login" *inside* the navigation landmark. Flattening the chain produced
368
+ // role=navigation name="Login" — an element that does not exist, and a
369
+ // locator that would never resolve on replay.
370
+ //
371
+ // So the TARGET is the last link that actually addresses something, and
372
+ // everything before it is scope, kept as a hint rather than folded into the
373
+ // element's own identity.
374
+ let targetIndex = -1;
375
+ for (let i = bits.length - 1; i >= 0; i--) {
376
+ if (addresses(bits[i])) {
377
+ targetIndex = i;
378
+ break;
379
+ }
380
+ }
381
+ const target = targetIndex >= 0 ? bits[targetIndex] : {};
382
+ const scopeBits = targetIndex > 0 ? bits.slice(0, targetIndex).filter(addresses) : [];
383
+ // nth, frameHint and hasText are positional/structural: they apply to the
384
+ // target wherever in the chain they were written. hasText takes the LAST
385
+ // one, matching nth — in practice a filter directly follows the locator it
386
+ // narrows.
387
+ const nth = [...bits].reverse().find((b) => b.nth !== undefined)?.nth;
388
+ const frameHint = bits.find((b) => b.frameHint !== undefined)?.frameHint;
389
+ const hasText = [...bits].reverse().find((b) => b.hasText !== undefined)?.hasText;
390
+ const unsupported = bits.find((b) => b.unsupported !== undefined)?.unsupported;
391
+ return {
392
+ rooted,
393
+ bare: bits.length === 0 && !unknown,
394
+ merged: {
395
+ ...target,
396
+ ...(nth !== undefined ? { nth } : {}),
397
+ ...(frameHint !== undefined ? { frameHint } : {}),
398
+ ...(hasText !== undefined ? { hasText } : {}),
399
+ },
400
+ ...(scopeBits.length
401
+ ? { scope: scopeBits.map((b) => (b.role ? `role=${b.role}` : b.css ? `css=${b.css}` : `name=${b.name?.source}`)) }
402
+ : {}),
403
+ ...(unknown ? { unknown } : {}),
404
+ ...(unsupported ? { unsupported } : {}),
405
+ };
406
+ }
407
+ /** The element's identity fields of an event. */
408
+ function who(m) {
409
+ return {
410
+ ...(m.role ? { role: m.role } : {}),
411
+ // `name` stays a plain string because sig(), selector dedupe and the
412
+ // embeddings all key on it. When the source was a regex, the string is its
413
+ // SOURCE and hints carry the regex-ness so replay can rebuild the real
414
+ // matcher — `exact` would be wrong here, a source like `Version 2\.5`
415
+ // never equals an accessible name.
416
+ ...(m.name !== undefined ? { name: m.name.source } : {}),
417
+ ...(m.exact ? { exact: m.exact } : {}),
418
+ };
419
+ }
420
+ /** The element's fallback addressing fields of an event. */
421
+ function where(m) {
422
+ return {
423
+ ...(m.css ? { css: m.css } : {}),
424
+ ...(m.testId ? { testId: m.testId } : {}),
425
+ ...(m.frameHint ? { frameHint: m.frameHint } : {}),
426
+ };
427
+ }
428
+ /** The hints an addressed event carries, plus any the caller adds. */
429
+ function hintsOf(t, extra = {}) {
430
+ const m = t.merged;
431
+ const hints = {
432
+ ...(m.nth !== undefined ? { nth: m.nth } : {}),
433
+ ...(t.scope ? { scope: t.scope } : {}),
434
+ ...(t.unknown ? { unparsedChainStep: t.unknown } : {}),
435
+ ...(m.hasText
436
+ ? { hasText: m.hasText.source, ...(m.hasText.regex ? { hasTextRegex: true, hasTextFlags: m.hasText.flags } : {}) }
437
+ : {}),
438
+ ...(m.name?.regex ? { nameRegex: true, nameFlags: m.name.flags } : {}),
439
+ ...(m.by ? { by: m.by } : {}),
440
+ ...extra,
441
+ };
442
+ return Object.keys(hints).length ? { hints } : {};
443
+ }
444
+ /**
445
+ * `expect(x).toBeVisible()`, `expect.soft(x).not.toBeChecked()` → its parts.
446
+ * `poll` is reported as its own kind: it takes a function, not a locator.
447
+ */
448
+ function expectCall(node) {
449
+ if (!ts.isPropertyAccessExpression(node.expression))
450
+ return undefined;
451
+ const matcher = node.expression.name.text;
452
+ let recv = node.expression.expression;
453
+ let negated = false;
454
+ if (ts.isPropertyAccessExpression(recv) && recv.name.text === 'not') {
455
+ negated = true;
456
+ recv = recv.expression;
457
+ }
458
+ if (!ts.isCallExpression(recv))
459
+ return undefined;
460
+ const callee = recv.expression;
461
+ const flavour = ts.isIdentifier(callee) && callee.text === 'expect'
462
+ ? 'expect'
463
+ : ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === 'expect'
464
+ ? `expect.${callee.name.text}`
465
+ : undefined;
466
+ if (!flavour)
467
+ return undefined;
468
+ return { matcher, negated, flavour, ...(recv.arguments[0] ? { subject: recv.arguments[0] } : {}) };
469
+ }
470
+ /** Waits that sit in `Promise.all([...])` beside the action that triggers them. */
471
+ const WAIT_METHODS = new Set(['waitForURL', 'waitForSelector', 'waitForLoadState', 'waitForNavigation', 'waitForResponse', 'waitForRequest', 'waitForEvent']);
472
+ const isWaitCall = (e) => {
473
+ const x = ts.isAwaitExpression(e) ? e.expression : e;
474
+ return ts.isCallExpression(x) && ts.isPropertyAccessExpression(x.expression) && WAIT_METHODS.has(x.expression.name.text);
475
+ };
311
476
  export async function parseScript(filePath, appSlug, fallbackUrl) {
312
477
  const source = await readFile(filePath, 'utf8');
313
478
  const sourceFile = ts.createSourceFile(basename(filePath), source, ts.ScriptTarget.Latest,
314
479
  /* setParentNodes */ true, filePath.endsWith('.js') ? ts.ScriptKind.JS : ts.ScriptKind.TS);
315
480
  const events = [];
316
481
  const warnings = [];
482
+ const dropped = [];
317
483
  // A static read cannot know which page it is on, so the last goto stands in.
318
484
  // Anything before the first goto is attributed to the fallback URL.
319
485
  let currentUrl = fallbackUrl ?? '';
320
486
  let startUrl = fallbackUrl ?? '';
487
+ const snippet = (node) => node.getText().replace(/\s+/g, ' ').slice(0, 80);
488
+ const drop = (why, node) => dropped.push(`${why}: ${snippet(node)}`);
489
+ /** A URL wait, from `waitForURL(x)` or `expect(page).toHaveURL(x)`. */
490
+ const pushWaitUrl = (arg, node) => {
491
+ const match = textMatch(arg);
492
+ if (!match)
493
+ return drop('URL wait with a non-literal URL, not kept', node);
494
+ events.push({
495
+ seq: events.length,
496
+ ts: events.length,
497
+ action: 'wait_url',
498
+ value: match.source,
499
+ url: currentUrl,
500
+ resolution: 'script-literal',
501
+ ...(match.regex ? { hints: { urlRegex: true, urlFlags: match.flags } } : {}),
502
+ });
503
+ };
504
+ /** An `assert` step on an element (or, for `title`, the page). */
505
+ const pushAssert = (t, kind, arg, node) => {
506
+ const needsValue = kind === 'text' || kind === 'contains' || kind === 'value' || kind === 'title';
507
+ let valued = {};
508
+ const extra = { assert: kind };
509
+ if (needsValue) {
510
+ const match = textMatch(arg);
511
+ if (match) {
512
+ valued = { value: match.source };
513
+ if (match.regex)
514
+ Object.assign(extra, { valueRegex: true, valueFlags: match.flags });
515
+ // A literal password in an assertion is still a literal password.
516
+ if (kind === 'value' && !match.regex) {
517
+ const hint = t.merged.name?.source || t.merged.testId || t.merged.css || 'field';
518
+ valued = redactValue(hint, match.source, undefined, [t.merged.name?.source, t.merged.css, t.merged.testId].filter(Boolean).join(' '));
519
+ }
520
+ }
521
+ else if (arg && !ts.isArrayLiteralExpression(arg)) {
522
+ valued = readArgument(arg);
523
+ }
524
+ else {
525
+ return drop(`${kind} check with no single expected value, not kept`, node);
526
+ }
527
+ }
528
+ events.push({
529
+ seq: events.length,
530
+ ts: events.length,
531
+ action: 'assert',
532
+ ...who(t.merged),
533
+ ...valued,
534
+ ...where(t.merged),
535
+ url: currentUrl,
536
+ resolution: 'script-literal',
537
+ ...hintsOf(t, extra),
538
+ });
539
+ };
540
+ /** `expect(...)` — kept if the IR can say it, otherwise reported. */
541
+ const visitExpect = (node, ex) => {
542
+ if (SNAPSHOT_CALLS.has(ex.matcher))
543
+ return; // a visual checkpoint, handled above
544
+ if (ex.flavour !== 'expect' && ex.flavour !== 'expect.soft')
545
+ return drop(`${ex.flavour}() is not kept`, node);
546
+ if (!ex.subject)
547
+ return drop('expect() with nothing to check, not kept', node);
548
+ const t = readTarget(ex.subject);
549
+ if (!t.rooted) {
550
+ return drop('assertion on a value or a locator held in a variable, not kept — write the locator inline, e.g. expect(page.getByRole(...))', node);
551
+ }
552
+ const arg = node.arguments[0];
553
+ const { matcher, negated } = ex;
554
+ if (t.bare) {
555
+ if (matcher === 'toHaveURL' && !negated)
556
+ return pushWaitUrl(arg, node);
557
+ if (matcher === 'toHaveTitle' && !negated)
558
+ return pushAssert(t, 'title', arg, node);
559
+ return drop(`page assertion ${negated ? 'not.' : ''}${matcher}() is not kept`, node);
560
+ }
561
+ if (!addresses(t.merged))
562
+ return drop('assertion on an element with no usable locator, not kept', node);
563
+ if (t.unsupported)
564
+ warnings.push(`${t.unsupported} could not be represented: ${snippet(node)}`);
565
+ const kind = matcher === 'toBeVisible' ? (negated ? 'hidden' : 'visible')
566
+ : matcher === 'toBeHidden' ? (negated ? 'visible' : 'hidden')
567
+ : matcher === 'toBeChecked' ? (negated ? 'unchecked' : 'checked')
568
+ : negated ? undefined
569
+ : matcher === 'toHaveText' ? 'text'
570
+ : matcher === 'toContainText' ? 'contains'
571
+ : matcher === 'toHaveValue' ? 'value'
572
+ : undefined;
573
+ if (!kind)
574
+ return drop(`assertion ${negated ? 'not.' : ''}${matcher}() is not kept`, node);
575
+ pushAssert(t, kind, arg, node);
576
+ };
321
577
  const visit = (node) => {
578
+ // `Promise.all([page.waitForURL(x), page.click(y)])` — the wait is written
579
+ // first but happens after the click it waits on. Replay is sequential, so
580
+ // the actions go first and the waits after them.
581
+ if (ts.isArrayLiteralExpression(node) &&
582
+ ts.isCallExpression(node.parent) &&
583
+ /^Promise\.(all|allSettled|race)$/.test(node.parent.expression.getText()) &&
584
+ node.elements.some(isWaitCall)) {
585
+ for (const e of node.elements)
586
+ if (!isWaitCall(e))
587
+ visit(e);
588
+ for (const e of node.elements)
589
+ if (isWaitCall(e))
590
+ visit(e);
591
+ return;
592
+ }
322
593
  // VISUAL CHECKPOINTS, WHICH ARE NOT PAGE METHODS.
323
594
  //
324
595
  // `expect(page).toHaveScreenshot('x.png')` is a chain off expect(), and a
@@ -349,9 +620,17 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
349
620
  });
350
621
  }
351
622
  else {
352
- warnings.push(`visual checkpoint with no literal name: ${node.getText().slice(0, 70)}`);
623
+ warnings.push(`visual checkpoint with no literal name: ${snippet(node)}`);
353
624
  }
354
625
  }
626
+ // ASSERTIONS. These used to vanish without a word, leaving a flow that
627
+ // only proved its buttons exist. See KEPT_ASSERTIONS.
628
+ const ex = expectCall(node);
629
+ if (ex) {
630
+ visitExpect(node, ex);
631
+ // The subject's own chain is addressing, not actions — don't walk it.
632
+ return;
633
+ }
355
634
  }
356
635
  if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
357
636
  const method = node.expression.name.text;
@@ -373,68 +652,36 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
373
652
  });
374
653
  }
375
654
  else {
376
- warnings.push(`${method}() cannot be expressed by the IR, step DROPPED: ${node.getText().slice(0, 70)}`);
655
+ warnings.push(`${method}() cannot be expressed by the IR, step DROPPED: ${snippet(node)}`);
377
656
  }
378
657
  }
379
- if (action) {
380
- // Unwind the chain back to its root, collecting addressing bits.
381
- const bits = [];
382
- let cursor = node.expression.expression;
383
- let rooted = false;
384
- let unknown;
385
- while (ts.isCallExpression(cursor) && ts.isPropertyAccessExpression(cursor.expression)) {
386
- const bit = locatorBit(cursor.expression.name.text, cursor.arguments);
387
- if (!bit)
388
- unknown ??= cursor.expression.name.text;
389
- else
390
- bits.unshift(bit);
391
- cursor = cursor.expression.expression;
392
- }
393
- // The root must be something page-like. `page`, `frame`, a page object's
394
- // `this.page` — but NOT `expect(...)`, which is an assertion.
395
- const rootText = cursor.getText();
396
- rooted = /(^|\.)page$|^frame$|^context$/.test(rootText) || rootText === 'page';
397
- if (rooted) {
398
- // A CHAIN IS SCOPE + TARGET, NOT ONE MERGED ELEMENT.
399
- //
400
- // `page.getByRole('navigation').getByText('Login')` addresses the
401
- // text "Login" *inside* the navigation landmark. Flattening the chain
402
- // produced role=navigation name="Login" — an element that does not
403
- // exist, and a locator that would never resolve on replay.
404
- //
405
- // So the TARGET is the last link that actually addresses something,
406
- // and everything before it is scope, kept as a hint rather than
407
- // folded into the element's own identity.
408
- const addresses = (b) => b.role !== undefined || b.name !== undefined || b.css !== undefined || b.testId !== undefined;
409
- let targetIndex = -1;
410
- for (let i = bits.length - 1; i >= 0; i--) {
411
- if (addresses(bits[i])) {
412
- targetIndex = i;
413
- break;
414
- }
658
+ // WAITS on the page.
659
+ if (!action && WAIT_METHODS.has(method) && readTarget(node.expression.expression).rooted) {
660
+ const arg = node.arguments[0];
661
+ if (method === 'waitForURL')
662
+ pushWaitUrl(arg, node);
663
+ else if (method === 'waitForSelector') {
664
+ const css = arg ? text(arg) : undefined;
665
+ if (css === undefined)
666
+ drop('waitForSelector with a non-literal selector, not kept', node);
667
+ else {
668
+ const state = readState(node.arguments[1]);
669
+ const kind = state === 'hidden' || state === 'detached' ? 'hidden' : 'visible';
670
+ pushAssert({ rooted: true, bare: false, merged: { css } }, kind, undefined, node);
415
671
  }
416
- const target = targetIndex >= 0 ? bits[targetIndex] : {};
417
- const scopeBits = targetIndex > 0 ? bits.slice(0, targetIndex).filter(addresses) : [];
418
- // nth, frameHint and hasText are positional/structural: they apply to
419
- // the target wherever in the chain they were written. hasText takes
420
- // the LAST one, matching nth — in practice a filter directly follows
421
- // the locator it narrows.
422
- const nth = [...bits].reverse().find((b) => b.nth !== undefined)?.nth;
423
- const frameHint = bits.find((b) => b.frameHint !== undefined)?.frameHint;
424
- const hasText = [...bits].reverse().find((b) => b.hasText !== undefined)?.hasText;
425
- const unsupported = bits.find((b) => b.unsupported !== undefined)?.unsupported;
426
- if (unsupported) {
427
- warnings.push(`${unsupported} could not be represented: ${node.getText().slice(0, 70)}`);
672
+ }
673
+ else if (!SETTLING_WAITS.has(method)) {
674
+ drop(`${method}() is not kept (replay can't wait on network events)`, node);
675
+ }
676
+ // waitForLoadState / waitForNavigation: replay settles after every step anyway.
677
+ }
678
+ if (action) {
679
+ const t = readTarget(node.expression.expression);
680
+ if (t.rooted) {
681
+ const merged = t.merged;
682
+ if (t.unsupported) {
683
+ warnings.push(`${t.unsupported} could not be represented: ${snippet(node)}`);
428
684
  }
429
- const merged = {
430
- ...target,
431
- ...(nth !== undefined ? { nth } : {}),
432
- ...(frameHint !== undefined ? { frameHint } : {}),
433
- ...(hasText !== undefined ? { hasText } : {}),
434
- };
435
- const scope = scopeBits.length
436
- ? scopeBits.map((b) => (b.role ? `role=${b.role}` : b.css ? `css=${b.css}` : `name=${b.name?.source}`))
437
- : undefined;
438
685
  if (action === 'goto') {
439
686
  const urlArg = node.arguments[0];
440
687
  const literal = urlArg ? text(urlArg) : undefined;
@@ -458,11 +705,11 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
458
705
  });
459
706
  }
460
707
  else {
461
- warnings.push(`goto with a non-literal URL: ${node.getText().slice(0, 70)}`);
708
+ warnings.push(`goto with a non-literal URL: ${snippet(node)}`);
462
709
  }
463
710
  }
464
- else if (!merged.role && !merged.name && !merged.css && !merged.testId) {
465
- warnings.push(`unaddressable ${action}: ${node.getText().slice(0, 70)}`);
711
+ else if (!addresses(merged)) {
712
+ warnings.push(`unaddressable ${action}: ${snippet(node)}`);
466
713
  }
467
714
  else {
468
715
  const raw = readArgument(node.arguments[0]);
@@ -481,40 +728,12 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
481
728
  seq: events.length,
482
729
  ts: events.length,
483
730
  action,
484
- ...(merged.role ? { role: merged.role } : {}),
485
- // `name` stays a plain string because sig(), selector dedupe and
486
- // the embeddings all key on it. When the source was a regex, the
487
- // string is its SOURCE and hints carry the regex-ness so replay
488
- // can rebuild the real matcher — `exact` would be wrong here, a
489
- // source like `Version 2\.5` never equals an accessible name.
490
- ...(merged.name !== undefined ? { name: merged.name.source } : {}),
491
- ...(merged.exact ? { exact: merged.exact } : {}),
731
+ ...who(merged),
492
732
  ...valued,
493
- ...(merged.css ? { css: merged.css } : {}),
494
- ...(merged.testId ? { testId: merged.testId } : {}),
495
- ...(merged.frameHint ? { frameHint: merged.frameHint } : {}),
733
+ ...where(merged),
496
734
  url: currentUrl,
497
735
  resolution: 'script-literal',
498
- ...(merged.nth !== undefined || unknown || scope || merged.hasText || merged.name?.regex
499
- ? {
500
- hints: {
501
- ...(merged.nth !== undefined ? { nth: merged.nth } : {}),
502
- ...(scope ? { scope } : {}),
503
- ...(unknown ? { unparsedChainStep: unknown } : {}),
504
- ...(merged.hasText
505
- ? {
506
- hasText: merged.hasText.source,
507
- ...(merged.hasText.regex
508
- ? { hasTextRegex: true, hasTextFlags: merged.hasText.flags }
509
- : {}),
510
- }
511
- : {}),
512
- ...(merged.name?.regex
513
- ? { nameRegex: true, nameFlags: merged.name.flags }
514
- : {}),
515
- },
516
- }
517
- : {}),
736
+ ...hintsOf(t),
518
737
  });
519
738
  }
520
739
  }
@@ -526,5 +745,16 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
526
745
  return {
527
746
  recording: buildRecording({ source: 'script', origin: filePath, appSlug, startUrl }, events.map((e, i) => ({ ...e, seq: i }))),
528
747
  warnings,
748
+ dropped,
529
749
  };
530
750
  }
751
+ /** `{ state: 'hidden' }` → 'hidden'. */
752
+ function readState(node) {
753
+ if (!node || !ts.isObjectLiteralExpression(node))
754
+ return undefined;
755
+ for (const prop of node.properties) {
756
+ if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'state')
757
+ return text(prop.initializer);
758
+ }
759
+ return undefined;
760
+ }
@@ -20,6 +20,7 @@
20
20
  * of git.
21
21
  */
22
22
  import type { BrowserContext } from 'playwright';
23
+ /** Under ~/.understudy, not the current folder — see recording-store.ts. */
23
24
  export declare const SESSIONS_DIR: string;
24
25
  /** Playwright's storageState payload. Opaque to us — we store and replay it. */
25
26
  export type StorageState = Awaited<ReturnType<BrowserContext['storageState']>>;