@owlmeans/test-ui 0.1.18-rc.8 → 0.1.18

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 (69) hide show
  1. package/README.md +10 -7
  2. package/agent-meta/manifest.json +3 -3
  3. package/agent-meta/skills/testing-ui/SKILL.md +209 -23
  4. package/build/browser/types.d.ts +22 -0
  5. package/build/browser/types.d.ts.map +1 -0
  6. package/build/browser/types.js +2 -0
  7. package/build/browser/types.js.map +1 -0
  8. package/build/browser.d.ts +8 -16
  9. package/build/browser.d.ts.map +1 -1
  10. package/build/browser.js +38 -41
  11. package/build/browser.js.map +1 -1
  12. package/build/consent/types.d.ts +36 -0
  13. package/build/consent/types.d.ts.map +1 -0
  14. package/build/consent/types.js +2 -0
  15. package/build/consent/types.js.map +1 -0
  16. package/build/consent.d.ts +4 -0
  17. package/build/consent.d.ts.map +1 -0
  18. package/build/consent.js +41 -0
  19. package/build/consent.js.map +1 -0
  20. package/build/consts.local.d.ts +9 -0
  21. package/build/consts.local.d.ts.map +1 -0
  22. package/build/consts.local.js +9 -0
  23. package/build/consts.local.js.map +1 -0
  24. package/build/index.d.ts +8 -0
  25. package/build/index.d.ts.map +1 -1
  26. package/build/index.js +3 -0
  27. package/build/index.js.map +1 -1
  28. package/build/marketing-consent.d.ts +5 -0
  29. package/build/marketing-consent.d.ts.map +1 -0
  30. package/build/marketing-consent.js +4 -0
  31. package/build/marketing-consent.js.map +1 -0
  32. package/build/mount.d.ts +2 -27
  33. package/build/mount.d.ts.map +1 -1
  34. package/build/mount.js +11 -4
  35. package/build/mount.js.map +1 -1
  36. package/build/page/types.d.ts +141 -0
  37. package/build/page/types.d.ts.map +1 -0
  38. package/build/page/types.js +2 -0
  39. package/build/page/types.js.map +1 -0
  40. package/build/page.d.ts +4 -0
  41. package/build/page.d.ts.map +1 -0
  42. package/build/page.js +168 -0
  43. package/build/page.js.map +1 -0
  44. package/build/supervisor/types.d.ts +56 -0
  45. package/build/supervisor/types.d.ts.map +1 -0
  46. package/build/supervisor/types.js +2 -0
  47. package/build/supervisor/types.js.map +1 -0
  48. package/build/supervisor.d.ts +9 -86
  49. package/build/supervisor.d.ts.map +1 -1
  50. package/build/supervisor.js +65 -123
  51. package/build/supervisor.js.map +1 -1
  52. package/build/types.d.ts +46 -0
  53. package/build/types.d.ts.map +1 -0
  54. package/build/types.js +2 -0
  55. package/build/types.js.map +1 -0
  56. package/package.json +11 -11
  57. package/src/browser/types.ts +22 -0
  58. package/src/browser.ts +43 -40
  59. package/src/consent/types.ts +38 -0
  60. package/src/consent.ts +48 -0
  61. package/src/consts.local.ts +12 -0
  62. package/src/index.ts +8 -0
  63. package/src/marketing-consent.ts +8 -0
  64. package/src/mount.ts +12 -32
  65. package/src/page/types.ts +144 -0
  66. package/src/page.ts +194 -0
  67. package/src/supervisor/types.ts +55 -0
  68. package/src/supervisor.ts +83 -187
  69. package/src/types.ts +47 -0
