@nifrajs/e2e 0.0.0-stage → 5.14.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 (84) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/LICENSE +21 -0
  3. package/README.md +127 -2
  4. package/dist/agent.d.ts +119 -0
  5. package/dist/agent.d.ts.map +1 -0
  6. package/dist/agent.js +312 -0
  7. package/dist/agent.js.map +1 -0
  8. package/dist/cache.d.ts +84 -0
  9. package/dist/cache.d.ts.map +1 -0
  10. package/dist/cache.js +162 -0
  11. package/dist/cache.js.map +1 -0
  12. package/dist/decision.d.ts +54 -0
  13. package/dist/decision.d.ts.map +1 -0
  14. package/dist/decision.js +122 -0
  15. package/dist/decision.js.map +1 -0
  16. package/dist/engine.d.ts +75 -0
  17. package/dist/engine.d.ts.map +1 -0
  18. package/dist/engine.js +13 -0
  19. package/dist/engine.js.map +1 -0
  20. package/dist/evidence.d.ts +14 -0
  21. package/dist/evidence.d.ts.map +1 -0
  22. package/dist/evidence.js +49 -0
  23. package/dist/evidence.js.map +1 -0
  24. package/dist/expect.d.ts +28 -0
  25. package/dist/expect.d.ts.map +1 -0
  26. package/dist/expect.js +88 -0
  27. package/dist/expect.js.map +1 -0
  28. package/dist/fake.d.ts +35 -0
  29. package/dist/fake.d.ts.map +1 -0
  30. package/dist/fake.js +124 -0
  31. package/dist/fake.js.map +1 -0
  32. package/dist/index.d.ts +11 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +8 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/internal/record.d.ts +3 -0
  37. package/dist/internal/record.d.ts.map +1 -0
  38. package/dist/internal/record.js +4 -0
  39. package/dist/internal/record.js.map +1 -0
  40. package/dist/locator.d.ts +53 -0
  41. package/dist/locator.d.ts.map +1 -0
  42. package/dist/locator.js +102 -0
  43. package/dist/locator.js.map +1 -0
  44. package/dist/params.d.ts +44 -0
  45. package/dist/params.d.ts.map +1 -0
  46. package/dist/params.js +93 -0
  47. package/dist/params.js.map +1 -0
  48. package/dist/playwright.d.ts +72 -0
  49. package/dist/playwright.d.ts.map +1 -0
  50. package/dist/playwright.js +165 -0
  51. package/dist/playwright.js.map +1 -0
  52. package/dist/replay.d.ts +34 -0
  53. package/dist/replay.d.ts.map +1 -0
  54. package/dist/replay.js +105 -0
  55. package/dist/replay.js.map +1 -0
  56. package/dist/route.d.ts +7 -0
  57. package/dist/route.d.ts.map +1 -0
  58. package/dist/route.js +20 -0
  59. package/dist/route.js.map +1 -0
  60. package/dist/session.d.ts +62 -0
  61. package/dist/session.d.ts.map +1 -0
  62. package/dist/session.js +98 -0
  63. package/dist/session.js.map +1 -0
  64. package/dist/snapshot.d.ts +8 -0
  65. package/dist/snapshot.d.ts.map +1 -0
  66. package/dist/snapshot.js +44 -0
  67. package/dist/snapshot.js.map +1 -0
  68. package/package.json +73 -4
  69. package/src/agent.ts +525 -0
  70. package/src/cache.ts +229 -0
  71. package/src/decision.ts +152 -0
  72. package/src/engine.ts +92 -0
  73. package/src/evidence.ts +58 -0
  74. package/src/expect.ts +171 -0
  75. package/src/fake.ts +185 -0
  76. package/src/index.ts +64 -0
  77. package/src/internal/record.ts +5 -0
  78. package/src/locator.ts +157 -0
  79. package/src/params.ts +128 -0
  80. package/src/playwright.ts +237 -0
  81. package/src/replay.ts +153 -0
  82. package/src/route.ts +26 -0
  83. package/src/session.ts +178 -0
  84. package/src/snapshot.ts +46 -0
