@nifrajs/e2e 0.0.0-placeholder → 5.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +128 -0
- package/dist/agent.d.ts +119 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +315 -0
- package/dist/agent.js.map +1 -0
- package/dist/cache.d.ts +84 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +166 -0
- package/dist/cache.js.map +1 -0
- package/dist/decision.d.ts +54 -0
- package/dist/decision.d.ts.map +1 -0
- package/dist/decision.js +122 -0
- package/dist/decision.js.map +1 -0
- package/dist/engine.d.ts +75 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +13 -0
- package/dist/engine.js.map +1 -0
- package/dist/evidence.d.ts +14 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +52 -0
- package/dist/evidence.js.map +1 -0
- package/dist/expect.d.ts +28 -0
- package/dist/expect.d.ts.map +1 -0
- package/dist/expect.js +88 -0
- package/dist/expect.js.map +1 -0
- package/dist/fake.d.ts +35 -0
- package/dist/fake.d.ts.map +1 -0
- package/dist/fake.js +129 -0
- package/dist/fake.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/record.d.ts +3 -0
- package/dist/internal/record.d.ts.map +1 -0
- package/dist/internal/record.js +6 -0
- package/dist/internal/record.js.map +1 -0
- package/dist/locator.d.ts +53 -0
- package/dist/locator.d.ts.map +1 -0
- package/dist/locator.js +103 -0
- package/dist/locator.js.map +1 -0
- package/dist/params.d.ts +44 -0
- package/dist/params.d.ts.map +1 -0
- package/dist/params.js +108 -0
- package/dist/params.js.map +1 -0
- package/dist/playwright.d.ts +72 -0
- package/dist/playwright.d.ts.map +1 -0
- package/dist/playwright.js +169 -0
- package/dist/playwright.js.map +1 -0
- package/dist/replay.d.ts +34 -0
- package/dist/replay.d.ts.map +1 -0
- package/dist/replay.js +111 -0
- package/dist/replay.js.map +1 -0
- package/dist/route.d.ts +7 -0
- package/dist/route.d.ts.map +1 -0
- package/dist/route.js +26 -0
- package/dist/route.js.map +1 -0
- package/dist/session.d.ts +62 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +105 -0
- package/dist/session.js.map +1 -0
- package/dist/snapshot.d.ts +8 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +49 -0
- package/dist/snapshot.js.map +1 -0
- package/package.json +75 -1
- package/src/agent.ts +525 -0
- package/src/cache.ts +229 -0
- package/src/decision.ts +152 -0
- package/src/engine.ts +92 -0
- package/src/evidence.ts +58 -0
- package/src/expect.ts +171 -0
- package/src/fake.ts +185 -0
- package/src/index.ts +64 -0
- package/src/internal/record.ts +5 -0
- package/src/locator.ts +157 -0
- package/src/params.ts +128 -0
- package/src/playwright.ts +236 -0
- package/src/replay.ts +153 -0
- package/src/route.ts +26 -0
- package/src/session.ts +178 -0
- 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,236 @@
|
|
|
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
|
+
const text = el.innerText ?? el.textContent ?? ""
|
|
131
|
+
return value === undefined ? { visible, text } : { visible, text, value }
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function translate(error: unknown): unknown {
|
|
136
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
137
|
+
if (message.includes("strict mode violation")) return new E2EError("LOCATOR_AMBIGUOUS", message)
|
|
138
|
+
if (error instanceof Error && error.name === "TimeoutError")
|
|
139
|
+
return new E2EError("LOCATOR_NOT_FOUND", message)
|
|
140
|
+
return error
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function loadBrowser(options: PlaywrightEngineOptions): Promise<PwBrowser> {
|
|
144
|
+
if (options.launch !== undefined) return options.launch()
|
|
145
|
+
const load = options.load ?? ((specifier: string) => import(specifier))
|
|
146
|
+
let loaded: Record<
|
|
147
|
+
string,
|
|
148
|
+
{ launch(options: { headless: boolean }): Promise<PwBrowser> } | undefined
|
|
149
|
+
>
|
|
150
|
+
try {
|
|
151
|
+
// 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.
|
|
152
|
+
loaded = (await load("playwright")) as typeof loaded
|
|
153
|
+
} catch (cause) {
|
|
154
|
+
throw new E2EError(
|
|
155
|
+
"ENGINE_MISSING",
|
|
156
|
+
"@nifrajs/e2e/playwright needs the playwright package - add it to devDependencies",
|
|
157
|
+
{ cause },
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
const type = loaded[options.browser ?? "chromium"]
|
|
161
|
+
if (type === undefined)
|
|
162
|
+
throw new E2EError("ENGINE_MISSING", `playwright has no browser "${options.browser}"`)
|
|
163
|
+
return type.launch({ headless: options.headless ?? true })
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function settle(page: PwPage, mode: HydrationMode, timeout: number): Promise<void> {
|
|
167
|
+
if (mode === "off") return
|
|
168
|
+
let state: string
|
|
169
|
+
try {
|
|
170
|
+
state = await page.evaluate<string>(HYDRATION_PROBE)
|
|
171
|
+
} catch {
|
|
172
|
+
await page.waitForLoadState("domcontentloaded")
|
|
173
|
+
state = await page.evaluate<string>(HYDRATION_PROBE)
|
|
174
|
+
}
|
|
175
|
+
if (state !== "pending") return
|
|
176
|
+
try {
|
|
177
|
+
await page.waitForSelector("html[data-nifra-hydrated]", { state: "attached", timeout })
|
|
178
|
+
} catch {
|
|
179
|
+
throw new E2EError(
|
|
180
|
+
"HYDRATION_TIMEOUT",
|
|
181
|
+
`the page did not set data-nifra-hydrated within ${timeout} ms; pass hydration: "off" if it is not a hydrated nifra page`,
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** A browser engine over Playwright (`playwright` is an optional peer, loaded on first use). */
|
|
187
|
+
export function playwrightEngine(options: PlaywrightEngineOptions = {}): EngineFactory {
|
|
188
|
+
return async (init) => {
|
|
189
|
+
const browser = await loadBrowser(options)
|
|
190
|
+
const hydrationTimeout = options.hydrationTimeout ?? 5000
|
|
191
|
+
let context: PwContext
|
|
192
|
+
let page: PwPage
|
|
193
|
+
try {
|
|
194
|
+
context = await browser.newContext()
|
|
195
|
+
if (init.cookies.length > 0) {
|
|
196
|
+
await context.addCookies(init.cookies.map((cookie) => ({ ...cookie, url: init.baseUrl })))
|
|
197
|
+
}
|
|
198
|
+
page = await context.newPage()
|
|
199
|
+
} catch (error) {
|
|
200
|
+
await browser.close()
|
|
201
|
+
throw error
|
|
202
|
+
}
|
|
203
|
+
const engine: Engine = {
|
|
204
|
+
async goto(url) {
|
|
205
|
+
await page.goto(url, { waitUntil: "load" })
|
|
206
|
+
await settle(page, init.hydration, hydrationTimeout)
|
|
207
|
+
},
|
|
208
|
+
async url() {
|
|
209
|
+
return page.url()
|
|
210
|
+
},
|
|
211
|
+
async resolve(selector) {
|
|
212
|
+
return toLocator(page, selector).evaluateAll(readElements)
|
|
213
|
+
},
|
|
214
|
+
async snapshot() {
|
|
215
|
+
await settle(page, init.hydration, hydrationTimeout)
|
|
216
|
+
return page.locator("body").ariaSnapshot()
|
|
217
|
+
},
|
|
218
|
+
async act(selector, action: ElementAction, timeout) {
|
|
219
|
+
await settle(page, init.hydration, hydrationTimeout)
|
|
220
|
+
const locator = toLocator(page, selector)
|
|
221
|
+
try {
|
|
222
|
+
if (action.kind === "tap") await locator.click({ timeout })
|
|
223
|
+
else if (action.kind === "fill") await locator.fill(action.value, { timeout })
|
|
224
|
+
else await locator.press(action.key, { timeout })
|
|
225
|
+
} catch (error) {
|
|
226
|
+
throw translate(error)
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
async close() {
|
|
230
|
+
await context.close()
|
|
231
|
+
await browser.close()
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
return engine
|
|
235
|
+
}
|
|
236
|
+
}
|
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
|
+
}
|