package/src/consent.ts ADDED
@@ -0,0 +1,48 @@
1
+ import type { BrowserContext, Page } from 'playwright'
2
+ import { DEFAULT_CONSENT_GEO_COUNTRY, DEFAULT_CONSENT_TRACE_PATH } from './consts.local.js'
3
+ import type { ConsentGeoMock, ConsentGeoMockOptions, ConsentGeoTestHelper } from './consent/types.js'
4
+
5
+ export const createConsentGeoTestHelper = (): ConsentGeoTestHelper => {
6
+ const mockConsentGeo = async (target: Page | BrowserContext, geo: ConsentGeoMock): Promise<void> => {
7
+ const options: ConsentGeoMockOptions & { country: string, delayMs: number, path: string } = {
8
+ country: typeof geo === 'string' ? geo : geo.country ?? DEFAULT_CONSENT_GEO_COUNTRY,
9
+ delayMs: typeof geo === 'string' ? 0 : geo.delayMs ?? 0,
10
+ path: typeof geo === 'string' ? DEFAULT_CONSENT_TRACE_PATH : geo.path ?? DEFAULT_CONSENT_TRACE_PATH,
11
+ ...(typeof geo !== 'string' && geo.fail != null ? { fail: geo.fail } : {}),
12
+ ...(typeof geo !== 'string' && geo.gpc != null ? { gpc: geo.gpc } : {}),
13
+ }
14
+
15
+ // A string, not a function: it runs in the page, and this package compiles without DOM types.
16
+ await target.addInitScript({ content: `(function(arg){
17
+ if (arg.gpc != null) {
18
+ Object.defineProperty(Navigator.prototype, 'globalPrivacyControl', { get: function () { return arg.gpc }, configurable: true })
19
+ }
20
+ window.__consentTraceCalls = 0
21
+ var original = window.fetch.bind(window)
22
+ window.fetch = function (input, init) {
23
+ var href = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
24
+ var url = new URL(href, location.href)
25
+ if (url.origin !== location.origin || url.pathname !== arg.path) return original(input, init)
26
+ window.__consentTraceCalls += 1
27
+ var answer = function () {
28
+ if (arg.fail === 'hang') return new Promise(function () {})
29
+ if (arg.fail === true) return Promise.resolve(new Response('not found', { status: 404 }))
30
+ return Promise.resolve(new Response(
31
+ 'fl=0f0\\nh=' + location.hostname + '\\nip=203.0.113.7\\nts=0\\nvisit_scheme=https\\ncolo=TST\\nloc=' + arg.country + '\\n',
32
+ { status: 200, headers: { 'content-type': 'text/plain' } }
33
+ ))
34
+ }
35
+ return arg.delayMs > 0
36
+ ? new Promise(function (resolve) { setTimeout(resolve, arg.delayMs) }).then(answer)
37
+ : answer()
38
+ }
39
+ })(${JSON.stringify(options)})` })
40
+ }
41
+
42
+ const traceCalls = async (page: Page): Promise<number> =>
43
+ await page.evaluate('window.__consentTraceCalls || 0') as number
44
+
45
+ return { mockConsentGeo, traceCalls }
46
+ }
47
+
48
+ export const consentGeoTestHelper = createConsentGeoTestHelper()
@@ -0,0 +1,12 @@
1
+ export const DEFAULT_MARKETING_CONSENT_TIMEOUT = 30_000
2
+
3
+ export const DEFAULT_SUPERVISOR_PATH = '/authentication/login/pk-supervisor'
4
+
5
+ /** A consent country: a mocked visitor is asked unless the spec says otherwise. */
6
+ export const DEFAULT_CONSENT_GEO_COUNTRY = 'PL'
7
+
8
+ /** `@owlmeans/consent`'s `CONSENT_TRACE_PATH`, repeated: this package depends on no consent package. */
9
+ export const DEFAULT_CONSENT_TRACE_PATH = '/cdn-cgi/trace'
10
+
11
+ /** What `acceptConsent` treats as "nothing to answer": the store settled on a decision without UI. */
12
+ export const CONSENT_SETTLED_WITHOUT_UI = 'html[data-consent="decided"], html[data-consent="idle"]'
package/src/index.ts CHANGED
@@ -1,4 +1,12 @@
1
1
  export * from './browser.js'
2
+ export * from './consent.js'
3
+ export type * from './consent/types.js'
4
+ export type * from './browser/types.js'
5
+ export * from './marketing-consent.js'
6
+ export type * from './types.js'
2
7
  export * from './mount.js'
8
+ export * from './page.js'
9
+ export type * from './page/types.js'
3
10
  export * from './supervisor.js'
11
+ export type * from './supervisor/types.js'
4
12
  export type { Browser, BrowserContext, Locator, Page } from 'playwright'
