@testver/testver 0.2.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.
@@ -0,0 +1,627 @@
1
+ /**
2
+ * Testver mobile cloud-bridge bootstrap (Node `--require` hook).
3
+ *
4
+ * Loaded via `NODE_OPTIONS=--require=<absolute-path>/bootstrap.cjs`
5
+ * BEFORE the user's test code runs. Monkey-patches the `webdriverio`
6
+ * package's `remote()` function to override:
7
+ * - hostname / port / protocol / path → the Appium cloud hub
8
+ * - user / key → provider credentials
9
+ * - capabilities → device + app + provider opts
10
+ *
11
+ * Reads everything from TESTVER_* and APPIUM_HUB_* env vars Testver injects.
12
+ * No-op when those env vars aren't set (so non-Testver invocations
13
+ * keep working exactly as before).
14
+ *
15
+ * Why this exists: mocha-based mobile projects don't load wdio.conf —
16
+ * they `require('webdriverio')` and call `remote({ hostname: 'localhost'
17
+ * })` directly. Without this bootstrap, env-var injection alone can't
18
+ * override those hardcoded values. The bootstrap intercepts at the
19
+ * package boundary so user code stays untouched.
20
+ *
21
+ * Strategy: install a require hook (via Module.prototype.require)
22
+ * that wraps `webdriverio` and `wdio-webdriver` on first import. Works
23
+ * for CommonJS test runners (mocha being the prime target). ESM-only
24
+ * projects fall through harmlessly — they typically already use
25
+ * wdio.conf so the overlay path handles them.
26
+ */
27
+
28
+ 'use strict';
29
+
30
+ // Skip when Testver env vars aren't present — safety net for users
31
+ // who accidentally inherit NODE_OPTIONS in unrelated processes.
32
+ if (!process.env.TESTVER_PROVIDER && !process.env.APPIUM_HUB_HOST) {
33
+ return;
34
+ }
35
+
36
+ const Module = require('module');
37
+ const origRequire = Module.prototype.require;
38
+
39
+ /**
40
+ * Standard W3C WebDriver capabilities — these stay unprefixed.
41
+ * Any other key without a `vendor:` prefix is treated as a legacy
42
+ * Appium cap and gets auto-prefixed with `appium:` below. List from
43
+ * https://w3c.github.io/webdriver/#capabilities (May 2026).
44
+ */
45
+ const W3C_STANDARD_CAPS = new Set([
46
+ 'browserName',
47
+ 'browserVersion',
48
+ 'platformName',
49
+ 'acceptInsecureCerts',
50
+ 'pageLoadStrategy',
51
+ 'proxy',
52
+ 'setWindowRect',
53
+ 'timeouts',
54
+ 'strictFileInteractability',
55
+ 'unhandledPromptBehavior',
56
+ 'webSocketUrl',
57
+ 'fedcm:accounts',
58
+ ]);
59
+
60
+ /**
61
+ * Auto-prefix unprefixed Appium-specific keys with `appium:` so a
62
+ * W3C-compliant server (BrowserStack, Sauce, Appium 2.x) accepts them.
63
+ * Anything that's already `vendor:foo` (contains a colon) is left alone.
64
+ * Standard W3C caps stay unprefixed. Mutates `caps` in place.
65
+ */
66
+ function appiumPrefixCaps(caps) {
67
+ for (const k of Object.keys(caps)) {
68
+ if (k.includes(':')) continue; // already vendor-prefixed
69
+ if (W3C_STANDARD_CAPS.has(k)) continue; // standard W3C cap
70
+ // Legacy Appium key → re-key under `appium:` namespace.
71
+ const v = caps[k];
72
+ delete caps[k];
73
+ caps['appium:' + k] = v;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Normalise a capabilities object to the flat shape webdriverio v8+
79
+ * accepts at the user-facing API. Some test code (esp. ones authored
80
+ * against the raw W3C spec or older WebDriver clients) hands wdio a
81
+ * `{ alwaysMatch: {...}, firstMatch: [...] }` payload, which wdio
82
+ * rejects with:
83
+ * Invalid or unsupported WebDriver capabilities found
84
+ * ("alwaysMatch", "firstMatch").
85
+ * We unwrap alwaysMatch into the flat shape and discard firstMatch
86
+ * (Testver overrides supply everything that matters for cloud runs).
87
+ */
88
+ function flattenCaps(caps) {
89
+ if (!caps || typeof caps !== 'object') return {};
90
+ if (Array.isArray(caps)) return {};
91
+ if ('alwaysMatch' in caps || 'firstMatch' in caps) {
92
+ const flat = Object.assign({}, caps.alwaysMatch || {});
93
+ // Preserve any non-W3C-internal keys the user attached alongside.
94
+ for (const k of Object.keys(caps)) {
95
+ if (k !== 'alwaysMatch' && k !== 'firstMatch') flat[k] = caps[k];
96
+ }
97
+ return flat;
98
+ }
99
+ return caps;
100
+ }
101
+
102
+ /** Apply Testver cloud overrides to a wdio `remote()` options object. */
103
+ function applyTestverOverrides(opts) {
104
+ opts = opts || {};
105
+ // Connection details
106
+ if (process.env.APPIUM_HUB_HOST) opts.hostname = process.env.APPIUM_HUB_HOST;
107
+ if (process.env.APPIUM_HUB_PORT) opts.port = Number(process.env.APPIUM_HUB_PORT);
108
+ if (process.env.APPIUM_HUB_PROTOCOL) opts.protocol = process.env.APPIUM_HUB_PROTOCOL;
109
+ if (process.env.APPIUM_HUB_PATH) opts.path = process.env.APPIUM_HUB_PATH;
110
+ if (process.env.APPIUM_HUB_USER) opts.user = process.env.APPIUM_HUB_USER;
111
+ if (process.env.APPIUM_HUB_KEY) opts.key = process.env.APPIUM_HUB_KEY;
112
+
113
+ // Local-Appium has NO credentials. The user's test code may have set
114
+ // `user`/`key` from a BrowserStack-shaped .env — if we leave them on
115
+ // the options, WebdriverIO's detectBackend() sees user+key present
116
+ // with hostname 127.0.0.1 (not a known cloud) and throws:
117
+ // 'A "user" or "key" was provided but could not be connected to a
118
+ // known cloud service'.
119
+ // Strip them so wdio treats this as a plain local Appium endpoint.
120
+ if (process.env.TESTVER_PROVIDER === 'local-appium') {
121
+ delete opts.user;
122
+ delete opts.key;
123
+ }
124
+
125
+ // Force the flat capabilities shape — strips out any alwaysMatch /
126
+ // firstMatch the user's code might have built manually. wdio v8+
127
+ // builds the W3C envelope internally; passing one in errors.
128
+ const caps = flattenCaps(opts.capabilities);
129
+ opts.capabilities = caps;
130
+
131
+ // Auto-prefix legacy unprefixed Appium keys (deviceName, appPackage,
132
+ // automationName, …) with `appium:` so W3C-compliant servers accept
133
+ // them. Caps that are already vendor-prefixed (`bstack:options`,
134
+ // `appium:foo`) and standard W3C caps (`platformName`) stay as-is.
135
+ appiumPrefixCaps(caps);
136
+
137
+ if (process.env.TESTVER_PLATFORM_NAME) caps.platformName = process.env.TESTVER_PLATFORM_NAME;
138
+ if (process.env.TESTVER_DEVICE_NAME) caps['appium:deviceName'] = process.env.TESTVER_DEVICE_NAME;
139
+ if (process.env.TESTVER_PLATFORM_VERSION) caps['appium:platformVersion'] = process.env.TESTVER_PLATFORM_VERSION;
140
+ if (process.env.TESTVER_APP_URL) {
141
+ caps['appium:app'] = process.env.TESTVER_APP_URL;
142
+ // The user's test code may hard-code app-identifier caps that
143
+ // belong to a DIFFERENT build than what Testver just uploaded
144
+ // (e.g., appPackage / appActivity / bundleId). Cloud providers
145
+ // (BrowserStack, Sauce, LambdaTest) auto-detect these from the
146
+ // uploaded APK/IPA metadata when omitted, so dropping them here
147
+ // makes the run robust against mismatches like:
148
+ // [BROWSERSTACK_INVALID_APP_ACTIVITY] Activity name "..." used
149
+ // to start the app doesn't exist. Supported values: "c".
150
+ delete caps['appium:appPackage'];
151
+ delete caps['appium:appActivity'];
152
+ delete caps['appium:appWaitActivity'];
153
+ delete caps['appium:appWaitPackage'];
154
+ delete caps['appium:bundleId']; // iOS counterpart
155
+ delete caps['appium:appWaitForLaunch'];
156
+ }
157
+
158
+ // Sensible automation name default — required by cloud providers.
159
+ // Only set if the user didn't already pick one (e.g. Espresso, XCUITest).
160
+ if (!caps['appium:automationName']) {
161
+ caps['appium:automationName'] = caps.platformName === 'iOS' ? 'XCUITest' : 'UiAutomator2';
162
+ }
163
+
164
+ // Provider-specific options block.
165
+ //
166
+ // CRITICAL: BrowserStack / Sauce Labs / LambdaTest route to a
167
+ // specific cloud device by reading the device name from THEIR own
168
+ // options block (e.g. `bstack:options.deviceName`), NOT from
169
+ // `appium:deviceName`. The latter is the *Appium server's* internal
170
+ // device label, which on cloud hubs is often the same string but
171
+ // can also be the cloud's internal udid — providers reject device
172
+ // selection when only `appium:deviceName` is set:
173
+ // [BROWSERSTACK_NO_DEVICE_SPECIFIED] The 'device' capability is
174
+ // missing in your test script.
175
+ //
176
+ // So we ALWAYS mirror the device + OS version into the
177
+ // provider-options block. The source of truth is whichever was
178
+ // already populated on caps — either by the user's test code (caps
179
+ // built manually) or by Testver overrides above (caps['appium:*']
180
+ // populated from TESTVER_* env vars). Order of preference:
181
+ // 1. Testver env var (explicit selection by UI / Runner)
182
+ // 2. User-provided `appium:deviceName` from their caps
183
+ // 3. Anything the user already put in `bstack:options.deviceName`
184
+ const provider = process.env.TESTVER_PROVIDER;
185
+ const deviceFromEnv = process.env.TESTVER_DEVICE_NAME;
186
+ const osVerFromEnv = process.env.TESTVER_PLATFORM_VERSION;
187
+ const deviceFromUser = caps['appium:deviceName'];
188
+ const osVerFromUser = caps['appium:platformVersion'];
189
+ const providerOpts = {
190
+ projectName: 'Testver',
191
+ buildName: process.env.TESTVER_BUILD_NAME || 'testver-cloud-run',
192
+ sessionName: process.env.TESTVER_SESSION_NAME || 'mobile-test',
193
+ };
194
+ const resolvedDevice = deviceFromEnv || deviceFromUser;
195
+ const resolvedOsVer = osVerFromEnv || osVerFromUser;
196
+
197
+ if (provider === 'browserstack') {
198
+ const existing = caps['bstack:options'] || {};
199
+ caps['bstack:options'] = Object.assign({}, existing, providerOpts);
200
+ // BrowserStack uses `deviceName` + `osVersion` keys.
201
+ if (resolvedDevice && !existing.deviceName) caps['bstack:options'].deviceName = resolvedDevice;
202
+ if (resolvedOsVer && !existing.osVersion) caps['bstack:options'].osVersion = resolvedOsVer;
203
+ } else if (provider === 'saucelabs') {
204
+ const existing = caps['sauce:options'] || {};
205
+ caps['sauce:options'] = Object.assign({}, existing, providerOpts);
206
+ // Sauce Labs uses `deviceName` (or `appium:deviceName` at top level — both honoured).
207
+ if (resolvedDevice && !existing.deviceName) caps['sauce:options'].deviceName = resolvedDevice;
208
+ if (resolvedOsVer && !existing.platformVersion) caps['sauce:options'].platformVersion = resolvedOsVer;
209
+ } else if (provider === 'lambdatest') {
210
+ const existing = caps['LT:Options'] || {};
211
+ caps['LT:Options'] = Object.assign({}, existing, providerOpts);
212
+ // LambdaTest uses `deviceName` + `platformVersion`.
213
+ if (resolvedDevice && !existing.deviceName) caps['LT:Options'].deviceName = resolvedDevice;
214
+ if (resolvedOsVer && !existing.platformVersion) caps['LT:Options'].platformVersion = resolvedOsVer;
215
+ }
216
+ return opts;
217
+ }
218
+
219
+ /**
220
+ * Wrap the `remote` export on a webdriverio module. Idempotent.
221
+ *
222
+ * Two behaviours, selected at call time by env state:
223
+ * - TESTVER_REUSE_SESSION_ID present → call wdio.attach() to ATTACH
224
+ * to the existing AI Assistant / AI Record live session. Saves the
225
+ * 30-60s device-boot cost + one cloud minute per claim.
226
+ * - Otherwise → call the original wdio.remote() with cloud-redirected
227
+ * connection + Testver-normalized capabilities (fresh session).
228
+ */
229
+ /**
230
+ * When the test code is running on a SHARED reused session, the
231
+ * test's teardown call to `driver.quit()` / `driver.deleteSession()`
232
+ * would terminate the entire BrowserStack session — killing the
233
+ * live session AI Assistant is still using. We can't have that.
234
+ *
235
+ * Wrap the attached browser so those teardown methods become no-ops
236
+ * (but still return a resolved promise so existing `await driver.quit()`
237
+ * code keeps working). Other operations on the browser remain
238
+ * untouched. Idempotent — only wraps once per browser instance.
239
+ *
240
+ * For non-reuse runs (fresh `remote()`), this wrapper is NOT applied:
241
+ * `quit()` works normally and cleanly tears down the freshly-created
242
+ * cloud session as the test author expects.
243
+ */
244
+ /**
245
+ * Reset the app to a fresh launch state on an attached session.
246
+ *
247
+ * When AI Assistant has been driving the device, the app is sitting on
248
+ * whatever screen the user navigated to. A test attached to this
249
+ * session expects a clean launch (welcome screen, login screen, etc.).
250
+ * Without resetting, every test fails on its first assertion because
251
+ * the screen it expects to see isn't there.
252
+ *
253
+ * Strategy:
254
+ * 1. terminateApp(appId) → kills the running app process
255
+ * 2. activateApp(appId) → relaunches it (same as a cold-launch from
256
+ * the user's perspective)
257
+ *
258
+ * The cloud SESSION stays alive across both calls — only the app
259
+ * process is recycled. ~1-2 seconds total. Cheaper than booting a
260
+ * fresh device (30-60s).
261
+ *
262
+ * App identifier sources, in order:
263
+ * - caps['appium:appPackage'] (Android, set by user test code)
264
+ * - caps['appium:bundleId'] (iOS, set by user test code)
265
+ * - TESTVER_APP_PACKAGE env var (override hook for future use)
266
+ * - TESTVER_APP_BUNDLE_ID env var
267
+ *
268
+ * Disable: set TESTVER_SKIP_APP_RESET=1 in the run env.
269
+ */
270
+ async function resetAppOnAttach(browser, caps) {
271
+ // Idempotency guard — if the browser already went through a reset
272
+ // (e.g. wdio.remote() delegated to wdio.attach() which is also
273
+ // wrapped), don't reset twice.
274
+ if (browser.__testverResetDone) return;
275
+ try { Object.defineProperty(browser, '__testverResetDone', { value: true, enumerable: false }); }
276
+ catch (_) { browser.__testverResetDone = true; }
277
+
278
+ if (process.env.TESTVER_SKIP_APP_RESET === '1') {
279
+ // eslint-disable-next-line no-console
280
+ console.log('[testver-bootstrap] App reset skipped (TESTVER_SKIP_APP_RESET=1)');
281
+ return;
282
+ }
283
+ const appId = (caps && (caps['appium:appPackage'] || caps['appium:bundleId']))
284
+ || process.env.TESTVER_APP_PACKAGE
285
+ || process.env.TESTVER_APP_BUNDLE_ID;
286
+ if (!appId) {
287
+ // eslint-disable-next-line no-console
288
+ console.log('[testver-bootstrap] App reset on attach: no appPackage/bundleId in caps — skipping ' +
289
+ '(test may see stale UI state from prior AI Assistant interactions). ' +
290
+ 'Set caps.appPackage (Android) or caps.bundleId (iOS) in your test code, ' +
291
+ 'or export TESTVER_APP_PACKAGE / TESTVER_APP_BUNDLE_ID to enable auto-reset.');
292
+ return;
293
+ }
294
+
295
+ // Platform detection — drives whether we issue `mobile: clearApp`
296
+ // (Android only — wipes SharedPreferences + cache + databases so
297
+ // the app launches as if freshly installed, including onboarding
298
+ // screens). iOS doesn't have a direct equivalent at the WebDriver
299
+ // protocol level; terminate + activate is the best we can do.
300
+ const platform = String((caps && caps.platformName) || process.env.TESTVER_PLATFORM_NAME || '').toLowerCase();
301
+ const isAndroid = platform === 'android';
302
+ const skipClear = process.env.TESTVER_SKIP_APP_CLEAR === '1';
303
+
304
+ // eslint-disable-next-line no-console
305
+ console.log('[testver-bootstrap] Resetting app "' + appId + '" on attached session ' +
306
+ '(' + (isAndroid && !skipClear ? 'clearApp + ' : '') + 'terminate + activate) ' +
307
+ 'so test starts from a fresh launch...');
308
+ try {
309
+ // Step 1 (Android only): clear app DATA so onboarding state, login
310
+ // state, cached pages, etc. all reset. Without this, terminate +
311
+ // activate just kills + restarts the process — the user's previous
312
+ // "completed onboarding" flag persists and the welcome screen
313
+ // never appears. Skippable via TESTVER_SKIP_APP_CLEAR=1 when the
314
+ // test expects to inherit state from prior interactions.
315
+ if (isAndroid && !skipClear) {
316
+ try {
317
+ await browser.execute('mobile: clearApp', { appId });
318
+ // eslint-disable-next-line no-console
319
+ console.log('[testver-bootstrap] App data cleared (onboarding + cached state reset).');
320
+ } catch (err) {
321
+ // Some Appium-server / cloud-driver configs don't expose
322
+ // clearApp — fall back to terminate + activate alone. Most
323
+ // tests still work; the onboarding flag is the edge case.
324
+ // eslint-disable-next-line no-console
325
+ console.log('[testver-bootstrap] clearApp not available: ' + (err && err.message) +
326
+ ' — proceeding with terminate+activate (onboarding state may persist).');
327
+ }
328
+ }
329
+ // Step 2: terminate (if running). Failure is fine — activate
330
+ // launches anyway.
331
+ const terminate = async () => {
332
+ if (typeof browser.terminateApp === 'function') return browser.terminateApp(appId);
333
+ return browser.execute('mobile: terminateApp', { appId });
334
+ };
335
+ try {
336
+ await terminate();
337
+ } catch (err) {
338
+ // eslint-disable-next-line no-console
339
+ console.log('[testver-bootstrap] terminateApp non-fatal: ' + (err && err.message));
340
+ }
341
+ // Step 3: cold-launch the app.
342
+ const activate = async () => {
343
+ if (typeof browser.activateApp === 'function') return browser.activateApp(appId);
344
+ return browser.execute('mobile: activateApp', { appId });
345
+ };
346
+ await activate();
347
+ // eslint-disable-next-line no-console
348
+ console.log('[testver-bootstrap] App reset complete — test starts from fresh launch state');
349
+ } catch (err) {
350
+ // eslint-disable-next-line no-console
351
+ console.log('[testver-bootstrap] App reset failed: ' + (err && err.message) +
352
+ ' — continuing anyway. If the test fails on the first assertion, set TESTVER_SKIP_APP_RESET=1 ' +
353
+ 'and reset the app manually in your test setup.');
354
+ }
355
+ }
356
+
357
+ function suppressSessionTeardown(browser) {
358
+ if (!browser || browser.__testverTeardownSuppressed) return browser;
359
+ const noopMethodNames = ['deleteSession', 'quit', 'endSession', 'end'];
360
+ const noopFor = (name) => function suppressedQuit() {
361
+ // eslint-disable-next-line no-console
362
+ console.log('[testver-bootstrap] ' + name + '() suppressed — session is SHARED with AI Assistant ' +
363
+ '(use driver.terminateApp()/activateApp() to reset state instead).');
364
+ return Promise.resolve();
365
+ };
366
+
367
+ // Strategy A: Object.defineProperty (works when the property is
368
+ // non-writable but still configurable — wdio v8.27+ marks
369
+ // deleteSession non-writable via getters but leaves it configurable).
370
+ let allOverridden = true;
371
+ for (const m of noopMethodNames) {
372
+ try {
373
+ Object.defineProperty(browser, m, {
374
+ value: noopFor(m),
375
+ writable: true,
376
+ configurable: true,
377
+ enumerable: false,
378
+ });
379
+ } catch (err) {
380
+ allOverridden = false;
381
+ // eslint-disable-next-line no-console
382
+ console.warn('[testver-bootstrap] defineProperty(' + m + ') failed: ' + (err && err.message));
383
+ }
384
+ }
385
+
386
+ if (allOverridden) {
387
+ try { Object.defineProperty(browser, '__testverTeardownSuppressed', { value: true, enumerable: false }); }
388
+ catch (_) { /* swallow — flag is best-effort */ }
389
+ return browser;
390
+ }
391
+
392
+ // Strategy B (fallback): wrap in a Proxy that intercepts the four
393
+ // teardown methods. We bind every OTHER method to the original
394
+ // target so wdio internals that rely on `this` keep working.
395
+ // Proxy never breaks for read-only props — gets always return the
396
+ // value we choose.
397
+ const noopSet = new Set(noopMethodNames);
398
+ const proxied = new Proxy(browser, {
399
+ get(target, prop, receiver) {
400
+ if (typeof prop === 'string' && noopSet.has(prop)) {
401
+ return noopFor(prop);
402
+ }
403
+ const v = Reflect.get(target, prop, receiver);
404
+ // Methods need their `this` rebound to the real browser so
405
+ // wdio's command pipeline (which inspects `this.options`,
406
+ // `this.capabilities`, etc.) still sees a valid context.
407
+ return typeof v === 'function' ? v.bind(target) : v;
408
+ },
409
+ set(target, prop, value) {
410
+ return Reflect.set(target, prop, value);
411
+ },
412
+ });
413
+ try { Object.defineProperty(proxied, '__testverTeardownSuppressed', { value: true, enumerable: false }); }
414
+ catch (_) { /* swallow */ }
415
+ return proxied;
416
+ }
417
+
418
+ /**
419
+ * POST the cloud sessionId back to Testver so the Runner's live-preview
420
+ * panel can render screenshots from this very session. Fire-and-forget;
421
+ * a failure here just means the live panel stays empty — the test still
422
+ * runs unaffected. We pass the FULL hub URL (with credentials) so the
423
+ * server can authenticate direct screenshot calls without needing to
424
+ * re-resolve creds from disk.
425
+ */
426
+ function reportExternalSession(browser, patched) {
427
+ const reportUrl = process.env.TESTVER_REPORTBACK_URL;
428
+ const clientId = process.env.TESTVER_CLIENT_ID;
429
+ if (!reportUrl || !clientId || !browser || !browser.sessionId) return;
430
+
431
+ // Reconstruct the hub URL with embedded credentials — Testver's
432
+ // register endpoint parses this with new URL(...) to extract host/
433
+ // port/path/user/key without separate fields.
434
+ const proto = patched.protocol || 'https';
435
+ const host = patched.hostname;
436
+ const port = patched.port || (proto === 'https' ? 443 : 80);
437
+ const path = patched.path || '/wd/hub';
438
+ const user = encodeURIComponent(patched.user || '');
439
+ const key = encodeURIComponent(patched.key || '');
440
+ const hubUrl = `${proto}://${user}:${key}@${host}:${port}${path}`;
441
+ const body = JSON.stringify({
442
+ clientId,
443
+ sessionId: browser.sessionId,
444
+ hubUrl,
445
+ deviceName: patched.capabilities && patched.capabilities['appium:deviceName'],
446
+ platformName: patched.capabilities && patched.capabilities.platformName,
447
+ providerId: process.env.TESTVER_PROVIDER,
448
+ });
449
+ const endpoint = reportUrl.replace(/\/$/, '') + '/api/mobile/session/register-external';
450
+ // Node 18+ has global fetch — we target Node 20 in the parent app.
451
+ if (typeof fetch !== 'function') {
452
+ // eslint-disable-next-line no-console
453
+ console.log('[testver-bootstrap] No global fetch available — live-preview reportback skipped.');
454
+ return;
455
+ }
456
+ fetch(endpoint, {
457
+ method: 'POST',
458
+ headers: { 'Content-Type': 'application/json' },
459
+ body,
460
+ }).then(() => {
461
+ // eslint-disable-next-line no-console
462
+ console.log('[testver-bootstrap] Reported sessionId ' + browser.sessionId.slice(0, 12) + '… to Testver for live preview');
463
+ }).catch((err) => {
464
+ // eslint-disable-next-line no-console
465
+ console.log('[testver-bootstrap] Reportback failed (live preview may be empty): ' + (err && err.message));
466
+ });
467
+ }
468
+
469
+ /**
470
+ * Tell Testver this external session is over so it stops trying to
471
+ * poll its screenshots. Fire-and-forget; the registry has a TTL
472
+ * fallback if this call drops.
473
+ */
474
+ function unreportExternalSession() {
475
+ const reportUrl = process.env.TESTVER_REPORTBACK_URL;
476
+ const clientId = process.env.TESTVER_CLIENT_ID;
477
+ if (!reportUrl || !clientId || typeof fetch !== 'function') return;
478
+ const endpoint = reportUrl.replace(/\/$/, '') + '/api/mobile/session/unregister-external';
479
+ fetch(endpoint, {
480
+ method: 'POST',
481
+ headers: { 'Content-Type': 'application/json' },
482
+ body: JSON.stringify({ clientId }),
483
+ }).catch(() => { /* best-effort */ });
484
+ }
485
+
486
+ // Wire up process exit hooks so the registry doesn't keep a stale
487
+ // entry after the test process dies. The TTL on the server side
488
+ // catches anything we miss here.
489
+ process.on('exit', unreportExternalSession);
490
+ process.on('SIGINT', () => { unreportExternalSession(); process.exit(130); });
491
+ process.on('SIGTERM', () => { unreportExternalSession(); process.exit(143); });
492
+
493
+ function wrapWdioModule(mod) {
494
+ if (!mod || mod.__testverWrapped) return mod;
495
+
496
+ // Capture the ORIGINAL attach() reference BEFORE wrapping — we use
497
+ // this directly inside the remote() wrapper so we don't accidentally
498
+ // double-invoke our own attach wrapper (which would suppress +
499
+ // reset twice). After we install our wrapped attach below, all
500
+ // EXTERNAL callers (user test code calling wdio.attach() directly)
501
+ // hit the wrapped version; the remote() wrapper bypasses it.
502
+ const origAttach = typeof mod.attach === 'function' ? mod.attach : null;
503
+ const origRemote = typeof mod.remote === 'function' ? mod.remote : null;
504
+
505
+ if (origRemote) {
506
+ mod.remote = async function testverWrappedRemote(opts) {
507
+ const reuseId = process.env.TESTVER_REUSE_SESSION_ID;
508
+ // Always normalise/apply overrides — even attach() needs the
509
+ // hub host/port/user/key + flattened caps so wdio knows where
510
+ // to send subsequent commands.
511
+ const patched = applyTestverOverrides(opts);
512
+
513
+ if (reuseId && origAttach) {
514
+ // eslint-disable-next-line no-console
515
+ console.log('[testver-bootstrap] Attaching to live session ' + reuseId.slice(0, 12) + '… on ' +
516
+ (patched.hostname || '?') + ' (skips device boot)');
517
+ // webdriverio's attach() reads its connection details from
518
+ // `attachOptions.options` via detectBackend(), NOT from the
519
+ // top-level object. detectBackend(undefined) returns
520
+ // { hostname: undefined, port: undefined, … } which then
521
+ // OVERRIDES any flat top-level values we pass — producing the
522
+ // malformed `http://127.0.0.1:undefined/…` URL. So we MUST nest
523
+ // the connection params under `options` (and mirror them at the
524
+ // top level for older wdio versions that read both).
525
+ const connOpts = {
526
+ hostname: patched.hostname,
527
+ port: patched.port,
528
+ protocol: patched.protocol,
529
+ path: patched.path,
530
+ capabilities: patched.capabilities,
531
+ };
532
+ const attachOpts = Object.assign({}, patched, {
533
+ sessionId: reuseId,
534
+ capabilities: patched.capabilities,
535
+ requestedCapabilities: patched.capabilities,
536
+ options: connOpts,
537
+ });
538
+ // Use the ORIGINAL attach (not mod.attach) so we don't double
539
+ // through the wrapped version below.
540
+ const browser = await origAttach.call(this, attachOpts);
541
+ const suppressed = suppressSessionTeardown(browser);
542
+ await resetAppOnAttach(suppressed, patched.capabilities || {});
543
+ return suppressed;
544
+ }
545
+
546
+ // eslint-disable-next-line no-console
547
+ console.log('[testver-bootstrap] Redirecting wdio.remote() → ' +
548
+ (patched.protocol || 'https') + '://' + (patched.hostname || '?') + ':' + (patched.port || '?') +
549
+ (patched.path || '/wd/hub') +
550
+ ' device=' + (patched.capabilities && patched.capabilities['appium:deviceName']));
551
+ // Fresh sessions: pass through unchanged. Test's quit() correctly
552
+ // tears down the cloud session it created.
553
+ const browser = await origRemote.call(this, patched);
554
+ // Report this session id back to Testver so the Runner UI can
555
+ // render its live preview. Fire-and-forget — best-effort,
556
+ // doesn't block test execution.
557
+ try { reportExternalSession(browser, patched); } catch (_) { /* swallow */ }
558
+ return browser;
559
+ };
560
+ }
561
+
562
+ // Patch attach() for user code that calls it directly (uncommon — most
563
+ // call remote()). When the env var indicates Testver reuse, apply
564
+ // suppress + reset. Otherwise pass through.
565
+ if (origAttach) {
566
+ mod.attach = async function testverWrappedAttach(opts) {
567
+ // Apply the SAME normalisation the remote() wrapper does — strip
568
+ // user/key for local, nest connection params under `options` so
569
+ // webdriverio's detectBackend() reads host/port/path correctly.
570
+ // Without this, a direct wdio.attach() call hits the identical
571
+ // "port: undefined" / "unknown cloud service" bugs.
572
+ const patched = applyTestverOverrides(opts);
573
+ const connOpts = {
574
+ hostname: patched.hostname,
575
+ port: patched.port,
576
+ protocol: patched.protocol,
577
+ path: patched.path,
578
+ capabilities: patched.capabilities,
579
+ };
580
+ const attachOpts = Object.assign({}, patched, {
581
+ capabilities: patched.capabilities,
582
+ requestedCapabilities: patched.capabilities,
583
+ options: connOpts,
584
+ });
585
+ const browser = await origAttach.call(this, attachOpts);
586
+ if (process.env.TESTVER_REUSE_SESSION_ID) {
587
+ const suppressed = suppressSessionTeardown(browser);
588
+ await resetAppOnAttach(suppressed, patched.capabilities || {});
589
+ return suppressed;
590
+ }
591
+ return browser;
592
+ };
593
+ }
594
+ // Default export sometimes differs (e.g. ESM bundlers).
595
+ if (mod.default && typeof mod.default.remote === 'function' && mod.default !== mod) {
596
+ wrapWdioModule(mod.default);
597
+ }
598
+ try { Object.defineProperty(mod, '__testverWrapped', { value: true, enumerable: false }); }
599
+ catch (_) { mod.__testverWrapped = true; }
600
+ return mod;
601
+ }
602
+
603
+ // Install require hook — fires every time the user (or any dep) does
604
+ // `require('webdriverio')` etc. We patch the export on first load
605
+ // and re-return the same instance afterwards (Node's require cache
606
+ // gives us identity for free).
607
+ Module.prototype.require = function patchedRequire(id) {
608
+ const exp = origRequire.apply(this, arguments);
609
+ if (id === 'webdriverio' || id === 'wdio-webdriver') {
610
+ return wrapWdioModule(exp);
611
+ }
612
+ return exp;
613
+ };
614
+
615
+ // Also patch any webdriverio module already loaded BEFORE this
616
+ // bootstrap (rare, but possible if --require ordering is off).
617
+ try {
618
+ for (const cached of Object.keys(require.cache)) {
619
+ if (/[/\\]webdriverio[/\\]/.test(cached) && /index\.[cm]?js$/.test(cached)) {
620
+ wrapWdioModule(require.cache[cached].exports);
621
+ }
622
+ }
623
+ } catch (_) { /* swallow — best-effort */ }
624
+
625
+ // eslint-disable-next-line no-console
626
+ console.log('[testver-bootstrap] wdio cloud-bridge bootstrap active (' +
627
+ (process.env.TESTVER_PROVIDER || 'no provider') + ')');