@nifrajs/e2e 0.0.0-stage → 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.
Files changed (84) hide show
  1. package/CHANGELOG.md +23 -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 +315 -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 +166 -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 +52 -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 +129 -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 +6 -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 +103 -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 +108 -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 +169 -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 +111 -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 +26 -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 +105 -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 +49 -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 +236 -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/session.ts ADDED
@@ -0,0 +1,178 @@
1
+ import { fillRoutePath } from "@nifrajs/core/pattern"
2
+ import { type E2EApp, type E2EPaths, e2eUrl, serveTestApp } from "@nifrajs/testing/e2e"
3
+ import { type Agent, createAgent, type E2EModel } from "./agent.ts"
4
+ import { type Cache, type CacheOptions, createCache } from "./cache.ts"
5
+ import {
6
+ type Clock,
7
+ E2EError,
8
+ type Engine,
9
+ type EngineFactory,
10
+ type HydrationMode,
11
+ realClock,
12
+ } from "./engine.ts"
13
+ import type { UrlSource } from "./expect.ts"
14
+ import { type LocatorContext, Screen } from "./locator.ts"
15
+ import { playwrightEngine } from "./playwright.ts"
16
+
17
+ /** The `:name` segments of a route path. */
18
+ export type PathParams<P extends string> = P extends `${string}:${infer Rest}`
19
+ ? Rest extends `${infer Name}/${infer Tail}`
20
+ ? Name | PathParams<`/${Tail}`>
21
+ : Rest
22
+ : never
23
+
24
+ export interface OpenOptions<P extends string> {
25
+ readonly params?: Record<PathParams<P>, string | number>
26
+ readonly query?: Readonly<Record<string, string | number | boolean>>
27
+ }
28
+
29
+ /** A route with `:params` must be given them; one without takes only an optional query. */
30
+ export type OpenArgs<P extends string> = [PathParams<P>] extends [never]
31
+ ? [options?: { readonly query?: OpenOptions<P>["query"] }]
32
+ : [
33
+ options: {
34
+ readonly params: Record<PathParams<P>, string | number>
35
+ readonly query?: OpenOptions<P>["query"]
36
+ },
37
+ ]
38
+
39
+ export interface E2EOptions {
40
+ /** Defaults to the Playwright engine (`@nifrajs/e2e/playwright`), which needs `playwright` installed. */
41
+ readonly engine?: EngineFactory
42
+ /** A `testSession().cookies` jar (or anything with `header()`): logs the browser in without a UI login. */
43
+ readonly cookies?: { header(): string }
44
+ readonly hydration?: HydrationMode
45
+ /** ms an action waits for its element. Default 5000. */
46
+ readonly actionTimeout?: number
47
+ /** ms an assertion retries before it fails. Default 5000. */
48
+ readonly assertionTimeout?: number
49
+ readonly pollInterval?: number
50
+ readonly clock?: Clock
51
+ /** Answers agent steps. Without it `t.agent` rejects with `MODEL_MISSING`; locator tests need none. */
52
+ readonly model?: E2EModel | undefined
53
+ /** Words every agent step should know: the product, its jargon, what a plan is called. */
54
+ readonly agentContext?: string
55
+ /** Characters of page outline one model call may carry. Default 12000. */
56
+ readonly snapshotChars?: number
57
+ /** The replay cache for `agent.act`. On by default; `false` turns it off. */
58
+ readonly cache?: CacheOptions | false
59
+ }
60
+
61
+ export interface E2ESession<App> extends UrlSource, AsyncDisposable {
62
+ readonly baseUrl: string
63
+ readonly screen: Screen
64
+ readonly agent: Agent
65
+ open<P extends E2EPaths<App>>(path: P, ...args: OpenArgs<P>): Promise<void>
66
+ close(): Promise<void>
67
+ }
68
+
69
+ export function parseCookieHeader(header: string): { name: string; value: string }[] {
70
+ const cookies: { name: string; value: string }[] = []
71
+ for (const raw of header.split(";")) {
72
+ const part = raw.trim()
73
+ const at = part.indexOf("=")
74
+ if (at <= 0) continue
75
+ cookies.push({ name: part.slice(0, at), value: part.slice(at + 1) })
76
+ }
77
+ return cookies
78
+ }
79
+
80
+ export function buildPath(
81
+ pattern: string,
82
+ params: Readonly<Record<string, string | number>> | undefined,
83
+ query: Readonly<Record<string, string | number | boolean>> | undefined,
84
+ ): string {
85
+ const given: Record<string, string> = {}
86
+ for (const [name, value] of Object.entries(params ?? {})) given[name] = String(value)
87
+ const filled = fillRoutePath(pattern, given)
88
+ if (!filled.ok) {
89
+ const [missing] = filled.missing
90
+ throw new E2EError(
91
+ "BAD_PATH",
92
+ missing === undefined
93
+ ? `route ${pattern} cannot carry the value of "${filled.invalid.join('", "')}"`
94
+ : `route ${pattern} needs the param "${missing}"`,
95
+ )
96
+ }
97
+ const search = new URLSearchParams()
98
+ for (const [key, value] of Object.entries(query ?? {})) search.set(key, String(value))
99
+ const text = search.toString()
100
+ return text === "" ? filled.path : `${filled.path}?${text}`
101
+ }
102
+
103
+ /**
104
+ * Serve `app` on an ephemeral port and drive it from a browser. The session is `AsyncDisposable`:
105
+ * `await using t = await e2e(app)` closes the browser and the server at scope exit.
106
+ */
107
+ export async function e2e<App extends E2EApp>(
108
+ app: App,
109
+ options: E2EOptions = {},
110
+ ): Promise<E2ESession<App>> {
111
+ const factory = options.engine ?? playwrightEngine()
112
+ const served = await serveTestApp(app)
113
+ let engine: Engine
114
+ try {
115
+ engine = await factory({
116
+ baseUrl: served.baseUrl,
117
+ cookies: options.cookies === undefined ? [] : parseCookieHeader(options.cookies.header()),
118
+ hydration: options.hydration ?? "auto",
119
+ })
120
+ } catch (error) {
121
+ await served.stop()
122
+ throw error
123
+ }
124
+ const cache: Cache | undefined = options.cache === false ? undefined : createCache(options.cache)
125
+ const context: LocatorContext = {
126
+ engine,
127
+ clock: options.clock ?? realClock,
128
+ actionTimeout: options.actionTimeout ?? 5000,
129
+ assertionTimeout: options.assertionTimeout ?? 5000,
130
+ pollInterval: options.pollInterval ?? 100,
131
+ onCheck: cache === undefined ? undefined : (passed) => cache.onCheck(passed),
132
+ }
133
+ const agent = createAgent({
134
+ engine,
135
+ clock: context.clock,
136
+ pollInterval: context.pollInterval,
137
+ actionTimeout: context.actionTimeout,
138
+ model: options.model,
139
+ context: options.agentContext,
140
+ snapshotChars: options.snapshotChars ?? 12_000,
141
+ origin: new URL(served.baseUrl).origin,
142
+ cache,
143
+ navigate: (path) => {
144
+ // biome-ignore lint/plugin/requireSafetyCommentForTypeAssertion: a model-chosen path is not a declared route; e2eUrl refuses anything that is not a same-origin path.
145
+ return engine.goto(e2eUrl<App>(served.baseUrl, path as E2EPaths<App>))
146
+ },
147
+ })
148
+ let closed: Promise<void> | undefined
149
+ const close = (): Promise<void> => {
150
+ closed ??= engine.close().finally(() => served.stop())
151
+ return closed
152
+ }
153
+ return {
154
+ baseUrl: served.baseUrl,
155
+ context,
156
+ screen: new Screen(context),
157
+ agent,
158
+ open: async (path, ...args) => {
159
+ // biome-ignore lint/plugin/requireSafetyCommentForTypeAssertion: OpenArgs is a tuple of this one options shape per route; buildPath rejects a missing param at run time.
160
+ const given = args[0] as
161
+ | {
162
+ params?: Record<string, string | number>
163
+ query?: Record<string, string | number | boolean>
164
+ }
165
+ | undefined
166
+ // biome-ignore lint/plugin/requireSafetyCommentForTypeAssertion: the type was checked at the call site (P extends E2EPaths<App>); e2eUrl re-checks same-origin at run time.
167
+ const route = buildPath(path, given?.params, given?.query) as E2EPaths<App>
168
+ return engine.goto(e2eUrl<App>(served.baseUrl, route))
169
+ },
170
+ url: () => engine.url(),
171
+ path: async () => {
172
+ const url = new URL(await engine.url())
173
+ return `${url.pathname}${url.search}`
174
+ },
175
+ close,
176
+ [Symbol.asyncDispose]: close,
177
+ }
178
+ }
@@ -0,0 +1,46 @@
1
+ export const INTERACTIVE =
2
+ /^\s*- (?:button|link|textbox|searchbox|checkbox|radio|combobox|listbox|option|tab|menuitem|switch|slider|spinbutton|heading|dialog|alertdialog|alert|status)\b/
3
+
4
+ /**
5
+ * Fit a snapshot into `maxChars`: long lines are shortened, and when the whole is still too long the
6
+ * controls and headings are kept first and the rest fills the room that is left, in page order.
7
+ * Dropped runs are marked, so the model knows the page goes on.
8
+ */
9
+ export function pruneSnapshot(snapshot: string, maxChars: number, maxLine = 240): string {
10
+ const lines = snapshot
11
+ .split("\n")
12
+ .map((line) => (line.length > maxLine ? `${line.slice(0, maxLine - 1)}…` : line))
13
+ if (lines.reduce((total, line) => total + line.length + 1, 0) <= maxChars) return lines.join("\n")
14
+
15
+ const keep = new Set<number>()
16
+ let used = 0
17
+ const take = (index: number, line: string): void => {
18
+ const cost = line.length + 1
19
+ if (used + cost > maxChars) return
20
+ keep.add(index)
21
+ used += cost
22
+ }
23
+ lines.forEach((line, index) => {
24
+ if (INTERACTIVE.test(line)) take(index, line)
25
+ })
26
+ lines.forEach((line, index) => {
27
+ if (!keep.has(index)) take(index, line)
28
+ })
29
+
30
+ const out: string[] = []
31
+ let omitted = 0
32
+ const flush = (): void => {
33
+ if (omitted > 0) out.push(` … (${omitted} lines omitted)`)
34
+ omitted = 0
35
+ }
36
+ lines.forEach((line, index) => {
37
+ if (keep.has(index)) {
38
+ flush()
39
+ out.push(line)
40
+ } else {
41
+ omitted += 1
42
+ }
43
+ })
44
+ flush()
45
+ return out.join("\n")
46
+ }