@@ -0,0 +1,8 @@
1
+ import type { Page } from 'playwright'
2
+ import { makePageHelper } from './page.js'
3
+ import type { AnswerMarketingConsentOptions } from './page/types.js'
4
+
5
+ /** @deprecated compat:factory-refactor — use `makePageHelper(page).answerMarketingConsent(…)` */
6
+ export const answerMarketingConsent = async (
7
+ page: Page, opts?: AnswerMarketingConsentOptions
8
+ ): Promise<boolean> => await makePageHelper(page).answerMarketingConsent(opts)
package/src/mount.ts CHANGED
@@ -1,32 +1,6 @@
1
- import type { Page } from 'playwright'
2
- import { launchBrowser } from './browser.js'
3
-
4
- export interface MountOptions {
5
- /**
6
- * URL the harness is reachable at. The consuming package is in charge
7
- * of producing it — typically a Vite dev server pointed at
8
- * `node_modules/@owlmeans/test-ui/harness/` plus a per-package
9
- * `mount.tsx` that registers the components under test, OR an
10
- * inlined `data:text/html,...` URL for the simplest smoke tests.
11
- */
12
- url: string
13
- /**
14
- * Component name registered in the harness. Appended as `?component=`.
15
- * Omit when the harness mounts a single fixed root.
16
- */
17
- component?: string
18
- /**
19
- * JSON-serialisable props passed to the component. Encoded into the
20
- * URL as `?props=<json>` for the harness's `mount.tsx` to read.
21
- */
22
- props?: Record<string, unknown>
23
- }
24
-
25
- export interface Mounted {
26
- page: Page
27
- /** Closes the page's browser context — the shared browser stays alive. */
28
- close: () => Promise<void>
29
- }
1
+ import { browserHelper } from './browser.js'
2
+ import { consentGeoTestHelper } from './consent.js'
3
+ import type { Mounted, MountOptions } from './types.js'
30
4
 