package/src/params.ts ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * A value a step may use but the model must never read: it is typed into the page by name, and
3
+ * `String(secret)`, `JSON.stringify(secret)` and template literals all print the name only.
4
+ */
5
+ export class Secret {
6
+ readonly name: string
7
+ readonly #value: string
8
+
9
+ constructor(name: string, value: string) {
10
+ this.name = name
11
+ this.#value = value
12
+ }
13
+
14
+ /** Read by the step runner when it types the value; nothing else should call it. */
15
+ static reveal(secret: Secret): string {
16
+ return secret.#value
17
+ }
18
+
19
+ toJSON(): string {
20
+ return `[secret:${this.name}]`
21
+ }
22
+
23
+ toString(): string {
24
+ return `[secret:${this.name}]`
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Run-varying data (a generated email, a timestamp). The model and the page get the value; the replay
30
+ * cache keys on the fact that it varies, so a new value does not miss, and re-types the new value.
31
+ */
32
+ export class Unique {
33
+ readonly value: string
34
+
35
+ constructor(value: string) {
36
+ this.value = value
37
+ }
38
+
39
+ toString(): string {
40
+ return this.value
41
+ }
42
+ }
43
+
44
+ export function unique(value: string | number): Unique {
45
+ return new Unique(String(value))
46
+ }
47
+
48
+ export type Param = string | number | boolean | Secret | Unique
49
+ export type Params = Readonly<Record<string, Param>>
50
+
51
+ const PLACEHOLDER = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g
52
+
53
+ /** `{name}` becomes the param's value, except a secret, which stays `{name}` and is listed by name. */
54
+ export function forModel(
55
+ text: string,
56
+ params: Params,
57
+ ): { readonly text: string; readonly secrets: readonly string[] } {
58
+ const secrets = new Set<string>()
59
+ const out = text.replace(PLACEHOLDER, (whole, name: string) => {
60
+ const param = params[name]
61
+ if (param === undefined) return whole
62
+ if (param instanceof Secret) {
63
+ secrets.add(name)
64
+ return whole
65
+ }
66
+ return String(param)
67
+ })
68
+ return { text: out, secrets: [...secrets] }
69
+ }
70
+
71
+ /** `{name}` becomes the real value, a secret's included. Run only on text headed for the page. */
72
+ export function forPage(text: string, params: Params): string {
73
+ return text.replace(PLACEHOLDER, (whole, name: string) => {
74
+ const param = params[name]
75
+ if (param === undefined) return whole
76
+ return param instanceof Secret ? Secret.reveal(param) : String(param)
77
+ })
78
+ }
79
+
80
+ /** A secret and the name it was given, which is the placeholder that stands in for its value. */
81
+ export type NamedSecret = readonly [name: string, secret: Secret]
82
+
83
+ /** Every secret value in `text` replaced by its placeholder, so a page that echoes one cannot leak it. */
84
+ export function redactSecrets(text: string, secrets: readonly NamedSecret[]): string {
85
+ let out = text
86
+ for (const [name, secret] of secrets) {
87
+ const value = Secret.reveal(secret)
88
+ if (value !== "") out = out.split(value).join(`{${name}}`)
89
+ }
90
+ return out
91
+ }
92
+
93
+ export function redact(text: string, params: Params): string {
94
+ const secrets: NamedSecret[] = []
95
+ for (const [name, param] of Object.entries(params)) {
96
+ if (param instanceof Secret) secrets.push([name, param])
97
+ }
98
+ return redactSecrets(text, secrets)
99
+ }
100
+
101
+ /** The params as a replay-cache key sees them: plain values by value, a secret or a unique by kind. */
102
+ export function keyParams(params: Params): string {
103
+ const entries = Object.entries(params)
104
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
105
+ .map(([name, param]) => [
106
+ name,
107
+ param instanceof Secret ? "<secret>" : param instanceof Unique ? "<unique>" : String(param),
108
+ ])
109
+ return JSON.stringify(entries)
110
+ }
111
+
112
+ /** Every unique value found literally in `text` turned back into its `{name}`, so a recording survives a new value. */
113
+ export function templatize(text: string, params: Params): string {
114
+ let out = text
115
+ for (const [name, param] of Object.entries(params)) {
116
+ if (param instanceof Unique && param.value !== "")
117
+ out = out.split(param.value).join(`{${name}}`)
118
+ }
119
+ return out
120
+ }
121
+
122
+ /** `{name}` becomes the current value of a unique param; any other placeholder stays. */
123
+ export function fillUnique(text: string, params: Params): string {
124
+ return text.replace(PLACEHOLDER, (whole, name: string) => {
125
+ const param = params[name]
126
+ return param instanceof Unique ? param.value : whole
127
+ })
128
+ }
@@ -0,0 +1,237 @@
1
+ import {
2
+ E2EError,
3
+ type ElementAction,
4
+ type ElementState,
5
+ type Engine,
6
+ type EngineFactory,
7
+ type HydrationMode,
8
+ type Selector,
9
+ } from "./engine.ts"
10
+
11
+ /** The slice of Playwright this engine calls, so the package carries no Playwright types and tests can stand in for it. */
12
+ export interface PwFinder {
13
+ getByRole(role: string, options?: { name?: string; exact?: boolean }): PwLocator
14
+ getByLabel(text: string, options?: { exact?: boolean }): PwLocator
15
+ getByText(text: string, options?: { exact?: boolean }): PwLocator
16
+ getByTestId(id: string): PwLocator
17
+ }
18
+
19
+ export interface PwLocator extends PwFinder {
20
+ filter(options: { hasText: string }): PwLocator
21
+ nth(index: number): PwLocator
22
+ evaluateAll<R>(pageFunction: (elements: readonly unknown[]) => R): Promise<R>
23
+ click(options: { timeout: number }): Promise<void>
24
+ fill(value: string, options: { timeout: number }): Promise<void>
25
+ press(key: string, options: { timeout: number }): Promise<void>
26
+ }
27
+
28
+ export interface PwPage extends PwFinder {
29
+ locator(selector: string): { ariaSnapshot(): Promise<string> }
30
+ goto(url: string, options: { waitUntil: "load" }): Promise<unknown>
31
+ url(): string
32
+ evaluate<R>(expression: string): Promise<R>
33
+ waitForSelector(
34
+ selector: string,
35
+ options: { state: "attached"; timeout: number },
36
+ ): Promise<unknown>
37
+ waitForLoadState(state: "domcontentloaded"): Promise<void>
38
+ }
39
+
40
+ export interface PwContext {
41
+ addCookies(cookies: { name: string; value: string; url: string }[]): Promise<void>
42
+ newPage(): Promise<PwPage>
43
+ close(): Promise<void>
44
+ }
45
+
46
+ export interface PwBrowser {
47
+ newContext(): Promise<PwContext>
48
+ close(): Promise<void>
49
+ }
50
+
51
+ export interface PlaywrightEngineOptions {
52
+ readonly browser?: "chromium" | "firefox" | "webkit"
53
+ readonly headless?: boolean
54
+ /** ms to wait for `data-nifra-hydrated` before `HYDRATION_TIMEOUT`. Default 5000. */
55
+ readonly hydrationTimeout?: number
56
+ /** Replaces the Playwright launch; used by tests. */
57
+ readonly launch?: () => Promise<PwBrowser>
58
+ /** Replaces the dynamic `import()` of `playwright`; used by tests. */
59
+ readonly load?: (specifier: string) => Promise<unknown>
60
+ }
61
+
62
+ const HYDRATION_PROBE =
63
+ "document.documentElement.hasAttribute('data-nifra-hydrated') ? 'ready' : " +
64
+ "document.querySelector('script[type=module][src]') ? 'pending' : 'none'"
65
+
66
+ function toLocator(page: PwPage, selector: Selector): PwLocator {
67
+ let located: PwLocator | undefined
68
+ for (const step of selector) {
69
+ const scope: PwFinder = located ?? page
70
+ switch (step.kind) {
71
+ case "role": {
72
+ const options: { name?: string; exact?: boolean } = {}
73
+ if (step.name !== undefined) options.name = step.name
74
+ if (step.exact !== undefined) options.exact = step.exact
75
+ located = scope.getByRole(step.role, options)
76
+ break
77
+ }
78
+ case "label":
79
+ located = scope.getByLabel(
80
+ step.text,
81
+ step.exact === undefined ? undefined : { exact: step.exact },
82
+ )
83
+ break
84
+ case "text":
85
+ located = scope.getByText(
86
+ step.text,
87
+ step.exact === undefined ? undefined : { exact: step.exact },
88
+ )
89
+ break
90
+ case "testId":
91
+ located = scope.getByTestId(step.id)
92
+ break
93
+ case "hasText":
94
+ if (located === undefined) {
95
+ throw new E2EError("LOCATOR_NOT_FOUND", "a text filter needs a locator to narrow")
96
+ }
97
+ located = located.filter({ hasText: step.text })
98
+ break
99
+ case "nth":
100
+ if (located === undefined) {
101
+ throw new E2EError("LOCATOR_NOT_FOUND", "nth needs a locator to pick from")
102
+ }
103
+ located = located.nth(step.index)
104
+ break
105
+ }
106
+ }
107
+ if (located === undefined) {
108
+ throw new E2EError("LOCATOR_NOT_FOUND", "an empty locator has nothing to find")
109
+ }
110
+ return located
111
+ }
112
+
113
+ // Runs in the page, so it carries no imports and no DOM lib types.
114
+ function readElements(elements: readonly unknown[]): ElementState[] {
115
+ return elements.map((node) => {
116
+ // biome-ignore lint/plugin/requireSafetyCommentForTypeAssertion: evaluateAll hands over the DOM elements a locator matched; this is the only shape read from them.
117
+ const el = node as {
118
+ innerText?: string
119
+ textContent?: string | null
120
+ value?: unknown
121
+ getBoundingClientRect(): { width: number; height: number }
122
+ checkVisibility?(options: object): boolean
123
+ }
124
+ const box = el.getBoundingClientRect()
125
+ const shown =
126
+ el.checkVisibility === undefined ||
127
+ el.checkVisibility({ checkVisibilityCSS: true, visibilityProperty: true })
128
+ const value = typeof el.value === "string" ? el.value : undefined
129
+ const visible = box.width > 0 && box.height > 0 && shown
130
+ // biome-ignore lint/performance/useDomNodeTextContent: innerText is the rendered text a user sees; textContent includes hidden nodes
131
+ const text = el.innerText ?? el.textContent ?? ""
132
+ return value === undefined ? { visible, text } : { visible, text, value }
133
+ })
134
+ }
135
+
136
+ function translate(error: unknown): unknown {
137
+ const message = error instanceof Error ? error.message : String(error)
138
+ if (message.includes("strict mode violation")) return new E2EError("LOCATOR_AMBIGUOUS", message)
139
+ if (error instanceof Error && error.name === "TimeoutError")
140
+ return new E2EError("LOCATOR_NOT_FOUND", message)
141
+ return error
142
+ }
143
+
144
+ async function loadBrowser(options: PlaywrightEngineOptions): Promise<PwBrowser> {
145
+ if (options.launch !== undefined) return options.launch()
146
+ const load = options.load ?? ((specifier: string) => import(specifier))
147
+ let loaded: Record<
148
+ string,
149
+ { launch(options: { headless: boolean }): Promise<PwBrowser> } | undefined
150
+ >
151
+ try {
152
+ // biome-ignore lint/plugin/requireSafetyCommentForTypeAssertion: the module's exports are read only as browser types with a launch(); a missing one is refused just below.
153
+ loaded = (await load("playwright")) as typeof loaded
154
+ } catch (cause) {
155
+ throw new E2EError(
156
+ "ENGINE_MISSING",
157
+ "@nifrajs/e2e/playwright needs the playwright package - add it to devDependencies",
158
+ { cause },
159
+ )
160
+ }
161
+ const type = loaded[options.browser ?? "chromium"]
162
+ if (type === undefined)
163
+ throw new E2EError("ENGINE_MISSING", `playwright has no browser "${options.browser}"`)
164
+ return type.launch({ headless: options.headless ?? true })
165
+ }
166
+
167
+ async function settle(page: PwPage, mode: HydrationMode, timeout: number): Promise<void> {
168
+ if (mode === "off") return
169
+ let state: string
170
+ try {
171
+ state = await page.evaluate<string>(HYDRATION_PROBE)
172
+ } catch {
173
+ await page.waitForLoadState("domcontentloaded")
174
+ state = await page.evaluate<string>(HYDRATION_PROBE)
175
+ }
176
+ if (state !== "pending") return
177
+ try {
178
+ await page.waitForSelector("html[data-nifra-hydrated]", { state: "attached", timeout })
179
+ } catch {
180
+ throw new E2EError(
181
+ "HYDRATION_TIMEOUT",
182
+ `the page did not set data-nifra-hydrated within ${timeout} ms; pass hydration: "off" if it is not a hydrated nifra page`,
183
+ )
184
+ }
185
+ }
186
+
187
+ /** A browser engine over Playwright (`playwright` is an optional peer, loaded on first use). */
188
+ export function playwrightEngine(options: PlaywrightEngineOptions = {}): EngineFactory {
189
+ return async (init) => {
190
+ const browser = await loadBrowser(options)
191
+ const hydrationTimeout = options.hydrationTimeout ?? 5000
192
+ let context: PwContext
193
+ let page: PwPage
194
+ try {
195
+ context = await browser.newContext()
196
+ if (init.cookies.length > 0) {
197
+ await context.addCookies(init.cookies.map((cookie) => ({ ...cookie, url: init.baseUrl })))
198
+ }
199
+ page = await context.newPage()
200
+ } catch (error) {
201
+ await browser.close()
202
+ throw error
203
+ }
204
+ const engine: Engine = {
205
+ async goto(url) {
206
+ await page.goto(url, { waitUntil: "load" })
207
+ await settle(page, init.hydration, hydrationTimeout)
208
+ },
209
+ async url() {
210
+ return page.url()
211
+ },
212
+ async resolve(selector) {
213
+ return toLocator(page, selector).evaluateAll(readElements)
214
+ },
215
+ async snapshot() {
216
+ await settle(page, init.hydration, hydrationTimeout)
217
+ return page.locator("body").ariaSnapshot()
218
+ },
219
+ async act(selector, action: ElementAction, timeout) {
220
+ await settle(page, init.hydration, hydrationTimeout)
221
+ const locator = toLocator(page, selector)
222
+ try {
223
+ if (action.kind === "tap") await locator.click({ timeout })
224
+ else if (action.kind === "fill") await locator.fill(action.value, { timeout })
225
+ else await locator.press(action.key, { timeout })
226
+ } catch (error) {
227
+ throw translate(error)
228
+ }
229
+ },
230
+ async close() {
231
+ await context.close()
232
+ await browser.close()
233
+ },
234
+ }
235
+ return engine
236
+ }
237
+ }
package/src/replay.ts ADDED
@@ -0,0 +1,153 @@
1
+ import type { CacheEntry, RecordedAction } from "./cache.ts"
2
+ import { targetSelector } from "./decision.ts"
3
+ import { type Clock, E2EError, type Engine, type Selector } from "./engine.ts"
4
+ import { checkEvidence, type EvidenceCheck } from "./evidence.ts"
5
+ import { fillUnique, forPage, type Params } from "./params.ts"
6
+ import { normalizeRoute } from "./route.ts"
7
+
8
+ /** Why a replay stopped short of finishing the recorded actions. */
9
+ export type StopReason =
10
+ | "target-not-found"
11
+ | "ambiguous"
12
+ | "end-mismatch"
13
+ | "action-uncertain"
14
+ | "route-mismatch"
15
+
16
+ export type ReplayOutcome =
17
+ | { readonly ok: true }
18
+ | {
19
+ readonly ok: false
20
+ readonly reason: StopReason
21
+ readonly detail: string
22
+ /** The actions that did run, in order; the one that stopped the replay is not among them. */
23
+ readonly performed: readonly RecordedAction[]
24
+ }
25
+
26
+ export interface ReplayDeps {
27
+ readonly engine: Engine
28
+ readonly clock: Clock
29
+ readonly pollInterval: number
30
+ readonly actionTimeout: number
31
+ /** Origin of the app under test, so the port does not count as part of a route. */
32
+ readonly origin: string
33
+ readonly navigate: (path: string) => Promise<void>
34
+ /** The redacted, unpruned outline of the page. */
35
+ readonly observe: () => Promise<string>
36
+ }
37
+
38
+ export function withoutNth(selector: Selector): Selector {
39
+ return selector.filter((step) => step.kind !== "nth")
40
+ }
41
+
42
+ export async function visibleCount(engine: Engine, selector: Selector): Promise<number> {
43
+ return (await engine.resolve(selector)).filter((state) => state.visible).length
44
+ }
45
+
46
+ /**
47
+ * Re-run recorded actions with no model. Each control is found by the same role, name, label, text
48
+ * or test id it had when recorded and must match exactly as often as it did then: a replay that
49
+ * cannot find its target, or finds more than it should, stops rather than tap a near miss.
50
+ */
51
+ export async function replayEntry(
52
+ deps: ReplayDeps,
53
+ entry: CacheEntry,
54
+ params: Params,
55
+ ): Promise<ReplayOutcome> {
56
+ const { engine, clock } = deps
57
+ const performed: RecordedAction[] = []
58
+ const stop = (reason: StopReason, detail: string): ReplayOutcome => ({
59
+ ok: false,
60
+ reason,
61
+ detail,
62
+ performed,
63
+ })
64
+
65
+ const start = normalizeRoute(await engine.url(), deps.origin)
66
+ if (start !== entry.startRoute) {
67
+ return stop("route-mismatch", `started at ${start}, recorded at ${entry.startRoute}`)
68
+ }
69
+
70
+ for (const action of entry.actions) {
71
+ if (action.kind === "goto") {
72
+ try {
73
+ await deps.navigate(forPage(action.path, params))
74
+ } catch (error) {
75
+ if (error instanceof E2EError || error instanceof TypeError) {
76
+ return stop("action-uncertain", `goto ${action.path} failed: ${error.message}`)
77
+ }
78
+ throw error
79
+ }
80
+ performed.push(action)
81
+ continue
82
+ }
83
+
84
+ const selector = targetSelector(action.target)
85
+ if (action.target.nth !== undefined) {
86
+ const settled = await settleMatches(deps, withoutNth(selector), action.matches)
87
+ if (settled !== undefined) return stop(settled.reason, settled.detail)
88
+ }
89
+ try {
90
+ if (action.kind === "tap") {
91
+ await engine.act(selector, { kind: "tap" }, deps.actionTimeout)
92
+ } else if (action.kind === "fill") {
93
+ await engine.act(
94
+ selector,
95
+ { kind: "fill", value: forPage(action.value, params) },
96
+ deps.actionTimeout,
97
+ )
98
+ } else {
99
+ await engine.act(selector, { kind: "press", key: action.key }, deps.actionTimeout)
100
+ }
101
+ } catch (error) {
102
+ if (!(error instanceof E2EError)) throw error
103
+ const what = `${action.kind} ${JSON.stringify(action.target)}`
104
+ if (error.code === "LOCATOR_NOT_FOUND")
105
+ return stop("target-not-found", `${what}: ${error.message}`)
106
+ if (error.code === "LOCATOR_AMBIGUOUS") return stop("ambiguous", `${what}: ${error.message}`)
107
+ return stop("action-uncertain", `${what}: ${error.message}`)
108
+ }
109
+ performed.push(action)
110
+ }
111
+
112
+ const deadline = clock.now() + deps.actionTimeout
113
+ for (;;) {
114
+ const route = normalizeRoute(await engine.url(), deps.origin)
115
+ const snapshot = await deps.observe()
116
+ let evidence: EvidenceCheck
117
+ if (route === entry.end.route) {
118
+ evidence = checkEvidence(
119
+ {
120
+ appeared: entry.end.appeared.map((line) => fillUnique(line, params)),
121
+ disappeared: entry.end.disappeared.map((line) => fillUnique(line, params)),
122
+ },
123
+ snapshot,
124
+ )
125
+ } else {
126
+ evidence = { ok: false, detail: `ended at ${route}, recorded ${entry.end.route}` }
127
+ }
128
+ if (evidence.ok) return { ok: true }
129
+ const remaining = deadline - clock.now()
130
+ if (remaining <= 0) return stop("end-mismatch", evidence.detail)
131
+ await clock.sleep(Math.min(deps.pollInterval, remaining))
132
+ }
133
+ }
134
+
135
+ /** Waits for `selector` to match `expected` visible elements; the stop it ends in otherwise. */
136
+ async function settleMatches(
137
+ deps: ReplayDeps,
138
+ selector: Selector,
139
+ expected: number,
140
+ ): Promise<{ reason: StopReason; detail: string } | undefined> {
141
+ const deadline = deps.clock.now() + deps.actionTimeout
142
+ for (;;) {
143
+ const count = await visibleCount(deps.engine, selector)
144
+ if (count === expected) return undefined
145
+ const remaining = deadline - deps.clock.now()
146
+ if (remaining <= 0) {
147
+ return count === 0
148
+ ? { reason: "target-not-found", detail: "no visible element matches the recorded target" }
149
+ : { reason: "ambiguous", detail: `${count} elements match, ${expected} did when recorded` }
150
+ }
151
+ await deps.clock.sleep(Math.min(deps.pollInterval, remaining))
152
+ }
153
+ }
package/src/route.ts ADDED
@@ -0,0 +1,26 @@
1
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
2
+
3
+ /** An id, uuid, long hex, timestamp or token-looking value: something that differs per run or per record. */
4
+ function varies(part: string): boolean {
5
+ if (/^\d+$/.test(part) || UUID.test(part) || /^[0-9a-f]{16,}$/i.test(part)) return true
6
+ return part.length >= 20 && /\d/.test(part) && /[A-Za-z]/.test(part)
7
+ }
8
+
9
+ /**
10
+ * Where a page is, for deciding whether a recording still starts and ends in the same place: the
11
+ * path and query with id-like parts replaced by `:id`, the origin left out when it is the app's own
12
+ * (the port changes every run), the hash dropped.
13
+ */
14
+ export function normalizeRoute(url: string, appOrigin: string): string {
15
+ const target = new URL(url)
16
+ const origin = target.origin === appOrigin ? "" : target.origin
17
+ const path = target.pathname
18
+ .split("/")
19
+ .map((part) => (varies(part) ? ":id" : part))
20
+ .join("/")
21
+ const query = [...target.searchParams.entries()]
22
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
23
+ .map(([key, value]) => `${key}=${varies(value) ? ":id" : value}`)
24
+ .join("&")
25
+ return `${origin}${path}${query === "" ? "" : `?${query}`}`
26
+ }