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