31
5
  const buildUrl = (opts: MountOptions): string => {
32
6
  const params = new URLSearchParams()
@@ -48,13 +22,19 @@ const buildUrl = (opts: MountOptions): string => {
48
22
  * try { expect(await page.locator('h1').textContent()).toBe('Sign in') }
49
23
  * finally { await close() }
50
24
  *
51
- * `closeBrowser()` from `afterAll` tears down the shared browser at the end of the suite.
25
+ * `browserHelper.closeBrowser()` from `afterAll` tears down the shared browser at the end of the suite.
52
26
  */
53
27
  export const mountComponent = async (opts: MountOptions): Promise<Mounted> => {
54
- const browser = await launchBrowser()
28
+ const browser = await browserHelper.launchBrowser()
55
29
  const context = await browser.newContext()
30
+ if (opts.consentGeo != null) {
31
+ await consentGeoTestHelper.mockConsentGeo(context, opts.consentGeo)
32
+ }
56
33
  const page = await context.newPage()
57
- await page.goto(buildUrl(opts))
34
+ await page.goto(buildUrl(opts), {
35
+ waitUntil: opts.waitUntil ?? 'domcontentloaded',
36
+ ...(opts.timeout != null ? { timeout: opts.timeout } : {}),
37
+ })
58
38
  return {
59
39
  page,
60
40
  close: async () => { await context.close() },
@@ -0,0 +1,144 @@
1
+ export interface AnswerMarketingConsentOptions {
2
+ /**
3
+ * Which choice to save when the step is shown. `'all'` (the default) ticks the "select all"
4
+ * checkbox (every consent, and the Terms row while it is up — see {@link terms} for what is left
5
+ * of that) before saving; `'none'` saves with every item left unchecked, which is a valid,
6
+ * fully-compliant state on its own; `'skip'` clicks "Skip for now" instead of saving anything —
7
+ * only valid when a Terms box is not on screen (nothing calls it there; see {@link terms}).
8
+ */
9
+ accept?: 'none' | 'all' | 'skip'
10
+ /**
11
+ * When a Terms row is on screen (`appendMarketingConsent({ terms: 'step' })`), `'accept'` (the
12
+ * default) ends with it ticked. `'leave'` ends with it unticked, even after a select-all — for a
13
+ * spec that means to drive the blocked state itself; the confirm click below still fires (with `{ force: true }`, since
14
+ * the control is never truly `disabled`), and this helper then EXPECTS the box to still be up
15
+ * afterward rather than treating that as a failure.
16
+ */
17
+ terms?: 'accept' | 'leave'
18
+ timeout?: number
19
+ }
20
+
21
+ /** What {@link PageHelper.acceptConsent} waits for. */
22
+ export interface AcceptConsentOptions {
23
+ /** How long the dialog may take to appear, and then to go away. Defaults to 5s. */
24
+ timeout?: number
25
+ }
26
+
27
+ export interface DispatcherLoginOptions {
28
+ dispatcherPath?: string
29
+ /** What counts as "arrived" for the navigation. Defaults to `domcontentloaded` — see `MountOptions.waitUntil`. */
30
+ waitUntil?: 'commit' | 'domcontentloaded' | 'load' | 'networkidle'
31
+ /**
32
+ * Answer the marketing-consent step if it is shown right after the dispatcher navigates away.
33
+ * Defaults to `'save'` (select-all and save) — see {@link PageHelper.answerMarketingConsent}. Pass
34
+ * `'ignore'` to skip the call entirely, e.g. in a spec that answers the step itself.
35
+ */
36
+ marketingConsent?: 'save' | 'ignore'
37
+ }
38
+
39
+ export interface SupervisorFormLoginOptions {
40
+ baseUrl: string
41
+ /** Target user id / email. */
42
+ userId: string
43
+ /** Supervisor private key (e.g. `ed25519:<base64>` from `.env.dev.secrets`). */
44
+ pk: string
45
+ /** Login path; defaults to the standard supervisor route. */
46
+ path?: string
47
+ /** Predicate/URL fragment that signals a successful landing (default: leaving the login path). */
48
+ expectPath?: string
49
+ timeout?: number
50
+ /**
51
+ * What counts as "arrived" for the initial navigation. Defaults to `domcontentloaded`.
52
+ *
53
+ * See the note on `MountOptions.waitUntil`: `load` is playwright's default and is wrong for a
54
+ * real application, because it waits for every subresource — a tag manager, an analytics beacon
55
+ * or any pixel that never settles holds it open until the navigation times out, with the login
56
+ * form rendered and fillable the whole time.
57
+ */
58
+ waitUntil?: 'commit' | 'domcontentloaded' | 'load' | 'networkidle'
59
+ /**
60
+ * What to do about a cookie-consent dialog covering the form. Defaults to `accept`, because an
61
+ * OwlMeans app will not start an authentication flow until consent is answered — see
62
+ * {@link PageHelper.acceptConsent}. Pass `ignore` only in a spec that answers the dialog itself.
63
+ */
64
+ consent?: 'accept' | 'ignore'
65
+ /** When set, capture the filled login form (`supervisor-login-form.png`) before submit. */
66
+ screenshotDir?: string
67
+ /**
68
+ * Answer the marketing-consent step if it is shown right after landing. Defaults to `'save'`
69
+ * (select-all and save) — see {@link PageHelper.answerMarketingConsent}. Pass `'ignore'` to skip the call
70
+ * entirely, e.g. in a spec that answers the step itself.
71
+ */
72
+ marketingConsent?: 'save' | 'ignore'
73
+ }
74
+
75
+ /** Driving one page of an OwlMeans app: consent dialogs, the login flows, screenshots. */
76
+ export interface PageHelper {
77
+ /**
78
+ * Answer the marketing-consent full-page step (`@owlmeans/web-marketing-consent`) if it is shown
79
+ * right after login, so a spec driving {@link PageHelper.loginViaSupervisorForm} or
80
+ * {@link PageHelper.loginViaDispatcher} is never blocked behind it.
81
+ *
82
+ * The screen is opt-in per app, and most apps/environments will not have it wired in — that makes
83
+ * detecting its ABSENCE cheaply the whole point. A plain `waitFor` on `[data-marketing-consent]`
84
+ * alone would cost the full `timeout` on every login of every app that never renders it (the same
85
+ * caveat `acceptConsent` documents for the cookie dialog). Instead this races the step's own root
86
+ * against the generic OwlMeans "the app has already landed" / "still on the login screen" markers
87
+ * this helper's own login flows already wait on (`#app-prompt`, `[data-login-method]`) — by the
88
+ * time a login flow calls this, one of those has typically already rendered, so the race resolves
89
+ * as soon as it does: no fixed sleep, and in the common "step absent" case, no material added
90
+ * latency over what the login flow already paid to get here.
91
+ *
92
+ * @returns whether the step was actually shown and answered (including the error/skip fallback);
93
+ * `false` when it never appeared within `timeout`, which is the expected result everywhere
94
+ * the screen is not yet configured or the visitor already has saved consents.
95
+ * @throws if a Terms box could not be confirmed (a `[data-marketing-consent-terms-error]`, or the
96
+ * box is still up with nowhere left to go — Skip is never offered there on purpose).
97
+ */
98
+ answerMarketingConsent: (opts?: AnswerMarketingConsentOptions) => Promise<boolean>
99
+ /**
100
+ * Inject a pre-generated bearer into an app that uses the standard owlmeans
101
+ * dispatcher: navigate to `/dispatcher?token=...` so the web app authenticates
102
+ * and redirects home natively. Note: apps that override the DISPATCHER route
103
+ * (e.g. to force an external IdP) should use {@link PageHelper.loginViaSupervisorForm}.
104
+ */
105
+ loginViaDispatcher: (baseUrl: string, token: string, opts?: DispatcherLoginOptions) => Promise<void>
106
+ /**
107
+ * Save a full-page screenshot to `<dir>/<name>.png`, creating `dir` if needed.
108
+ * Returns the absolute file path. Use a host-backed folder (e.g. the project's
109
+ * `tmp/tests/screenshots`) so the file is visible whether the test runs on the
110
+ * host or inside a dev container.
111
+ */
112
+ saveScreenshot: (dir: string, name: string) => Promise<string>
113
+ /**
114
+ * Answer the cookie-consent dialog if one is up, so the page underneath can be driven.
115
+ *
116
+ * An OwlMeans app asks for consent BEFORE it will start an authentication flow, and the dialog is
117
+ * a modal with no dismissal — by design, since a decision is what the gate is waiting for. For a
118
+ * test that means the login form renders, resolves, reports itself "visible, enabled and stable"
119
+ * and still cannot be clicked, because the overlay intercepts the pointer. Playwright retries for
120
+ * the full timeout and then blames the button, which is the most misleading failure in this
121
+ * helper: nothing is wrong with the form.
122
+ *
123
+ * Accepting is the honest default for a login helper — the flow it is about to drive is exactly
124
+ * what the dialog is gating — but it is best-effort: an app without the widget, or one where the
125
+ * visitor already decided, simply has no dialog and this returns at once.
126
+ *
127
+ * It waits for the consent store to SETTLE (`<html data-consent>`), so a visitor still being
128
+ * located is waited out — the transparent overlay is up then and would take the click — and a
129
+ * visitor decided for automatically (outside the consent countries) returns `false` the moment
130
+ * the decision lands, rather than after the whole `timeout`. Whichever surface asks — the bottom
131
+ * bar or the preferences window — carries `[data-consent-dialog]` and `[data-consent-accept-all]`.
132
+ * Where the runner's own country would decide the outcome, pin it with `mockConsentGeo` first.
133
+ *
134
+ * @returns whether a dialog was actually answered.
135
+ */
136
+ acceptConsent: (opts?: AcceptConsentOptions) => Promise<boolean>
137
+ /**
138
+ * Drive the PK-based supervisor login FORM end-to-end (the faithful path that
139
+ * exercises the real supervisor plugin + registration): navigate to the
140
+ * supervisor login route, fill the user id + private key, submit, and wait for
141
+ * the app to leave the login screen.
142
+ */
143
+ loginViaSupervisorForm: (opts: SupervisorFormLoginOptions) => Promise<void>
144
+ }
package/src/page.ts ADDED
@@ -0,0 +1,194 @@
1
+ import { mkdir } from 'node:fs/promises'
2
+ import { join, resolve } from 'node:path'
3
+ import type { Page } from 'playwright'
4
+ import {
5
+ CONSENT_SETTLED_WITHOUT_UI, DEFAULT_MARKETING_CONSENT_TIMEOUT, DEFAULT_SUPERVISOR_PATH,
6
+ } from './consts.local.js'
7
+ import type {
8
+ AcceptConsentOptions, AnswerMarketingConsentOptions, DispatcherLoginOptions, PageHelper, SupervisorFormLoginOptions,
9
+ } from './page/types.js'
10
+
11
+ export const makePageHelper = (page: Page): PageHelper => {
12
+ const answerMarketingConsent = async (opts?: AnswerMarketingConsentOptions): Promise<boolean> => {
13
+ const timeout = opts?.timeout ?? DEFAULT_MARKETING_CONSENT_TIMEOUT
14
+ const step = page.locator('[data-marketing-consent]')
15
+
16
+ try {
17
+ await page.locator('[data-marketing-consent], #app-prompt, [data-login-method]')
18
+ .first().waitFor({ state: 'visible', timeout })
19
+ } catch {
20
+ return false
21
+ }
22
+
23
+ if (await step.count() === 0) return false
24
+
25
+ // The step's own status read may still be outstanding (`data-state="loading"`) — wait past it,
26
+ // OR notice it already auto-continued (nothing was pending) and detached on its own. An older
27
+ // `web-marketing-consent` that predates `data-state` entirely satisfies the first selector
28
+ // immediately (a missing attribute is never `"loading"`), so this costs nothing there.
29
+ await Promise.race([
30
+ page.waitForSelector('[data-marketing-consent]:not([data-state="loading"])', { timeout }),
31
+ page.waitForSelector('[data-marketing-consent]', { state: 'detached', timeout }),
32
+ ]).catch(() => undefined)
33
+
34
+ // Nothing was pending — it already auto-continued while this waited.
35
+ if (await step.count() === 0) return true
36
+
37
+ const terms = page.locator('[data-marketing-consent-terms]')
38
+ const hasTerms = await terms.count() > 0
39
+
40
+ if (!hasTerms && opts?.accept === 'skip') {
41
+ await page.locator('[data-marketing-consent-skip]').click()
42
+ await step.waitFor({ state: 'detached', timeout })
43
+
44
+ return true
45
+ }
46
+
47
+ if ((opts?.accept ?? 'all') === 'all') {
48
+ // The step draws "Select all" only when there is more than one row to select; a lone consent
49
+ // is ticked itself. Select all speaks for the Terms row too while it is up, which the choice
50
+ // below then settles either way.
51
+ const all = page.locator('[data-marketing-consent-all]')
52
+ if (await all.count() > 0) {
53
+ await all.click()
54
+ } else {
55
+ for (const item of await page.locator('[data-marketing-consent-item]').all()) {
56
+ await item.check()
57
+ }
58
+ }
59
+ }
60
+ // 'none' leaves every item unchecked and clicks nothing else before saving.
61
+
62
+ if (hasTerms) {
63
+ const wanted = (opts?.terms ?? 'accept') === 'accept'
64
+ if (wanted && !(await terms.isChecked())) {
65
+ await terms.check()
66
+ } else if (!wanted && await terms.isChecked()) {
67
+ await terms.uncheck()
68
+ }
69
+ }
70
+
71
+ // `{ force: true }`: the confirm is never the native `disabled` — only `aria-disabled` while a
72
+ // Terms box is unticked, or merely styled muted with nothing changed yet — and Playwright's own
73
+ // actionability check honours `aria-disabled`, which this helper deliberately does not.
74
+ await page.locator('[data-marketing-consent-save]').click({ force: true })
75
+
76
+ const outcome = await Promise.race([
77
+ step.waitFor({ state: 'detached', timeout }).then(() => 'saved' as const),
78
+ page.locator('[data-marketing-consent-error]').waitFor({ state: 'visible', timeout })
79
+ .then(() => 'error' as const),
80
+ page.locator('[data-marketing-consent-terms-error]').waitFor({ state: 'visible', timeout })
81
+ .then(() => 'terms-error' as const),
82
+ ]).catch(() => 'error' as const)
83
+
84
+ if (outcome === 'terms-error') {
85
+ throw new Error('[@owlmeans/test-ui] the marketing-consent step could not confirm the Terms')
86
+ }
87
+
88
+ if (outcome !== 'saved') {
89
+ const skip = page.locator('[data-marketing-consent-skip]')
90
+ if (await skip.count() > 0) {
91
+ console.warn('[@owlmeans/test-ui] marketing consent save did not complete; using the skip link instead')
92
+ await skip.click()
93
+ await step.waitFor({ state: 'detached', timeout }).catch(() => undefined)
94
+ } else if (await terms.count() > 0) {
95
+ // No Skip is ever offered while the Terms box is up — a failed/blocked confirm here has no
96
+ // fallback, and silently returning would hide a caller stuck behind a real requirement.
97
+ throw new Error('[@owlmeans/test-ui] the marketing-consent step is still showing its Terms box')
98
+ }
99
+ }
100
+
101
+ // Answered either way: saved, or skipped past a flaky save. Never leaves the caller blocked.
102
+ return true
103
+ }
104
+
105
+ const loginViaDispatcher = async (
106
+ baseUrl: string, token: string, opts?: DispatcherLoginOptions
107
+ ): Promise<void> => {
108
+ const path = opts?.dispatcherPath ?? '/dispatcher'
109
+ const url = new URL(path, baseUrl)
110
+ url.searchParams.set('token', token)
111
+ // `domcontentloaded`, not playwright's `load` default — see the note on `MountOptions.waitUntil`.
112
+ await page.goto(url.toString(), { waitUntil: opts?.waitUntil ?? 'domcontentloaded' })
113
+ // Wait until the dispatcher has navigated away (token consumed).
114
+ await page.waitForURL(u => !u.pathname.startsWith(path), { timeout: 30_000 })
115
+
116
+ if (opts?.marketingConsent !== 'ignore') {
117
+ await answerMarketingConsent({ accept: 'all', timeout: 30_000 })
118
+ }
119
+ }
120
+
121
+ const saveScreenshot = async (dir: string, name: string): Promise<string> => {
122
+ const target = resolve(dir)
123
+ await mkdir(target, { recursive: true })
124
+ const file = join(target, `${name}.png`)
125
+ await page.screenshot({ path: file, fullPage: true })
126
+ return file
127
+ }
128
+
129
+ const acceptConsent = async (opts?: AcceptConsentOptions): Promise<boolean> => {
130
+ const dialog = page.locator('[data-consent-dialog]')
131
+ // Wait until the consent store has SETTLED: a surface is up, or a decision exists without one
132
+ // (stored earlier, or made automatically outside the consent countries — `<html data-consent>`).
133
+ // Never while the visitor is still being located: the overlay is up then and a click would land
134
+ // on it. An application older than the attribute only ever settles by showing the dialog.
135
+ try {
136
+ await page.locator(`[data-consent-dialog], ${CONSENT_SETTLED_WITHOUT_UI}`)
137
+ .first().waitFor({ state: 'visible', timeout: opts?.timeout ?? 5_000 })
138
+ } catch {
139
+ return false
140
+ }
141
+ if (!await dialog.first().isVisible()) {
142
+ return false
143
+ }
144
+ // Accept-all rather than essential-only: a test asserting a narrower decision should make that
145
+ // decision itself, and silently choosing the minimum here would hide it from the spec.
146
+ await page.locator('[data-consent-accept-all]').click()
147
+ await dialog.waitFor({ state: 'detached', timeout: opts?.timeout ?? 5_000 })
148
+
149
+ return true
150
+ }
151
+
152
+ const loginViaSupervisorForm = async (opts: SupervisorFormLoginOptions): Promise<void> => {
153
+ const path = opts.path ?? DEFAULT_SUPERVISOR_PATH
154
+ const timeout = opts.timeout ?? 60_000
155
+ await page.goto(new URL(path, opts.baseUrl).toString(), {
156
+ waitUntil: opts.waitUntil ?? 'domcontentloaded', timeout
157
+ })
158
+
159
+ // Wait for the app to MOUNT before deciding whether there is a dialog to answer. `domcontentloaded`
160
+ // returns while the SPA is still booting, and on a dev server that boot is occasionally tens of
161
+ // seconds — so a short consent probe reports "no dialog", the dialog then mounts over the form,
162
+ // and the fill below waits out its own timeout on a field that is present but covered. Either
163
+ // marker proves the app is up: the dialog, or the form itself when consent was already given.
164
+ await page.locator('[data-consent-dialog], [data-testid="supervisor-user-id"]')
165
+ .first().waitFor({ state: 'visible', timeout })
166
+
167
+ if (opts.consent !== 'ignore') await acceptConsent({ timeout })
168
+
169
+ // The form renders only AFTER the dialog is dismissed, so these carry the caller's budget rather
170
+ // than playwright's 30s default — the whole point of accepting an explicit `timeout` here.
171
+ await page.getByTestId('supervisor-user-id').fill(opts.userId, { timeout })
172
+ await page.getByTestId('supervisor-pk').fill(opts.pk, { timeout })
173
+
174
+ if (opts.screenshotDir != null) {
175
+ await saveScreenshot(opts.screenshotDir, 'supervisor-login-form')
176
+ }
177
+
178
+ await page.getByTestId('supervisor-submit').click({ timeout })
179
+
180
+ if (opts.expectPath != null) {
181
+ await page.waitForURL(url => url.toString().includes(opts.expectPath!), { timeout })
182
+ } else {
183
+ await page.waitForURL(url => !url.pathname.startsWith(path), { timeout })
184
+ }
185
+
186
+ // Carries the CALLER's own budget rather than the helper's smaller internal default — a slow
187
+ // cold environment (vite re-optimizing, a stage pod still warming) can easily spend most of a
188
+ // short fixed timeout just getting here, leaving too little for the two extra POSTs (terms, then
189
+ // items) a Terms-mode step now makes.
190
+ if (opts.marketingConsent !== 'ignore') await answerMarketingConsent({ accept: 'all', timeout })
191
+ }
192
+
193
+ return { answerMarketingConsent, loginViaDispatcher, saveScreenshot, acceptConsent, loginViaSupervisorForm }
194
+ }
@@ -0,0 +1,55 @@
1
+ import type { AuthRole } from '@owlmeans/auth'
2
+ import type { PageHelper } from '../page/types.js'
3
+
4
+ export interface PregenerateAuthTokenOptions {
5
+ /** Target user id / email the token represents. */
6
+ userId: string
7
+ /**
8
+ * Private key to sign the bearer with, e.g. `ed25519:<base64>` from
9
+ * `.env.dev.secrets`. MUST be the key the target backend trusts as its own
10
+ * signing key (it verifies bearers against `cfg.alias`/`cfg.service`).
11
+ */
12
+ pk: string
13
+ scopes?: string[]
14
+ role?: AuthRole
15
+ entityId?: string
16
+ profileId?: string
17
+ /** `source` recorded in the Auth payload (usually the backend service alias). */
18
+ source?: string
19
+ }
20
+
21
+ export interface SupervisorApiAuthOptions {
22
+ /** Auth-manager API base URL (the backend serving /authentication/* and /authenticate). */
23
+ apiBaseUrl: string
24
+ /** Target user id / email to authenticate (and register on first use). */
25
+ userId: string
26
+ /** Supervisor private key, e.g. `ed25519:<base64>` from `.env.dev.secrets`. */
27
+ pk: string
28
+ /** Paths, overridable for non-default routing. */
29
+ paths?: { init?: string, authenticate?: string, dispatch?: string }
30
+ fetchImpl?: typeof fetch
31
+ }
32
+
33
+ /** Bearers for a backend, minted without a browser. */
34
+ export interface SupervisorAuthHelper {
35
+ /**
36
+ * Mint a ready-to-use `ED25519-BASIC-TOKEN ...` bearer offline, reusing
37
+ * `@owlmeans/test-auth`'s `makeBearer`. This is the "set a token directly"
38
+ * fast-path for e2e/integration tests: no UI, no live auth round-trip. The
39
+ * backend accepts it because it is signed by the project's own trusted key.
40
+ *
41
+ * For a faithful end-to-end login (real supervisor plugin + registration), drive
42
+ * {@link PageHelper.loginViaSupervisorForm} instead.
43
+ */
44
+ pregenerateAuthToken: (opts: PregenerateAuthTokenOptions) => Promise<string>
45
+ /**
46
+ * Pregenerate a real bearer by driving the live PK-based supervisor flow over the
47
+ * backend API (no browser): `/authentication/init` -> sign the challenge with the
48
+ * supervisor key -> `/authentication/authenticate` -> `/authenticate` (dispatcher
49
+ * exchange). This is the faithful "set a token directly via API" path
50
+ * (registers the user on first use), independent of any front-end routing.
51
+ *
52
+ * Returns the final `ED25519-BASIC-TOKEN ...` bearer the backend accepts.
53
+ */
54
+ authenticateViaSupervisorApi: (opts: SupervisorApiAuthOptions) => Promise<string>
55
+ }