@qontinui/ui-bridge-wrapper 0.2.0 → 0.4.1

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,1136 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var url = require('url');
5
+ var module$1 = require('module');
6
+ var fs = require('fs');
7
+
8
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
+ // src/types.ts
10
+ var WrapperTransportError = class extends Error {
11
+ code;
12
+ retryable;
13
+ cause;
14
+ constructor(code, message, options = {}) {
15
+ super(message);
16
+ this.name = "WrapperTransportError";
17
+ this.code = code;
18
+ this.retryable = options.retryable ?? false;
19
+ if (options.cause !== void 0) {
20
+ this.cause = options.cause;
21
+ }
22
+ }
23
+ };
24
+
25
+ // src/handler-registry.ts
26
+ var HandlerRegistry = class {
27
+ handlers = /* @__PURE__ */ new Map();
28
+ /**
29
+ * Register (or replace) a handler for `actionId`. Replacement is explicit
30
+ * rather than throwing because live reloading / hot module scenarios need
31
+ * to update handlers without tearing the whole transport down.
32
+ */
33
+ register(actionId, fn) {
34
+ this.handlers.set(actionId, fn);
35
+ }
36
+ /** Remove a handler. Returns `true` if a handler was removed. */
37
+ unregister(actionId) {
38
+ return this.handlers.delete(actionId);
39
+ }
40
+ /** All registered action ids. Stable iteration order (insertion order). */
41
+ list() {
42
+ return Array.from(this.handlers.keys());
43
+ }
44
+ /** Check whether a handler is registered for `actionId`. */
45
+ has(actionId) {
46
+ return this.handlers.has(actionId);
47
+ }
48
+ /**
49
+ * Invoke the handler registered under `actionId`.
50
+ *
51
+ * Throws `WrapperTransportError("NO_HANDLER")` if no handler is registered.
52
+ * Propagates handler errors wrapped as `WrapperTransportError("HANDLER_ERROR")`
53
+ * so callers can uniformly check `err.code`.
54
+ */
55
+ async dispatch(actionId, params, ctx) {
56
+ const handler = this.handlers.get(actionId);
57
+ if (!handler) {
58
+ throw new WrapperTransportError(
59
+ "NO_HANDLER",
60
+ `No handler registered for action '${actionId}'`
61
+ );
62
+ }
63
+ try {
64
+ const result = await handler(params, ctx);
65
+ return result;
66
+ } catch (err) {
67
+ if (err instanceof WrapperTransportError) throw err;
68
+ const message = err instanceof Error ? err.message : String(err);
69
+ throw new WrapperTransportError("HANDLER_ERROR", message, { cause: err });
70
+ }
71
+ }
72
+ };
73
+
74
+ // src/base-transport.ts
75
+ var BaseTransport = class {
76
+ _status = "idle";
77
+ listeners = /* @__PURE__ */ new Set();
78
+ registry;
79
+ readyPromise = null;
80
+ constructor(registry) {
81
+ this.registry = registry ?? new HandlerRegistry();
82
+ }
83
+ get status() {
84
+ return this._status;
85
+ }
86
+ /** Expose the underlying registry so wrappers can register handlers. */
87
+ get handlerRegistry() {
88
+ return this.registry;
89
+ }
90
+ /** Convenience: register a handler on the transport's registry. */
91
+ register(actionId, fn) {
92
+ this.registry.register(actionId, fn);
93
+ }
94
+ /**
95
+ * Idempotent async setup. First call runs `onReady()`; subsequent calls
96
+ * share the same promise until it settles, after which further calls
97
+ * are no-ops if `status === 'ready'`, or re-run setup if it errored.
98
+ */
99
+ async ready() {
100
+ if (this._status === "ready") return;
101
+ if (this._status === "closed") {
102
+ throw new WrapperTransportError("TRANSPORT_CLOSED", `Transport '${this.kind}' is closed`);
103
+ }
104
+ if (this.readyPromise) return this.readyPromise;
105
+ this.setStatus("connecting");
106
+ this.readyPromise = this.onReady().then(() => {
107
+ this.setStatus("ready");
108
+ }).catch((err) => {
109
+ this.setStatus("error");
110
+ this.readyPromise = null;
111
+ throw err;
112
+ });
113
+ return this.readyPromise;
114
+ }
115
+ /** Default dispatch — waits for ready, builds ctx, delegates to registry. */
116
+ async dispatch(actionId, params) {
117
+ await this.ready();
118
+ const ctx = await this.buildContext(actionId, params);
119
+ return this.registry.dispatch(actionId, params, ctx);
120
+ }
121
+ async close() {
122
+ if (this._status === "closed") return;
123
+ try {
124
+ await this.onClose();
125
+ } finally {
126
+ this.setStatus("closed");
127
+ this.listeners.clear();
128
+ this.readyPromise = null;
129
+ }
130
+ }
131
+ onStatusChange(listener) {
132
+ this.listeners.add(listener);
133
+ return () => {
134
+ this.listeners.delete(listener);
135
+ };
136
+ }
137
+ /** Update status and notify listeners. Safe to call from subclasses. */
138
+ setStatus(next) {
139
+ if (this._status === next) return;
140
+ this._status = next;
141
+ for (const l of this.listeners) {
142
+ try {
143
+ l(next);
144
+ } catch {
145
+ }
146
+ }
147
+ }
148
+ /**
149
+ * Subclass hook: build the context object passed to handlers. Default is
150
+ * `undefined` (api transport). Headless/headed override to provide the
151
+ * Playwright `page`; live overrides to provide a response helper.
152
+ */
153
+ async buildContext(_actionId, _params) {
154
+ return void 0;
155
+ }
156
+ };
157
+
158
+ // src/transports/api.ts
159
+ var ApiTransport = class extends BaseTransport {
160
+ kind = "api";
161
+ fallback;
162
+ constructor(config = { kind: "api" }, registry) {
163
+ super(registry);
164
+ const handler = config.options?.handler;
165
+ if (typeof handler === "function") {
166
+ this.fallback = handler;
167
+ }
168
+ }
169
+ async onReady() {
170
+ }
171
+ async onClose() {
172
+ }
173
+ async buildContext() {
174
+ return { kind: "api" };
175
+ }
176
+ /**
177
+ * Override dispatch to fall back to `options.handler` when no explicit
178
+ * registration exists for `actionId`.
179
+ */
180
+ async dispatch(actionId, params) {
181
+ await this.ready();
182
+ if (this.registry.has(actionId)) {
183
+ const ctx = await this.buildContext();
184
+ return this.registry.dispatch(actionId, params, ctx);
185
+ }
186
+ if (this.fallback) {
187
+ try {
188
+ return await this.fallback(actionId, params);
189
+ } catch (err) {
190
+ if (err instanceof WrapperTransportError) throw err;
191
+ const message = err instanceof Error ? err.message : String(err);
192
+ throw new WrapperTransportError("HANDLER_ERROR", message, { cause: err });
193
+ }
194
+ }
195
+ throw new WrapperTransportError("NO_HANDLER", `No handler registered for action '${actionId}'`);
196
+ }
197
+ };
198
+
199
+ // src/transports/headless.ts
200
+ var HeadlessTransport = class extends BaseTransport {
201
+ kind;
202
+ options;
203
+ headless;
204
+ tab = null;
205
+ constructor(config, registry, overrides = {}) {
206
+ super(registry);
207
+ this.kind = overrides.kind ?? "headless";
208
+ this.headless = overrides.headless ?? true;
209
+ this.options = this.parseOptions(config);
210
+ }
211
+ parseOptions(config) {
212
+ const raw = config.options ?? {};
213
+ const targetUrl = raw["targetUrl"];
214
+ if (typeof targetUrl !== "string" || targetUrl.length === 0) {
215
+ throw new WrapperTransportError(
216
+ "INVALID_CONFIG",
217
+ `Transport kind '${this.kind}' requires options.targetUrl (string)`
218
+ );
219
+ }
220
+ return {
221
+ targetUrl,
222
+ viewportWidth: typeof raw["viewportWidth"] === "number" ? raw["viewportWidth"] : void 0,
223
+ viewportHeight: typeof raw["viewportHeight"] === "number" ? raw["viewportHeight"] : void 0,
224
+ uiBridgeBase: typeof raw["uiBridgeBase"] === "string" ? raw["uiBridgeBase"] : void 0,
225
+ waitForUiBridgeMs: typeof raw["waitForUiBridgeMs"] === "number" ? raw["waitForUiBridgeMs"] : void 0,
226
+ userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
227
+ forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0
228
+ };
229
+ }
230
+ async onReady() {
231
+ let launchHeadlessTab;
232
+ try {
233
+ ({ launchHeadlessTab } = await import('@qontinui/ui-bridge-headless'));
234
+ } catch (err) {
235
+ const cause = err instanceof Error ? err.message : String(err);
236
+ throw new WrapperTransportError(
237
+ "INVALID_CONFIG",
238
+ `Transport kind '${this.kind}' needs the optional '@qontinui/ui-bridge-headless' peer, which is not installed. Install it and the Chromium browser:
239
+ npm i @qontinui/ui-bridge-headless && npx playwright install chromium
240
+ (bare \`npx @qontinui/ui-bridge-wrapper \u2026\` does NOT install peers \u2014 pass each peer with \`-p\`, e.g.
241
+ npx -y -p @qontinui/ui-bridge-wrapper -p @qontinui/ui-bridge -p @qontinui/ui-bridge-headless -p playwright ui-bridge-login-web \u2026)
242
+ Underlying import error: ${cause}`
243
+ );
244
+ }
245
+ const initScripts = await this.buildInitScripts();
246
+ const tab = await launchHeadlessTab({
247
+ url: this.options.targetUrl,
248
+ headless: this.headless,
249
+ uiBridgeBase: this.options.uiBridgeBase,
250
+ waitForUiBridgeMs: this.options.waitForUiBridgeMs,
251
+ viewportWidth: this.options.viewportWidth,
252
+ viewportHeight: this.options.viewportHeight,
253
+ userAgent: this.options.userAgent,
254
+ forwardConsole: this.options.forwardConsole,
255
+ initScripts: initScripts.length > 0 ? initScripts : void 0
256
+ });
257
+ this.tab = {
258
+ browser: tab.browser,
259
+ context: tab.context,
260
+ page: tab.page,
261
+ uiBridgeRegistered: tab.uiBridgeRegistered,
262
+ tabId: tab.tabId,
263
+ close: tab.close
264
+ };
265
+ await this.afterLaunch(tab.page);
266
+ }
267
+ /**
268
+ * Subclass hook: init-scripts to register on the browser context before the
269
+ * first navigation (via `context.addInitScript`). Default: none. Injected
270
+ * mode overrides this to inject the config + runtime bundle pre-paint.
271
+ */
272
+ async buildInitScripts() {
273
+ return [];
274
+ }
275
+ /**
276
+ * Subclass hook: run after launch + navigation, before `ready()` resolves.
277
+ * Default: no-op. Injected mode overrides it to await the in-page runtime.
278
+ */
279
+ async afterLaunch(_page) {
280
+ }
281
+ async onClose() {
282
+ if (!this.tab) return;
283
+ const t = this.tab;
284
+ this.tab = null;
285
+ await t.close();
286
+ }
287
+ async buildContext() {
288
+ if (!this.tab) {
289
+ throw new WrapperTransportError(
290
+ "NOT_READY",
291
+ `Transport '${this.kind}' is not ready; call ready() before dispatch`
292
+ );
293
+ }
294
+ return {
295
+ kind: this.kind,
296
+ page: this.tab.page,
297
+ browserContext: this.tab.context,
298
+ browser: this.tab.browser,
299
+ uiBridgeRegistered: this.tab.uiBridgeRegistered,
300
+ tabId: this.tab.tabId
301
+ };
302
+ }
303
+ };
304
+
305
+ // src/transports/headed.ts
306
+ var HeadedTransport = class extends HeadlessTransport {
307
+ constructor(config, registry) {
308
+ super(config, registry, { kind: "headed", headless: false });
309
+ }
310
+ };
311
+ var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('login-web-cli.cjs', document.baseURI).href)));
312
+ var cachedBundle = null;
313
+ function loadInjectedBundle() {
314
+ if (cachedBundle !== null) return cachedBundle;
315
+ let bundlePath;
316
+ try {
317
+ bundlePath = require2.resolve("@qontinui/ui-bridge/injected/bundle.global.js");
318
+ } catch {
319
+ const pkgJson = require2.resolve("@qontinui/ui-bridge/package.json");
320
+ bundlePath = pkgJson.replace(/package\.json$/, "dist/injected/bundle.global.js");
321
+ }
322
+ try {
323
+ cachedBundle = fs.readFileSync(bundlePath, "utf8");
324
+ } catch (cause) {
325
+ throw new WrapperTransportError(
326
+ "INJECTED_BUNDLE_MISSING",
327
+ `Could not read the UI Bridge injected runtime bundle at '${bundlePath}'. Ensure @qontinui/ui-bridge is built (the IIFE is emitted by its tsup build).`,
328
+ { cause }
329
+ );
330
+ }
331
+ return cachedBundle;
332
+ }
333
+ var InjectedTransport = class extends HeadlessTransport {
334
+ injected;
335
+ constructor(config, registry) {
336
+ const raw = config.options ?? {};
337
+ const headed = raw["headed"] === true;
338
+ super(config, registry, { kind: "injected", headless: !headed });
339
+ this.injected = {
340
+ headed,
341
+ readyTimeoutMs: typeof raw["readyTimeoutMs"] === "number" ? raw["readyTimeoutMs"] : 3e4,
342
+ waitForSettle: raw["waitForSettle"] !== false,
343
+ settleQuietMs: typeof raw["settleQuietMs"] === "number" ? raw["settleQuietMs"] : void 0,
344
+ settleTimeoutMs: typeof raw["settleTimeoutMs"] === "number" ? raw["settleTimeoutMs"] : void 0,
345
+ expectSelector: typeof raw["expectSelector"] === "string" && raw["expectSelector"].length > 0 ? raw["expectSelector"] : void 0,
346
+ authToken: typeof raw["authToken"] === "string" ? raw["authToken"] : void 0,
347
+ registrationMetadata: isRegistrationMetadata(raw["registrationMetadata"]) ? raw["registrationMetadata"] : void 0,
348
+ appId: typeof raw["appId"] === "string" ? raw["appId"] : void 0,
349
+ appName: typeof raw["appName"] === "string" ? raw["appName"] : void 0,
350
+ tabId: typeof raw["tabId"] === "string" ? raw["tabId"] : void 0
351
+ };
352
+ }
353
+ /**
354
+ * Build the `__uiBridgeInjectedConfig` injected ahead of the bundle, or null
355
+ * if there's nothing to configure. Carries the relay fields (Variant B only,
356
+ * when `uiBridgeBase` is set) AND the settle-tuning fields (both variants).
357
+ */
358
+ injectedConfig() {
359
+ const cfg = {};
360
+ const base = this.options.uiBridgeBase;
361
+ if (base) {
362
+ cfg.uiBridgeBase = base;
363
+ if (this.injected.authToken) cfg.authToken = this.injected.authToken;
364
+ if (this.injected.registrationMetadata)
365
+ cfg.registrationMetadata = this.injected.registrationMetadata;
366
+ if (this.injected.appId) cfg.appId = this.injected.appId;
367
+ if (this.injected.appName) cfg.appName = this.injected.appName;
368
+ if (this.injected.tabId) cfg.tabId = this.injected.tabId;
369
+ }
370
+ if (this.injected.settleQuietMs !== void 0)
371
+ cfg.settleQuietMs = this.injected.settleQuietMs;
372
+ if (this.injected.settleTimeoutMs !== void 0)
373
+ cfg.settleTimeoutMs = this.injected.settleTimeoutMs;
374
+ if (this.injected.expectSelector !== void 0)
375
+ cfg.expectSelector = this.injected.expectSelector;
376
+ return Object.keys(cfg).length > 0 ? cfg : null;
377
+ }
378
+ async buildInitScripts() {
379
+ const scripts = [];
380
+ const cfg = this.injectedConfig();
381
+ if (cfg) {
382
+ scripts.push(`window.__uiBridgeInjectedConfig = ${JSON.stringify(cfg)};`);
383
+ }
384
+ scripts.push(loadInjectedBundle());
385
+ return scripts;
386
+ }
387
+ async afterLaunch(page) {
388
+ try {
389
+ await page.waitForFunction(
390
+ () => window.__uiBridgeInjected?.ready === true,
391
+ void 0,
392
+ { timeout: this.injected.readyTimeoutMs }
393
+ );
394
+ } catch (cause) {
395
+ throw new WrapperTransportError(
396
+ "INJECTED_RUNTIME_NOT_READY",
397
+ `The injected UI Bridge runtime did not report ready within ${this.injected.readyTimeoutMs}ms. The bundle may have failed to evaluate (check page console / CSP) or the page never reached DOMContentLoaded.`,
398
+ { cause, retryable: true }
399
+ );
400
+ }
401
+ if (this.injected.waitForSettle) {
402
+ let state;
403
+ try {
404
+ await page.waitForFunction(
405
+ () => window.__uiBridgeInjected?.settled === true,
406
+ void 0,
407
+ { timeout: this.injected.readyTimeoutMs }
408
+ );
409
+ state = await page.evaluate(() => {
410
+ const api = window.__uiBridgeInjected;
411
+ return {
412
+ settled: api?.settled === true,
413
+ settledByTimeout: api?.settledByTimeout === true,
414
+ expectSatisfied: api?.expectSatisfied === true,
415
+ elementCount: api?.elementCount ?? 0
416
+ };
417
+ });
418
+ } catch (cause) {
419
+ throw new WrapperTransportError(
420
+ "INJECTED_RUNTIME_NOT_SETTLED",
421
+ `The injected UI Bridge runtime did not report settled within ${this.injected.readyTimeoutMs}ms. The page kept mutating past its settle cap, or the realm was torn down. Pass options.waitForSettle=false to gate on ready only, or raise options.settleTimeoutMs / readyTimeoutMs.`,
422
+ { cause, retryable: true }
423
+ );
424
+ }
425
+ if (state.settledByTimeout && !state.expectSatisfied) {
426
+ const sel = this.injected.expectSelector;
427
+ throw new WrapperTransportError(
428
+ "INJECTED_EXPECT_SELECTOR_UNMET",
429
+ sel ? `The injected runtime settled at its cap without the expected control (selector '${sel}') appearing \u2014 ${state.elementCount} element(s) were registered, but none matched. The control may mount slower than the settle cap (raise options.settleTimeoutMs), the selector may be wrong, or the inject failed. Treat as BLOCKED/UNVERIFIED, not a clean page.` : `The injected runtime settled at its cap with an empty registry (0 elements). The page never rendered interactive content within the settle cap, or the inject failed. Raise options.settleTimeoutMs for a slow page; otherwise treat as BLOCKED/UNVERIFIED.`,
430
+ { retryable: true }
431
+ );
432
+ }
433
+ }
434
+ }
435
+ async buildContext() {
436
+ if (!this.tab) {
437
+ throw new WrapperTransportError(
438
+ "NOT_READY",
439
+ `Transport 'injected' is not ready; call ready() before dispatch`
440
+ );
441
+ }
442
+ const { page, context: browserContext, browser, uiBridgeRegistered, tabId } = this.tab;
443
+ const execute = (action, payload) => page.evaluate(
444
+ (args) => window.__uiBridgeInjected.execute(args[0], args[1]),
445
+ [action, payload]
446
+ );
447
+ const settleState = () => page.evaluate(() => {
448
+ const api = window.__uiBridgeInjected;
449
+ return {
450
+ settled: api?.settled === true,
451
+ elementCount: api?.elementCount ?? 0,
452
+ settledByTimeout: api?.settledByTimeout === true,
453
+ expectSatisfied: api?.expectSatisfied === true
454
+ };
455
+ });
456
+ const whenSettled = (timeoutMs) => page.evaluate(
457
+ (ms) => {
458
+ const api = window.__uiBridgeInjected;
459
+ if (api?.whenSettled) return api.whenSettled(ms ?? void 0);
460
+ return Promise.resolve({
461
+ settled: api?.settled === true,
462
+ elementCount: api?.elementCount ?? 0,
463
+ settledByTimeout: api?.settledByTimeout === true,
464
+ expectSatisfied: api?.expectSatisfied === true
465
+ });
466
+ },
467
+ timeoutMs ?? null
468
+ );
469
+ return {
470
+ kind: "injected",
471
+ page,
472
+ browserContext,
473
+ browser,
474
+ uiBridgeRegistered,
475
+ ready: true,
476
+ tabId,
477
+ settleState,
478
+ whenSettled,
479
+ execute,
480
+ find: (criteria) => execute("find", criteria ?? {}),
481
+ act: (id, request) => execute("executeElementAction", { id, request }),
482
+ snapshot: (options) => execute("getControlSnapshot", options ?? {}),
483
+ assert: (spec) => execute("aiAssert", spec)
484
+ };
485
+ }
486
+ };
487
+ function isRegistrationMetadata(value) {
488
+ if (!value || typeof value !== "object") return false;
489
+ const v = value;
490
+ return typeof v.userId === "string" && typeof v.sessionId === "string";
491
+ }
492
+
493
+ // src/transports/live.ts
494
+ var LiveSessionTransport = class extends BaseTransport {
495
+ kind = "live";
496
+ url;
497
+ appId;
498
+ appName;
499
+ opts;
500
+ wsCtor;
501
+ ws = null;
502
+ ackResolvers = null;
503
+ constructor(config, registry, injected) {
504
+ super(registry);
505
+ if (!config.runnerUrl) {
506
+ throw new WrapperTransportError("INVALID_CONFIG", `Transport kind 'live' requires runnerUrl`);
507
+ }
508
+ this.url = config.runnerUrl;
509
+ this.appId = config.appId;
510
+ this.appName = config.appName;
511
+ this.opts = config.options ?? {};
512
+ const fromInjection = injected?.webSocketCtor;
513
+ const fromGlobal = typeof globalThis.WebSocket === "function" ? globalThis.WebSocket : void 0;
514
+ const resolved = fromInjection ?? fromGlobal;
515
+ if (!resolved) {
516
+ throw new WrapperTransportError(
517
+ "NO_WEBSOCKET",
518
+ `No WebSocket constructor available. Provide one via the second constructor arg or run in an environment with global WebSocket.`
519
+ );
520
+ }
521
+ this.wsCtor = resolved;
522
+ }
523
+ async onReady() {
524
+ const ws = new this.wsCtor(this.url);
525
+ this.ws = ws;
526
+ ws.addEventListener("message", (ev) => this.handleMessage(ev.data));
527
+ ws.addEventListener("close", () => this.handleClose());
528
+ ws.addEventListener("error", (ev) => this.handleError(ev));
529
+ await new Promise((resolve, reject) => {
530
+ const onOpen = () => {
531
+ try {
532
+ const frame = {
533
+ type: "register",
534
+ transport: "websocket",
535
+ appId: this.appId,
536
+ appName: this.appName,
537
+ appType: this.opts.appType ?? "wrapper"
538
+ };
539
+ if (this.opts.framework !== void 0) frame.framework = this.opts.framework;
540
+ if (this.opts.version !== void 0) frame.version = this.opts.version;
541
+ if (this.opts.capabilities !== void 0) frame.capabilities = this.opts.capabilities;
542
+ if (this.opts.origin !== void 0) frame.origin = this.opts.origin;
543
+ if (this.opts.pageUrl !== void 0) frame.pageUrl = this.opts.pageUrl;
544
+ ws.send(JSON.stringify(frame));
545
+ } catch (err) {
546
+ reject(err instanceof Error ? err : new Error(String(err)));
547
+ return;
548
+ }
549
+ const timeoutMs = this.opts.handshakeTimeoutMs ?? 1e4;
550
+ const timer = setTimeout(() => {
551
+ this.ackResolvers = null;
552
+ reject(
553
+ new WrapperTransportError(
554
+ "HANDSHAKE_TIMEOUT",
555
+ `Did not receive register ack within ${timeoutMs}ms`
556
+ )
557
+ );
558
+ }, timeoutMs);
559
+ this.ackResolvers = { resolve, reject, timer };
560
+ };
561
+ ws.addEventListener("open", onOpen);
562
+ });
563
+ }
564
+ async onClose() {
565
+ const ws = this.ws;
566
+ this.ws = null;
567
+ if (this.ackResolvers) {
568
+ clearTimeout(this.ackResolvers.timer);
569
+ this.ackResolvers.reject(
570
+ new WrapperTransportError("TRANSPORT_CLOSED", "Transport closed during handshake")
571
+ );
572
+ this.ackResolvers = null;
573
+ }
574
+ if (ws) {
575
+ try {
576
+ ws.close();
577
+ } catch {
578
+ }
579
+ }
580
+ }
581
+ async buildContext() {
582
+ return { kind: "live", commandId: null };
583
+ }
584
+ handleMessage(data) {
585
+ let frame;
586
+ try {
587
+ const text = typeof data === "string" ? data : String(data);
588
+ frame = JSON.parse(text);
589
+ } catch {
590
+ return;
591
+ }
592
+ switch (frame.type) {
593
+ case "ack":
594
+ case "registered": {
595
+ const f = frame;
596
+ if (!this.ackResolvers) return;
597
+ clearTimeout(this.ackResolvers.timer);
598
+ if (f.ok === false) {
599
+ const err = new WrapperTransportError(
600
+ f.error?.code ?? "REGISTER_FAILED",
601
+ f.error?.message ?? "Runner refused registration"
602
+ );
603
+ this.ackResolvers.reject(err);
604
+ } else {
605
+ this.ackResolvers.resolve();
606
+ }
607
+ this.ackResolvers = null;
608
+ return;
609
+ }
610
+ case "command": {
611
+ const f = frame;
612
+ void this.handleCommand(f);
613
+ return;
614
+ }
615
+ default:
616
+ return;
617
+ }
618
+ }
619
+ async handleCommand(frame) {
620
+ const ctx = { kind: "live", commandId: frame.commandId };
621
+ let response;
622
+ try {
623
+ const result = await this.registry.dispatch(frame.action, frame.payload, ctx);
624
+ response = {
625
+ type: "response",
626
+ commandId: frame.commandId,
627
+ success: true,
628
+ result
629
+ };
630
+ } catch (err) {
631
+ const code = err instanceof WrapperTransportError ? err.code : "HANDLER_ERROR";
632
+ const retryable = err instanceof WrapperTransportError ? err.retryable : false;
633
+ const message = err instanceof Error ? err.message : String(err);
634
+ response = {
635
+ type: "response",
636
+ commandId: frame.commandId,
637
+ success: false,
638
+ error: { code, message, retryable }
639
+ };
640
+ }
641
+ try {
642
+ this.ws?.send(JSON.stringify(response));
643
+ } catch {
644
+ }
645
+ }
646
+ handleClose() {
647
+ if (this._status === "closed") return;
648
+ this.setStatus("closed");
649
+ if (this.ackResolvers) {
650
+ clearTimeout(this.ackResolvers.timer);
651
+ this.ackResolvers.reject(
652
+ new WrapperTransportError("DISCONNECTED", "WebSocket closed before ack")
653
+ );
654
+ this.ackResolvers = null;
655
+ }
656
+ }
657
+ handleError(ev) {
658
+ if (this.ackResolvers) {
659
+ clearTimeout(this.ackResolvers.timer);
660
+ const message = this.extractErrorMessage(ev);
661
+ this.ackResolvers.reject(
662
+ new WrapperTransportError("WEBSOCKET_ERROR", message, { retryable: true })
663
+ );
664
+ this.ackResolvers = null;
665
+ } else {
666
+ this.setStatus("error");
667
+ }
668
+ }
669
+ extractErrorMessage(ev) {
670
+ if (ev && typeof ev === "object" && "message" in ev) {
671
+ const m = ev.message;
672
+ if (typeof m === "string") return m;
673
+ }
674
+ if (ev instanceof Error) return ev.message;
675
+ return "WebSocket error";
676
+ }
677
+ };
678
+
679
+ // src/create-transport.ts
680
+ function createTransport(config) {
681
+ switch (config.kind) {
682
+ case "api":
683
+ return new ApiTransport(config);
684
+ case "headless":
685
+ return new HeadlessTransport(config);
686
+ case "headed":
687
+ return new HeadedTransport(config);
688
+ case "injected":
689
+ return new InjectedTransport(config);
690
+ case "live": {
691
+ const opts = config.options ?? {};
692
+ const injected = typeof opts.webSocketCtor === "function" ? { webSocketCtor: opts.webSocketCtor } : void 0;
693
+ return new LiveSessionTransport(config, void 0, injected);
694
+ }
695
+ default: {
696
+ const kind = config.kind ?? "<missing>";
697
+ throw new WrapperTransportError("UNKNOWN_TRANSPORT", `Unknown transport kind '${kind}'`);
698
+ }
699
+ }
700
+ }
701
+
702
+ // src/cli-args.ts
703
+ var COMMON_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "--quiet"]);
704
+ function isFlagShaped(value) {
705
+ return value.startsWith("--");
706
+ }
707
+ var ArgReader = class {
708
+ argv;
709
+ error;
710
+ /**
711
+ * @param argv Already sliced past `node script`.
712
+ * @param known All flags the bin recognizes (union the bin's set with {@link COMMON_FLAGS}).
713
+ * @param error Factory producing the bin's domain error type.
714
+ */
715
+ constructor(argv, known, error) {
716
+ this.argv = argv;
717
+ this.error = error;
718
+ for (const arg of argv) {
719
+ if (isFlagShaped(arg) && !known.has(arg)) {
720
+ throw error(`Unknown flag: ${arg}`);
721
+ }
722
+ }
723
+ }
724
+ /** True if `name` appears as a bare boolean flag. */
725
+ has(name) {
726
+ return this.argv.includes(name);
727
+ }
728
+ /**
729
+ * Value following the value-flag `name`, or `null` when the flag is absent OR
730
+ * has no following token (the caller defaults it). Throws when the following
731
+ * token is flag-shaped — the swallow this kit exists to kill.
732
+ */
733
+ value(name) {
734
+ const i = this.argv.indexOf(name);
735
+ if (i < 0 || i + 1 >= this.argv.length) return null;
736
+ const raw = this.argv[i + 1];
737
+ if (isFlagShaped(raw)) {
738
+ throw this.error(
739
+ `${name} expects a value but got the flag '${raw}' \u2014 did you omit ${name}'s argument?`
740
+ );
741
+ }
742
+ return raw;
743
+ }
744
+ };
745
+ function makeLogger(prefix, quiet) {
746
+ if (quiet) return () => {
747
+ };
748
+ return (m) => process.stderr.write(`${prefix} ${m}
749
+ `) ;
750
+ }
751
+
752
+ // src/login-drive.ts
753
+ var isCognito = (u) => /auth\.qontinui\.io|amazoncognito\.com|\/oauth2\//i.test(u);
754
+ var pathOf = (u) => {
755
+ try {
756
+ return new URL(u).pathname;
757
+ } catch {
758
+ return "";
759
+ }
760
+ };
761
+ var isSuccessPath = (u, success) => pathOf(u).includes(success);
762
+ var isAppLoginPath = (u) => /\/login(\b|\/|$)/.test(pathOf(u)) && !isCognito(u);
763
+ async function scrapeErrorCard(page) {
764
+ try {
765
+ const alerts = page.locator(
766
+ '[role="alert"], #loginErrorMessage, .error-message, [class*="error" i], [data-testid*="error" i]'
767
+ );
768
+ const an = await alerts.count();
769
+ for (let i = 0; i < an; i++) {
770
+ const el = alerts.nth(i);
771
+ if (await el.isVisible().catch(() => false)) {
772
+ const t = (await el.innerText().catch(() => "")).trim();
773
+ if (t) return t.slice(0, 500);
774
+ }
775
+ }
776
+ } catch {
777
+ }
778
+ return null;
779
+ }
780
+ async function loginDrive(page, { email, password, timeoutMs, log = () => {
781
+ } }) {
782
+ log(`landed ${page.url()}`);
783
+ const emailBtn = page.getByRole("button", { name: /continue with email/i }).or(page.getByText(/continue with email/i));
784
+ await emailBtn.first().waitFor({ state: "visible", timeout: 15e3 });
785
+ await emailBtn.first().click();
786
+ await page.waitForURL(
787
+ (u) => {
788
+ const s = u.toString();
789
+ return isCognito(s) || !isAppLoginPath(s) && !/\/auth\/callback/.test(pathOf(s));
790
+ },
791
+ { timeout: timeoutMs }
792
+ );
793
+ if (isCognito(page.url())) {
794
+ await page.waitForLoadState("domcontentloaded");
795
+ log(`cognito ${page.url()}`);
796
+ const fillFirst = async (sels, val, what) => {
797
+ for (const s of sels) {
798
+ const loc = page.locator(s);
799
+ const n = await loc.count().catch(() => 0);
800
+ for (let i = 0; i < n; i++) {
801
+ const el = loc.nth(i);
802
+ if (await el.isVisible().catch(() => false)) {
803
+ await el.fill(val, { timeout: 1e4 });
804
+ log(`filled ${what} via ${s} [visible #${i}]`);
805
+ return;
806
+ }
807
+ }
808
+ }
809
+ throw new Error(`Cognito ${what} field (visible) not found (selectors: ${sels.join(", ")})`);
810
+ };
811
+ await fillFirst(
812
+ [
813
+ "#signInFormUsername",
814
+ 'input[name="username"]',
815
+ 'input[type="email"]',
816
+ 'input[autocomplete="username"]'
817
+ ],
818
+ email,
819
+ "email"
820
+ );
821
+ await fillFirst(
822
+ [
823
+ "#signInFormPassword",
824
+ 'input[name="password"]',
825
+ 'input[type="password"]',
826
+ 'input[autocomplete="current-password"]'
827
+ ],
828
+ password,
829
+ "password"
830
+ );
831
+ const submitLoc = page.locator(
832
+ 'input[name="signInSubmitButton"], button[type="submit"], input[type="submit"], [name="signInSubmitButton"]'
833
+ );
834
+ let clicked = false;
835
+ const sn = await submitLoc.count().catch(() => 0);
836
+ for (let i = 0; i < sn; i++) {
837
+ const el = submitLoc.nth(i);
838
+ if (await el.isVisible().catch(() => false)) {
839
+ await el.click();
840
+ clicked = true;
841
+ log(`clicked submit [visible #${i}]`);
842
+ break;
843
+ }
844
+ }
845
+ if (!clicked) {
846
+ await page.getByRole("button", { name: /sign in|log in|continue|submit/i }).first().click();
847
+ log("clicked submit [role fallback]");
848
+ }
849
+ try {
850
+ await page.waitForURL(
851
+ (u) => {
852
+ const s = u.toString();
853
+ return !isCognito(s) && !/\/auth\/callback/.test(pathOf(s));
854
+ },
855
+ { timeout: timeoutMs }
856
+ );
857
+ } catch {
858
+ const errorText2 = await scrapeErrorCard(page);
859
+ const finalUrl2 = page.url();
860
+ log(`final ${finalUrl2} (stalled)`);
861
+ return { ok: false, finalUrl: finalUrl2, landingPath: pathOf(finalUrl2), errorText: errorText2 };
862
+ }
863
+ }
864
+ await page.waitForLoadState("networkidle").catch(() => {
865
+ });
866
+ await page.waitForFunction(
867
+ () => window.__uiBridgeInjected?.ready === true,
868
+ { timeout: 15e3 }
869
+ ).catch(() => {
870
+ });
871
+ const finalUrl = page.url();
872
+ log(`final ${finalUrl}`);
873
+ const landingPath = await page.evaluate(() => location.pathname).catch(() => pathOf(finalUrl));
874
+ const ok = !isAppLoginPath(finalUrl) && !isCognito(finalUrl) && !/\/auth\/callback/.test(pathOf(finalUrl));
875
+ const errorText = ok ? null : await scrapeErrorCard(page);
876
+ return { ok, finalUrl, landingPath, errorText };
877
+ }
878
+
879
+ // src/login-web-cli.ts
880
+ var USAGE = `ui-bridge-login-web \u2014 automated web login via the UI Bridge injected transport
881
+
882
+ Required (one of):
883
+ --email <e> / --password <p> Credentials. Falls back to env
884
+ UIB_LOGIN_EMAIL / UIB_LOGIN_PASSWORD.
885
+
886
+ Options:
887
+ --url <pageUrl> App login URL (default https://qontinui.io/login).
888
+ Prefer a ?next=<urlencoded-path> form so the
889
+ authed landing is deterministic.
890
+ --success <pathSubstring> Pathname substring the authed landing must
891
+ contain (default /dashboard). Matched against the
892
+ PATHNAME only \u2014 query/fragment excluded.
893
+ --timeout <ms> Per-redirect-hop wait budget (default 60000).
894
+ --headed Launch a visible window (default headless).
895
+ --post-login-click <css> Click this selector ONCE on the authed landing
896
+ (e.g. [data-testid='co-pilot-consent-allow']).
897
+ Non-fatal when the target never appears.
898
+ --expect-text <comma-list> Assert the authed page's body text contains EVERY
899
+ comma-separated entry. Missing entries fail the
900
+ exit code; the result JSON lists expectFound /
901
+ expectMissing. Matched case-sensitively.
902
+ --scroll-to <text> Before screenshotting, scroll the first element
903
+ containing this text into view (non-fatal if absent).
904
+ --screenshot <path> Write a full-page PNG of the authed landing to
905
+ <path> (captured BEFORE the --expect-text check, so
906
+ a failing assertion still leaves a diagnostic image).
907
+ --keep-open On success, park the authed session until SIGINT/
908
+ SIGTERM instead of closing the browser.
909
+ --quiet Suppress human-readable stderr logs (the JSON
910
+ result line still prints).
911
+ --help, -h Print this help and exit.
912
+
913
+ Prerequisites (packaged bin): the optional @qontinui/ui-bridge-headless peer must
914
+ be installed AND Chromium available (run \`npx playwright install chromium\` once,
915
+ or set PLAYWRIGHT_BROWSERS_PATH). Git Bash callers: prefix MSYS_NO_PATHCONV=1 so
916
+ a leading-slash --success value is not rewritten into a Windows path.
917
+
918
+ Examples:
919
+ ui-bridge-login-web --url "https://qontinui.io/login?next=%2Fbuild%2Fworkflows" \\
920
+ --success /build/workflows
921
+ ui-bridge-login-web --url "https://qontinui.io/login?next=%2Fco-pilot" \\
922
+ --success /co-pilot --post-login-click "[data-testid='co-pilot-consent-allow']" --keep-open
923
+ ui-bridge-login-web --url "https://qontinui.io/login?next=%2Foperations" \\
924
+ --success /operations --expect-text "option2-actions-outage-drill,metric_threshold" \\
925
+ --screenshot out.png
926
+ `;
927
+ var LoginCliArgError = class extends Error {
928
+ constructor(message) {
929
+ super(message);
930
+ this.name = "LoginCliArgError";
931
+ }
932
+ };
933
+ function parseArgs(argv) {
934
+ const mkError = (m) => new LoginCliArgError(m);
935
+ const reader = new ArgReader(argv, KNOWN_FLAGS, mkError);
936
+ const valueOf = (name) => reader.value(name);
937
+ const has = (name) => reader.has(name);
938
+ const help = has("--help") || has("-h");
939
+ const timeoutRaw = valueOf("--timeout");
940
+ const timeoutMs = timeoutRaw === null ? 6e4 : Number.parseInt(timeoutRaw, 10);
941
+ if (!help && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
942
+ throw new LoginCliArgError(`--timeout expects a positive integer (got ${timeoutRaw})`);
943
+ }
944
+ const args = {
945
+ url: valueOf("--url") ?? "https://qontinui.io/login",
946
+ email: valueOf("--email") ?? process.env.UIB_LOGIN_EMAIL ?? "",
947
+ password: valueOf("--password") ?? process.env.UIB_LOGIN_PASSWORD ?? "",
948
+ success: valueOf("--success") ?? "/dashboard",
949
+ timeoutMs,
950
+ headed: has("--headed"),
951
+ postClick: valueOf("--post-login-click"),
952
+ expectText: (valueOf("--expect-text") ?? "").split(",").map((s) => s.trim()).filter((s) => s.length > 0),
953
+ scrollToText: valueOf("--scroll-to"),
954
+ screenshotPath: valueOf("--screenshot"),
955
+ keepOpen: has("--keep-open"),
956
+ quiet: has("--quiet"),
957
+ help
958
+ };
959
+ validateArgs(args);
960
+ return args;
961
+ }
962
+ var KNOWN_FLAGS = /* @__PURE__ */ new Set([
963
+ "--url",
964
+ "--email",
965
+ "--password",
966
+ "--success",
967
+ "--timeout",
968
+ "--headed",
969
+ "--post-login-click",
970
+ "--expect-text",
971
+ "--scroll-to",
972
+ "--screenshot",
973
+ "--keep-open",
974
+ ...COMMON_FLAGS
975
+ ]);
976
+ function validateArgs(args) {
977
+ if (args.help) return;
978
+ if (!/^https?:\/\//i.test(args.url)) {
979
+ throw new LoginCliArgError(`--url must start with http:// or https:// (got ${args.url})`);
980
+ }
981
+ if (!args.email || !args.password) {
982
+ throw new LoginCliArgError(
983
+ "need --email/--password or env UIB_LOGIN_EMAIL / UIB_LOGIN_PASSWORD"
984
+ );
985
+ }
986
+ }
987
+ async function main() {
988
+ let args;
989
+ try {
990
+ args = parseArgs(process.argv.slice(2));
991
+ } catch (err) {
992
+ if (err instanceof LoginCliArgError) {
993
+ process.stderr.write(`${err.message}
994
+
995
+ ${USAGE}`);
996
+ process.exit(2);
997
+ }
998
+ throw err;
999
+ }
1000
+ if (args.help) {
1001
+ process.stdout.write(USAGE);
1002
+ process.exit(0);
1003
+ }
1004
+ const { url, email, password, success, timeoutMs, headed, postClick, expectText, scrollToText, screenshotPath } = args;
1005
+ const log = makeLogger("[login-web]", args.quiet);
1006
+ const transport = createTransport({
1007
+ kind: "injected",
1008
+ options: { targetUrl: url, waitForSettle: false, readyTimeoutMs: 45e3, headed }
1009
+ });
1010
+ transport.register("drive", async (_p, ctx) => {
1011
+ const page = ctx.page;
1012
+ const r = await loginDrive(page, { email, password, timeoutMs, log });
1013
+ if (r.ok && !isSuccessPath(page.url(), success)) {
1014
+ await page.waitForURL((u) => isSuccessPath(u.toString(), success), { timeout: 1e4 }).catch(() => {
1015
+ });
1016
+ }
1017
+ const finalUrl = page.url();
1018
+ log(`final ${finalUrl}`);
1019
+ await page.waitForFunction(() => window.__uiBridgeInjected?.ready === true, {
1020
+ timeout: 15e3
1021
+ }).catch(() => {
1022
+ });
1023
+ let snap = null;
1024
+ try {
1025
+ snap = await ctx.snapshot();
1026
+ } catch {
1027
+ }
1028
+ const uiBridgeRoute = snap?.route ?? null;
1029
+ const landingPath = uiBridgeRoute ?? (finalUrl === r.finalUrl ? r.landingPath : pathOf(finalUrl));
1030
+ const onAppLoginPage = isAppLoginPath(finalUrl);
1031
+ const stillOnCognito = isCognito(finalUrl);
1032
+ const ok = !onAppLoginPage && !stillOnCognito && landingPath.includes(success);
1033
+ let errorText = r.errorText;
1034
+ if (!ok && !errorText) {
1035
+ errorText = await scrapeErrorCard(page);
1036
+ }
1037
+ let postLoginClicked = null;
1038
+ if (ok && postClick) {
1039
+ postLoginClicked = false;
1040
+ try {
1041
+ const target = page.locator(postClick).first();
1042
+ await target.waitFor({ state: "visible", timeout: 2e4 });
1043
+ await target.click();
1044
+ postLoginClicked = true;
1045
+ log(`post-login click: ${postClick}`);
1046
+ } catch {
1047
+ log(`post-login click target never visible (non-fatal): ${postClick}`);
1048
+ }
1049
+ }
1050
+ let screenshotWritten = null;
1051
+ if (ok && screenshotPath) {
1052
+ try {
1053
+ if (scrollToText) {
1054
+ await page.getByText(scrollToText).first().scrollIntoViewIfNeeded({ timeout: 5e3 }).catch(() => log(`scroll-to target not found (non-fatal): ${scrollToText}`));
1055
+ }
1056
+ await page.screenshot({ path: screenshotPath, fullPage: true });
1057
+ screenshotWritten = screenshotPath;
1058
+ log(`screenshot written: ${screenshotPath}`);
1059
+ } catch (err) {
1060
+ log(`screenshot failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
1061
+ }
1062
+ }
1063
+ let expectFound;
1064
+ let expectMissing;
1065
+ if (ok && expectText.length > 0) {
1066
+ const body = await page.evaluate(() => document.body?.innerText ?? "").catch(() => "");
1067
+ expectFound = expectText.filter((t) => body.includes(t));
1068
+ expectMissing = expectText.filter((t) => !body.includes(t));
1069
+ if (expectMissing.length > 0) log(`expect-text missing: ${expectMissing.join(", ")}`);
1070
+ }
1071
+ const finalOk = ok && (expectMissing?.length ?? 0) === 0;
1072
+ return {
1073
+ ok: finalOk,
1074
+ finalUrl,
1075
+ landingPath,
1076
+ onAppLoginPage,
1077
+ stillOnCognito,
1078
+ errorText,
1079
+ uiBridgeRoute,
1080
+ uiBridgeRegistered: snap?.registration?.totalRegistered ?? null,
1081
+ postLoginClicked,
1082
+ expectFound,
1083
+ expectMissing,
1084
+ screenshotPath: screenshotPath ? screenshotWritten : void 0
1085
+ };
1086
+ });
1087
+ let result;
1088
+ let code;
1089
+ try {
1090
+ await transport.ready();
1091
+ result = await transport.dispatch("drive");
1092
+ code = result && result.ok ? 0 : 1;
1093
+ } catch (err) {
1094
+ result = { ok: false, error: err instanceof Error ? err.message : String(err) };
1095
+ code = 1;
1096
+ }
1097
+ process.stdout.write(JSON.stringify(result) + "\n");
1098
+ if (args.keepOpen && result && result.ok) {
1099
+ log("--keep-open: authed session parked; press Ctrl+C to exit");
1100
+ const stop = async () => {
1101
+ await transport.close().catch(() => {
1102
+ });
1103
+ process.exit(0);
1104
+ };
1105
+ process.on("SIGINT", () => void stop());
1106
+ process.on("SIGTERM", () => void stop());
1107
+ setInterval(() => {
1108
+ }, 1 << 30);
1109
+ return;
1110
+ }
1111
+ await transport.close().catch(() => {
1112
+ });
1113
+ process.exit(code);
1114
+ }
1115
+ var isMain = (() => {
1116
+ try {
1117
+ return process.argv[1] === url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('login-web-cli.cjs', document.baseURI).href)));
1118
+ } catch {
1119
+ return false;
1120
+ }
1121
+ })();
1122
+ if (isMain) {
1123
+ void main().catch((err) => {
1124
+ const msg = err instanceof Error ? err.message : String(err);
1125
+ process.stderr.write(`[login-web] fatal: ${msg}
1126
+ `);
1127
+ process.exit(1);
1128
+ });
1129
+ }
1130
+
1131
+ exports.LoginCliArgError = LoginCliArgError;
1132
+ exports.USAGE = USAGE;
1133
+ exports.parseArgs = parseArgs;
1134
+ exports.validateArgs = validateArgs;
1135
+ //# sourceMappingURL=login-web-cli.cjs.map
1136
+ //# sourceMappingURL=login-web-cli.cjs.map